diff --git a/.gitignore b/.gitignore index cfd789ec1c..27196b5528 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +venv/ .DS_Store .tags .ipynb_checkpoints diff --git a/Dockerfile.openpilot b/Dockerfile.openpilot index f4c667fa03..0248d5acb0 100644 --- a/Dockerfile.openpilot +++ b/Dockerfile.openpilot @@ -4,32 +4,44 @@ ENV PYTHONUNBUFFERED 1 RUN apt-get update && apt-get install -y \ autoconf \ build-essential \ - clang \ - wget \ bzip2 \ + clang \ git \ + libarchive-dev \ + libavcodec-dev \ + libavdevice-dev \ + libavfilter-dev \ + libavresample-dev \ + libavutil-dev \ + libffi-dev \ libglib2.0-0 \ + libssl-dev \ + libswscale-dev \ libtool \ - python-pip \ - libzmq5-dev \ - libffi-dev \ libusb-1.0-0 \ - libssl-dev \ + 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 diff --git a/Pipfile b/Pipfile new file mode 100644 index 0000000000..614968710c --- /dev/null +++ b/Pipfile @@ -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" diff --git a/Pipfile.lock b/Pipfile.lock new file mode 100644 index 0000000000..e4623df10a --- /dev/null +++ b/Pipfile.lock @@ -0,0 +1,2810 @@ +{ + "_meta": { + "hash": { + "sha256": "72c6a6eac19abf85ca5f272d04761f8336150d5bec599423c4b16891c99cb0bf" + }, + "pipfile-spec": 6, + "requires": { + "python_version": "2.7" + }, + "sources": [ + { + "name": "pypi", + "url": "https://pypi.org/simple", + "verify_ssl": true + } + ] + }, + "default": { + "asn1crypto": { + "hashes": [ + "sha256:2f1adbb7546ed199e3c90ef23ec95c5cf3585bac7d11fb7eb562a3fe89c64e87", + "sha256:9d5c20441baf0cb60a4ac34cc447c6c189024b6b4c6cd7877034f4965c464e49" + ], + "version": "==0.24.0" + }, + "astroid": { + "hashes": [ + "sha256:87de48a92e29cedf7210ffa853d11441e7ad94cb47bacd91b023499b51cbc756", + "sha256:d25869fc7f44f1d9fb7d24fd7ea0639656f5355fc3089cd1f3d18c6ec6b124c7" + ], + "version": "==1.6.6" + }, + "atomicwrites": { + "hashes": [ + "sha256:03472c30eb2c5d1ba9227e4c2ca66ab8287fbfbbda3888aa93dc2e28fc6811b4", + "sha256:75a9445bac02d8d058d5e1fe689654ba5a6556a1dfd8ce6ec55a0ed79866cfa6" + ], + "index": "pypi", + "version": "==1.3.0" + }, + "backports.functools-lru-cache": { + "hashes": [ + "sha256:9d98697f088eb1b0fa451391f91afb5e3ebde16bbdb272819fd091151fda4f1a", + "sha256:f0b0e4eba956de51238e17573b7087e852dfe9854afd2e9c873f73fc0ca0a6dd" + ], + "markers": "python_version < '3.2'", + "version": "==1.5" + }, + "certifi": { + "hashes": [ + "sha256:59b7658e26ca9c7339e00f8f4636cdfe59d34fa37b9b04f6f9e9926b3cece1a5", + "sha256:b26104d6835d1f5e49452a26eb2ff87fe7090b89dfcaee5ea2212697e1e1d7ae" + ], + "version": "==2019.3.9" + }, + "cffi": { + "hashes": [ + "sha256:041c81822e9f84b1d9c401182e174996f0bae9991f33725d059b771744290774", + "sha256:046ef9a22f5d3eed06334d01b1e836977eeef500d9b78e9ef693f9380ad0b83d", + "sha256:066bc4c7895c91812eff46f4b1c285220947d4aa46fa0a2651ff85f2afae9c90", + "sha256:066c7ff148ae33040c01058662d6752fd73fbc8e64787229ea8498c7d7f4041b", + "sha256:2444d0c61f03dcd26dbf7600cf64354376ee579acad77aef459e34efcb438c63", + "sha256:300832850b8f7967e278870c5d51e3819b9aad8f0a2c8dbe39ab11f119237f45", + "sha256:34c77afe85b6b9e967bd8154e3855e847b70ca42043db6ad17f26899a3df1b25", + "sha256:46de5fa00f7ac09f020729148ff632819649b3e05a007d286242c4882f7b1dc3", + "sha256:4aa8ee7ba27c472d429b980c51e714a24f47ca296d53f4d7868075b175866f4b", + "sha256:4d0004eb4351e35ed950c14c11e734182591465a33e960a4ab5e8d4f04d72647", + "sha256:4e3d3f31a1e202b0f5a35ba3bc4eb41e2fc2b11c1eff38b362de710bcffb5016", + "sha256:50bec6d35e6b1aaeb17f7c4e2b9374ebf95a8975d57863546fa83e8d31bdb8c4", + "sha256:55cad9a6df1e2a1d62063f79d0881a414a906a6962bc160ac968cc03ed3efcfb", + "sha256:5662ad4e4e84f1eaa8efce5da695c5d2e229c563f9d5ce5b0113f71321bcf753", + "sha256:59b4dc008f98fc6ee2bb4fd7fc786a8d70000d058c2bbe2698275bc53a8d3fa7", + "sha256:73e1ffefe05e4ccd7bcea61af76f36077b914f92b76f95ccf00b0c1b9186f3f9", + "sha256:a1f0fd46eba2d71ce1589f7e50a9e2ffaeb739fb2c11e8192aa2b45d5f6cc41f", + "sha256:a2e85dc204556657661051ff4bab75a84e968669765c8a2cd425918699c3d0e8", + "sha256:a5457d47dfff24882a21492e5815f891c0ca35fefae8aa742c6c263dac16ef1f", + "sha256:a8dccd61d52a8dae4a825cdbb7735da530179fea472903eb871a5513b5abbfdc", + "sha256:ae61af521ed676cf16ae94f30fe202781a38d7178b6b4ab622e4eec8cefaff42", + "sha256:b012a5edb48288f77a63dba0840c92d0504aa215612da4541b7b42d849bc83a3", + "sha256:d2c5cfa536227f57f97c92ac30c8109688ace8fa4ac086d19d0af47d134e2909", + "sha256:d42b5796e20aacc9d15e66befb7a345454eef794fdb0737d1af593447c6c8f45", + "sha256:dee54f5d30d775f525894d67b1495625dd9322945e7fee00731952e0368ff42d", + "sha256:e070535507bd6aa07124258171be2ee8dfc19119c28ca94c9dfb7efd23564512", + "sha256:e1ff2748c84d97b065cc95429814cdba39bcbd77c9c85c89344b317dc0d9cbff", + "sha256:ed851c75d1e0e043cbf5ca9a8e1b13c4c90f3fbd863dacb01c0808e2b5204201" + ], + "index": "pypi", + "version": "==1.12.3" + }, + "chardet": { + "hashes": [ + "sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae", + "sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691" + ], + "index": "pypi", + "version": "==3.0.4" + }, + "click": { + "hashes": [ + "sha256:2335065e6395b9e67ca716de5f7526736bfa6ceead690adf616d925bdc622b13", + "sha256:5b94b49521f6456670fdb30cd82a4eca9412788a93fa6dd6df72c94d5a8ff2d7" + ], + "version": "==7.0" + }, + "configparser": { + "hashes": [ + "sha256:8be81d89d6e7b4c0d4e44bcc525845f6da25821de80cb5e06e7e0238a2899e32", + "sha256:da60d0014fd8c55eb48c1c5354352e363e2d30bbf7057e5e171a468390184c75" + ], + "markers": "python_version == '2.7'", + "version": "==3.7.4" + }, + "contextlib2": { + "hashes": [ + "sha256:509f9419ee91cdd00ba34443217d5ca51f5a364a404e1dce9e8979cea969ca48", + "sha256:f5260a6e679d2ff42ec91ec5252f4eeffdcf21053db9113bd0a8e4d953769c00" + ], + "markers": "python_version < '3.2'", + "version": "==0.5.5" + }, + "crcmod": { + "hashes": [ + "sha256:dc7051a0db5f2bd48665a990d3ec1cc305a466a77358ca4492826f41f283601e" + ], + "index": "pypi", + "version": "==1.7" + }, + "cryptography": { + "hashes": [ + "sha256:24b61e5fcb506424d3ec4e18bca995833839bf13c59fc43e530e488f28d46b8c", + "sha256:25dd1581a183e9e7a806fe0543f485103232f940fcfc301db65e630512cce643", + "sha256:3452bba7c21c69f2df772762be0066c7ed5dc65df494a1d53a58b683a83e1216", + "sha256:41a0be220dd1ed9e998f5891948306eb8c812b512dc398e5a01846d855050799", + "sha256:5751d8a11b956fbfa314f6553d186b94aa70fdb03d8a4d4f1c82dcacf0cbe28a", + "sha256:5f61c7d749048fa6e3322258b4263463bfccefecb0dd731b6561cb617a1d9bb9", + "sha256:72e24c521fa2106f19623a3851e9f89ddfdeb9ac63871c7643790f872a305dfc", + "sha256:7b97ae6ef5cba2e3bb14256625423413d5ce8d1abb91d4f29b6d1a081da765f8", + "sha256:961e886d8a3590fd2c723cf07be14e2a91cf53c25f02435c04d39e90780e3b53", + "sha256:96d8473848e984184b6728e2c9d391482008646276c3ff084a1bd89e15ff53a1", + "sha256:ae536da50c7ad1e002c3eee101871d93abdc90d9c5f651818450a0d3af718609", + "sha256:b0db0cecf396033abb4a93c95d1602f268b3a68bb0a9cc06a7cff587bb9a7292", + "sha256:cfee9164954c186b191b91d4193989ca994703b2fff406f71cf454a2d3c7327e", + "sha256:e6347742ac8f35ded4a46ff835c60e68c22a536a8ae5c4422966d06946b6d4c6", + "sha256:f27d93f0139a3c056172ebb5d4f9056e770fdf0206c2f422ff2ebbad142e09ed", + "sha256:f57b76e46a58b63d1c6375017f4564a28f19a5ca912691fd2e4261b3414b618d" + ], + "index": "pypi", + "version": "==2.7" + }, + "cython": { + "hashes": [ + "sha256:0afa0b121b89de619e71587e25702e2b7068d7da2164c47e6eee80c17823a62f", + "sha256:1c608ba76f7a20cc9f0c021b7fe5cb04bc1a70327ae93a9298b1bc3e0edddebe", + "sha256:26229570d6787ff3caa932fe9d802960f51a89239b990d275ae845405ce43857", + "sha256:2a9deafa437b6154cac2f25bb88e0bfd075a897c8dc847669d6f478d7e3ee6b1", + "sha256:2f28396fbce6d9d68a40edbf49a6729cf9d92a4d39ff0f501947a89188e9099f", + "sha256:3983dd7b67297db299b403b29b328d9e03e14c4c590ea90aa1ad1d7b35fb178b", + "sha256:4100a3f8e8bbe47d499cdac00e56d5fe750f739701ea52dc049b6c56f5421d97", + "sha256:51abfaa7b6c66f3f18028876713c8804e73d4c2b6ceddbcbcfa8ec62429377f0", + "sha256:61c24f4554efdb8fb1ac6c8e75dab301bcdf2b7b739ed0c2b267493bb43163c5", + "sha256:700ccf921b2fdc9b23910e95b5caae4b35767685e0812343fa7172409f1b5830", + "sha256:7b41eb2e792822a790cb2a171df49d1a9e0baaa8e81f58077b7380a273b93d5f", + "sha256:803987d3b16d55faa997bfc12e8b97f1091f145930dee229b020487aed8a1f44", + "sha256:99af5cfcd208c81998dcf44b3ca466dee7e17453cfb50e98b87947c3a86f8753", + "sha256:9faea1cca34501c7e139bc7ef8e504d532b77865c58592493e2c154a003b450f", + "sha256:a7ba4c9a174db841cfee9a0b92563862a0301d7ca543334666c7266b541f141a", + "sha256:b26071c2313d1880599c69fd831a07b32a8c961ba69d7ccbe5db1cd8d319a4ca", + "sha256:b49dc8e1116abde13a3e6a9eb8da6ab292c5a3325155fb872e39011b110b37e6", + "sha256:bd40def0fd013569887008baa6da9ca428e3d7247adeeaeada153006227bb2e7", + "sha256:bfd0db770e8bd4e044e20298dcae6dfc42561f85d17ee546dcd978c8b23066ae", + "sha256:c2fad1efae5889925c8fd7867fdd61f59480e4e0b510f9db096c912e884704f1", + "sha256:c81aea93d526ccf6bc0b842c91216ee9867cd8792f6725a00f19c8b5837e1715", + "sha256:da786e039b4ad2bce3d53d4799438cf1f5e01a0108f1b8d78ac08e6627281b1a", + "sha256:deab85a069397540987082d251e9c89e0e5b2e3e044014344ff81f60e211fc4b", + "sha256:e3f1e6224c3407beb1849bdc5ae3150929e593e4cffff6ca41c6ec2b10942c80", + "sha256:e74eb224e53aae3943d66e2d29fe42322d5753fd4c0641329bccb7efb3a46552", + "sha256:ee697c7ea65cb14915a64f36874da8ffc2123df43cf8bc952172e04a26656cd6", + "sha256:f37792b16d11606c28e428460bd6a3d14b8917b109e77cdbe4ca78b0b9a52c87", + "sha256:fd2906b54cbf879c09d875ad4e4687c58d87f5ed03496063fec1c9065569fd5d" + ], + "index": "pypi", + "version": "==0.29.10" + }, + "enum34": { + "hashes": [ + "sha256:2d81cbbe0e73112bdfe6ef8576f2238f2ba27dd0d55752a776c41d38b7da2850", + "sha256:644837f692e5f550741432dd3f223bbb9852018674981b1664e5dc339387588a", + "sha256:6bd0f6ad48ec2aa117d3d141940d484deccda84d4fcd884f5c3d93c23ecd8c79", + "sha256:8ad8c4783bf61ded74527bffb48ed9b54166685e4230386a9ed9b1279e2df5b1" + ], + "markers": "python_version < '3'", + "version": "==1.1.6" + }, + "flask": { + "hashes": [ + "sha256:ad7c6d841e64296b962296c2c2dabc6543752985727af86a975072dea984b6f3", + "sha256:e7d32475d1de5facaa55e3958bc4ec66d3762076b074296aa50ef8fdc5b9df61" + ], + "index": "pypi", + "version": "==1.0.3" + }, + "futures": { + "hashes": [ + "sha256:9ec02aa7d674acb8618afb127e27fde7fc68994c0437ad759fa094a574adb265", + "sha256:ec0a6cb848cc212002b9828c3e34c675e0c9ff6741dc445cab6fdd4e1085d1f1" + ], + "markers": "python_version < '3.2'", + "version": "==3.2.0" + }, + "gunicorn": { + "hashes": [ + "sha256:aa8e0b40b4157b36a5df5e599f45c9c76d6af43845ba3b3b0efe2c70473c2471", + "sha256:fa2662097c66f920f53f70621c6c58ca4a3c4d3434205e608e121b5b3b71f4f3" + ], + "index": "pypi", + "version": "==19.9.0" + }, + "hexdump": { + "hashes": [ + "sha256:d781a43b0c16ace3f9366aade73e8ad3a7bd5137d58f0b45ab2d3f54876f20db" + ], + "index": "pypi", + "version": "==3.3" + }, + "idna": { + "hashes": [ + "sha256:c357b3f628cf53ae2c4c05627ecc484553142ca23264e593d327bcde5e9c3407", + "sha256:ea8b7f6188e6fa117537c3df7da9fc686d485087abf6ac197f9c46432f7e4a3c" + ], + "index": "pypi", + "version": "==2.8" + }, + "ipaddress": { + "hashes": [ + "sha256:64b28eec5e78e7510698f6d4da08800a5c575caa4a286c93d651c5d3ff7b6794", + "sha256:b146c751ea45cad6188dd6cf2d9b757f6f4f8d6ffb96a023e6f2e26eea02a72c" + ], + "markers": "python_version < '3'", + "version": "==1.0.22" + }, + "isort": { + "hashes": [ + "sha256:c40744b6bc5162bbb39c1257fe298b7a393861d50978b565f3ccd9cb9de0182a", + "sha256:f57abacd059dc3bd666258d1efb0377510a89777fda3e3274e3c01f7c03ae22d" + ], + "version": "==4.3.20" + }, + "itsdangerous": { + "hashes": [ + "sha256:321b033d07f2a4136d3ec762eac9f16a10ccd60f53c0c91af90217ace7ba1f19", + "sha256:b12271b2047cb23eeb98c8b5622e2e5c5e9abd9784a153e9d8ef9cb4dd09d749" + ], + "version": "==1.1.0" + }, + "jinja2": { + "hashes": [ + "sha256:065c4f02ebe7f7cf559e49ee5a95fb800a9e4528727aec6f24402a5374c65013", + "sha256:14dd6caf1527abb21f08f86c784eac40853ba93edb79552aa1e4b8aef1b61c7b" + ], + "index": "pypi", + "version": "==2.10.1" + }, + "json-rpc": { + "hashes": [ + "sha256:bc84451268b48a576d3138744322a8ce673eccadf7424edf4d446b1ddb59e58c", + "sha256:d6ed3dae670a12e4caa738d309807357d22e2f6e222bb34e8ef019e8b5b1228b" + ], + "index": "pypi", + "version": "==1.12.1" + }, + "lazy-object-proxy": { + "hashes": [ + "sha256:159a745e61422217881c4de71f9eafd9d703b93af95618635849fe469a283661", + "sha256:23f63c0821cc96a23332e45dfaa83266feff8adc72b9bcaef86c202af765244f", + "sha256:3b11be575475db2e8a6e11215f5aa95b9ec14de658628776e10d96fa0b4dac13", + "sha256:3f447aff8bc61ca8b42b73304f6a44fa0d915487de144652816f950a3f1ab821", + "sha256:4ba73f6089cd9b9478bc0a4fa807b47dbdb8fad1d8f31a0f0a5dbf26a4527a71", + "sha256:4f53eadd9932055eac465bd3ca1bd610e4d7141e1278012bd1f28646aebc1d0e", + "sha256:64483bd7154580158ea90de5b8e5e6fc29a16a9b4db24f10193f0c1ae3f9d1ea", + "sha256:6f72d42b0d04bfee2397aa1862262654b56922c20a9bb66bb76b6f0e5e4f9229", + "sha256:7c7f1ec07b227bdc561299fa2328e85000f90179a2f44ea30579d38e037cb3d4", + "sha256:7c8b1ba1e15c10b13cad4171cfa77f5bb5ec2580abc5a353907780805ebe158e", + "sha256:8559b94b823f85342e10d3d9ca4ba5478168e1ac5658a8a2f18c991ba9c52c20", + "sha256:a262c7dfb046f00e12a2bdd1bafaed2408114a89ac414b0af8755c696eb3fc16", + "sha256:acce4e3267610c4fdb6632b3886fe3f2f7dd641158a843cf6b6a68e4ce81477b", + "sha256:be089bb6b83fac7f29d357b2dc4cf2b8eb8d98fe9d9ff89f9ea6012970a853c7", + "sha256:bfab710d859c779f273cc48fb86af38d6e9210f38287df0069a63e40b45a2f5c", + "sha256:c10d29019927301d524a22ced72706380de7cfc50f767217485a912b4c8bd82a", + "sha256:dd6e2b598849b3d7aee2295ac765a578879830fb8966f70be8cd472e6069932e", + "sha256:e408f1eacc0a68fed0c08da45f31d0ebb38079f043328dce69ff133b95c29dc1" + ], + "version": "==1.4.1" + }, + "libusb1": { + "hashes": [ + "sha256:adf64a4f3f5c94643a1286f8153bcf4bc787c348b38934aacd7fe17fbeebc571" + ], + "index": "pypi", + "version": "==1.7.1" + }, + "logentries": { + "git": "https://github.com/commaai/le_python.git", + "ref": "5eef8f5be5929d33973e1b10e686fa0cdcd6792f" + }, + "markupsafe": { + "hashes": [ + "sha256:00bc623926325b26bb9605ae9eae8a215691f33cae5df11ca5424f06f2d1f473", + "sha256:09027a7803a62ca78792ad89403b1b7a73a01c8cb65909cd876f7fcebd79b161", + "sha256:09c4b7f37d6c648cb13f9230d847adf22f8171b1ccc4d5682398e77f40309235", + "sha256:1027c282dad077d0bae18be6794e6b6b8c91d58ed8a8d89a89d59693b9131db5", + "sha256:24982cc2533820871eba85ba648cd53d8623687ff11cbb805be4ff7b4c971aff", + "sha256:29872e92839765e546828bb7754a68c418d927cd064fd4708fab9fe9c8bb116b", + "sha256:43a55c2930bbc139570ac2452adf3d70cdbb3cfe5912c71cdce1c2c6bbd9c5d1", + "sha256:46c99d2de99945ec5cb54f23c8cd5689f6d7177305ebff350a58ce5f8de1669e", + "sha256:500d4957e52ddc3351cabf489e79c91c17f6e0899158447047588650b5e69183", + "sha256:535f6fc4d397c1563d08b88e485c3496cf5784e927af890fb3c3aac7f933ec66", + "sha256:62fe6c95e3ec8a7fad637b7f3d372c15ec1caa01ab47926cfdf7a75b40e0eac1", + "sha256:6dd73240d2af64df90aa7c4e7481e23825ea70af4b4922f8ede5b9e35f78a3b1", + "sha256:717ba8fe3ae9cc0006d7c451f0bb265ee07739daf76355d06366154ee68d221e", + "sha256:79855e1c5b8da654cf486b830bd42c06e8780cea587384cf6545b7d9ac013a0b", + "sha256:7c1699dfe0cf8ff607dbdcc1e9b9af1755371f92a68f706051cc8c37d447c905", + "sha256:88e5fcfb52ee7b911e8bb6d6aa2fd21fbecc674eadd44118a9cc3863f938e735", + "sha256:8defac2f2ccd6805ebf65f5eeb132adcf2ab57aa11fdf4c0dd5169a004710e7d", + "sha256:98c7086708b163d425c67c7a91bad6e466bb99d797aa64f965e9d25c12111a5e", + "sha256:9add70b36c5666a2ed02b43b335fe19002ee5235efd4b8a89bfcf9005bebac0d", + "sha256:9bf40443012702a1d2070043cb6291650a0841ece432556f784f004937f0f32c", + "sha256:ade5e387d2ad0d7ebf59146cc00c8044acbd863725f887353a10df825fc8ae21", + "sha256:b00c1de48212e4cc9603895652c5c410df699856a2853135b3967591e4beebc2", + "sha256:b1282f8c00509d99fef04d8ba936b156d419be841854fe901d8ae224c59f0be5", + "sha256:b2051432115498d3562c084a49bba65d97cf251f5a331c64a12ee7e04dacc51b", + "sha256:ba59edeaa2fc6114428f1637ffff42da1e311e29382d81b339c1817d37ec93c6", + "sha256:c8716a48d94b06bb3b2524c2b77e055fb313aeb4ea620c8dd03a105574ba704f", + "sha256:cd5df75523866410809ca100dc9681e301e3c27567cf498077e8551b6d20e42f", + "sha256:e249096428b3ae81b08327a63a485ad0878de3fb939049038579ac0ef61e17e7" + ], + "version": "==1.1.1" + }, + "mccabe": { + "hashes": [ + "sha256:ab8a6258860da4b6677da4bd2fe5dc2c659cff31b3ee4f7f5d64e79735b80d42", + "sha256:dd8d182285a0fe56bace7f45b5e7d1a6ebcbf524e8f3bd87eb0f125271b8831f" + ], + "version": "==0.6.1" + }, + "mpmath": { + "hashes": [ + "sha256:fc17abe05fbab3382b61a123c398508183406fa132e0223874578e20946499f6" + ], + "version": "==1.1.0" + }, + "nose": { + "hashes": [ + "sha256:9ff7c6cc443f8c51994b34a667bbcf45afd6d945be7477b52e97516fd17c53ac", + "sha256:dadcddc0aefbf99eea214e0f1232b94f2fa9bd98fa8353711dacb112bfcbbb2a", + "sha256:f1bffef9cbc82628f6e7d7b40d7e255aefaa1adb6a1b1d26c69a8b79e6208a98" + ], + "index": "pypi", + "version": "==1.3.7" + }, + "numpy": { + "hashes": [ + "sha256:0778076e764e146d3078b17c24c4d89e0ecd4ac5401beff8e1c87879043a0633", + "sha256:141c7102f20abe6cf0d54c4ced8d565b86df4d3077ba2343b61a6db996cefec7", + "sha256:14270a1ee8917d11e7753fb54fc7ffd1934f4d529235beec0b275e2ccf00333b", + "sha256:27e11c7a8ec9d5838bc59f809bfa86efc8a4fd02e58960fa9c49d998e14332d5", + "sha256:2a04dda79606f3d2f760384c38ccd3d5b9bb79d4c8126b67aff5eb09a253763e", + "sha256:3c26010c1b51e1224a3ca6b8df807de6e95128b0908c7e34f190e7775455b0ca", + "sha256:52c40f1a4262c896420c6ea1c6fda62cf67070e3947e3307f5562bd783a90336", + "sha256:6e4f8d9e8aa79321657079b9ac03f3cf3fd067bf31c1cca4f56d49543f4356a5", + "sha256:7242be12a58fec245ee9734e625964b97cf7e3f2f7d016603f9e56660ce479c7", + "sha256:7dc253b542bfd4b4eb88d9dbae4ca079e7bf2e2afd819ee18891a43db66c60c7", + "sha256:94f5bd885f67bbb25c82d80184abbf7ce4f6c3c3a41fbaa4182f034bba803e69", + "sha256:a89e188daa119ffa0d03ce5123dee3f8ffd5115c896c2a9d4f0dbb3d8b95bfa3", + "sha256:ad3399da9b0ca36e2f24de72f67ab2854a62e623274607e37e0ce5f5d5fa9166", + "sha256:b0348be89275fd1d4c44ffa39530c41a21062f52299b1e3ee7d1c61f060044b8", + "sha256:b5554368e4ede1856121b0dfa35ce71768102e4aa55e526cb8de7f374ff78722", + "sha256:cbddc56b2502d3f87fda4f98d948eb5b11f36ff3902e17cb6cc44727f2200525", + "sha256:d79f18f41751725c56eceab2a886f021d70fd70a6188fd386e29a045945ffc10", + "sha256:dc2ca26a19ab32dc475dbad9dfe723d3a64c835f4c23f625c2b6566ca32b9f29", + "sha256:dd9bcd4f294eb0633bb33d1a74febdd2b9018b8b8ed325f861fffcd2c7660bb8", + "sha256:e8baab1bc7c9152715844f1faca6744f2416929de10d7639ed49555a85549f52", + "sha256:ec31fe12668af687b99acf1567399632a7c47b0e17cfb9ae47c098644ef36797", + "sha256:f12b4f7e2d8f9da3141564e6737d79016fe5336cc92de6814eba579744f65b0a", + "sha256:f58ac38d5ca045a377b3b377c84df8175ab992c970a53332fa8ac2373df44ff7" + ], + "index": "pypi", + "version": "==1.16.4" + }, + "overpy": { + "git": "https://github.com/commaai/python-overpy.git", + "ref": "f86529af402d4642e1faeb146671c40284007323" + }, + "psutil": { + "hashes": [ + "sha256:028a1ec3c6197eadd11e7b46e8cc2f0720dc18ac6d7aabdb8e8c0d6c9704f000", + "sha256:503e4b20fa9d3342bcf58191bbc20a4a5ef79ca7df8972e6197cc14c5513e73d", + "sha256:863a85c1c0a5103a12c05a35e59d336e1d665747e531256e061213e2e90f63f3", + "sha256:954f782608bfef9ae9f78e660e065bd8ffcfaea780f9f2c8a133bb7cb9e826d7", + "sha256:b6e08f965a305cd84c2d07409bc16fbef4417d67b70c53b299116c5b895e3f45", + "sha256:bc96d437dfbb8865fc8828cf363450001cb04056bbdcdd6fc152c436c8a74c61", + "sha256:cf49178021075d47c61c03c0229ac0c60d5e2830f8cab19e2d88e579b18cdb76", + "sha256:d5350cb66690915d60f8b233180f1e49938756fb2d501c93c44f8fb5b970cc63", + "sha256:eba238cf1989dfff7d483c029acb0ac4fcbfc15de295d682901f0e2497e6781a" + ], + "index": "pypi", + "version": "==5.6.3" + }, + "pycapnp": { + "hashes": [ + "sha256:44e14a5ace399cf1753acb8bbce558b8c895c48fd2102d266c34eaff286824cf" + ], + "index": "pypi", + "version": "==0.6.4" + }, + "pycparser": { + "hashes": [ + "sha256:a988718abfad80b6b157acce7bf130a30876d27603738ac39f140993246b25b3" + ], + "version": "==2.19" + }, + "pycryptodome": { + "hashes": [ + "sha256:0281dc6a65a4d0d9e439f54e0ad5faf27bfdc2ebe9ead36912bac74a0920fa2e", + "sha256:02af9b284f5c9a55f06f5e4532c16c9b7bd958e293e93969934d864ef7bd87ee", + "sha256:09da99372fb69762e4b9690291176a166cc351793e2e1c9405d29ca291503aa8", + "sha256:0c2400ccfc049c3f24e65d4f02bb4208d86e408011019e455fab7f50d2b226c9", + "sha256:2081dd6dce6b21bf3596427edaedd4f2561dce616893b162ed2c674f3a3ca70a", + "sha256:28b86ec9fdb005a2a18e4862a3a7277046738825ee8dc89cda5657e75a396089", + "sha256:2d790c0d4c0d5edcf5fbab4e2af7b03757e40c5ae8d217f0dfe9ddea37fe130f", + "sha256:2f24906153dca16528cf5515b1afa9ef635423d5a654904e861765f88ca667b6", + "sha256:30d283939896fa4bacbdb9fa86e6fd51e9a5b953a511e210b38481f697f289f5", + "sha256:31f78b67f97830d137f74813c0502a181a03b43a32ed124049bb20428176c307", + "sha256:33c1f3a380fd38ab4dd4372bef17e98002b360b52814bb1b077693b1bd06ec87", + "sha256:34091e9a6650c44e25339f22fc821396f19f152f65be2546edd823a093fb5a04", + "sha256:567fb73951ab6865a2eb1a0060b54be1e27302574f6c65879525bdf53fab49e1", + "sha256:5bc40f8aa7ba8ca7f833ad2477b9d84e1bfd2630b22a46d9bbd221982f8c3ac0", + "sha256:6b0a0ccf33c7a6100c569667c888335a4aaf0d22218cb97b4963a65d70f6c343", + "sha256:71b93157f1ce93fc7cfff9359b76def2b4826a7ef7a7f95e070161368e7f584a", + "sha256:7d939d511b7dac29b2d936706786771ecb8256e43fade5cdb0e8bc58f02b86cf", + "sha256:7fbc5a93d52e4c51487f4648b00dc41700adb144d10fc567b05f852e76c243ad", + "sha256:9cb94b8f9c915a5d2b273d612a25a8e5d67b49543f8eb6bcec0275ac46cda421", + "sha256:a585ea1722f9731e75881d5ffcc51d11c794d244ac57e7c2a9cbb8d5ac729302", + "sha256:a6458dd7a10ae51f6fce56bdfc79bf6d3b54556237045d09e77fbda9d6d37864", + "sha256:a9fb92e948128bce0239b87c6efcf2cb1c5a703d0b41dd6835211e6fafd1c5df", + "sha256:b0b6b4ca1c53e7d6ca9f2720919f63837f05e7a5f92912a2bc29bfd03ed3b54f", + "sha256:b7d22c8d648aaa3a7ec785eda544402141eb78ac5ffbba4cbe2c3a1f52276870", + "sha256:bc9560574a868cfa2ba781b7bb0b4685b08ea251697abfc49070ffc05e1cbee6", + "sha256:c0c5a576f3f7b7de3f86889cb47eb51b59dc11db9cf1e2a0f51eb4d988010ea4", + "sha256:e1c91c2fa942a71c98a7a1f462de6dbbe82f34b9267eb8131314d97bd13bf0d4", + "sha256:ec936361ad78aa95382c313df95777795b8185aac5dd3ec5463363ea94b556fc" + ], + "index": "pypi", + "version": "==3.8.2" + }, + "pyflakes": { + "hashes": [ + "sha256:17dbeb2e3f4d772725c777fabc446d5634d1038f234e77343108ce445ea69ce0", + "sha256:d976835886f8c5b31d47970ed689944a0262b5f3afa00a5a7b4dc81e5449f8a2" + ], + "index": "pypi", + "version": "==2.1.1" + }, + "pyjwt": { + "hashes": [ + "sha256:5c6eca3c2940464d106b99ba83b00c6add741c9becaec087fb7ccdefea71350e", + "sha256:8d59a976fb773f3e6a39c85636357c4f0e242707394cadadd9814f5cbaa20e96" + ], + "index": "pypi", + "version": "==1.7.1" + }, + "pylint": { + "hashes": [ + "sha256:02c2b6d268695a8b64ad61847f92e611e6afcff33fd26c3a2125370c4662905d", + "sha256:ee1e85575587c5b58ddafa25e1c1b01691ef172e139fc25585e5d3f02451da93" + ], + "index": "pypi", + "version": "==1.9.4" + }, + "pyserial": { + "hashes": [ + "sha256:6e2d401fdee0eab996cf734e67773a0143b932772ca8b42451440cfed942c627", + "sha256:e0770fadba80c31013896c7e6ef703f72e7834965954a78e71a3049488d4d7d8" + ], + "index": "pypi", + "version": "==3.4" + }, + "python-dateutil": { + "hashes": [ + "sha256:7e6584c74aeed623791615e26efd690f29817a27c73085b78e4bad02493df2fb", + "sha256:c89805f6f4d64db21ed966fda138f8a5ed7a4fdbc1a8ee329ce1b74e3c74da9e" + ], + "index": "pypi", + "version": "==2.8.0" + }, + "pyyaml": { + "hashes": [ + "sha256:57acc1d8533cbe51f6662a55434f0dbecfa2b9eaf115bede8f6fd00115a0c0d3", + "sha256:588c94b3d16b76cfed8e0be54932e5729cc185caffaa5a451e7ad2f7ed8b4043", + "sha256:68c8dd247f29f9a0d09375c9c6b8fdc64b60810ebf07ba4cdd64ceee3a58c7b7", + "sha256:70d9818f1c9cd5c48bb87804f2efc8692f1023dac7f1a1a5c61d454043c1d265", + "sha256:86a93cccd50f8c125286e637328ff4eef108400dd7089b46a7be3445eecfa391", + "sha256:a0f329125a926876f647c9fa0ef32801587a12328b4a3c741270464e3e4fa778", + "sha256:a3c252ab0fa1bb0d5a3f6449a4826732f3eb6c0270925548cac342bc9b22c225", + "sha256:b4bb4d3f5e232425e25dda21c070ce05168a786ac9eda43768ab7f3ac2770955", + "sha256:cd0618c5ba5bda5f4039b9398bb7fb6a317bb8298218c3de25c47c4740e4b95e", + "sha256:ceacb9e5f8474dcf45b940578591c7f3d960e82f926c707788a570b51ba59190", + "sha256:fe6a88094b64132c4bb3b631412e90032e8cfe9745a58370462240b8cb7553cd" + ], + "index": "pypi", + "version": "==5.1.1" + }, + "pyzmq": { + "hashes": [ + "sha256:1651e52ed91f0736afd6d94ef9f3259b5534ce8beddb054f3d5ca989c4ef7c4f", + "sha256:5ccb9b3d4cd20c000a9b75689d5add8cd3bce67fcbd0f8ae1b59345247d803af", + "sha256:5e120c4cd3872e332fb35d255ad5998ebcee32ace4387b1b337416b6b90436c7", + "sha256:5e2a3707c69a7281a9957f83718815fd74698cba31f6d69f9ed359921f662221", + "sha256:63d51add9af8d0442dc90f916baf98fdc04e3b0a32afec4bfc83f8d85e72959f", + "sha256:65c5a0bdc49e20f7d6b03a661f71e2fda7a99c51270cafe71598146d09810d0d", + "sha256:66828fabe911aa545d919028441a585edb7c9c77969a5fea6722ef6e6ece38ab", + "sha256:7d79427e82d9dad6e9b47c0b3e7ae5f9d489b1601e3a36ea629bb49501a4daf3", + "sha256:824ee5d3078c4eae737ffc500fbf32f2b14e6ec89b26b435b7834febd70120cf", + "sha256:89dc0a83cccec19ff3c62c091e43e66e0183d1e6b4658c16ee4e659518131494", + "sha256:8b319805f6f7c907b101c864c3ca6cefc9db8ce0791356f180b1b644c7347e4c", + "sha256:90facfb379ab47f94b19519c1ecc8ec8d10813b69d9c163117944948bdec5d15", + "sha256:a0a178c7420021fc0730180a914a4b4b3092ce9696ceb8e72d0f60f8ce1655dd", + "sha256:a7a89591ae315baccb8072f216614b3e59aed7385aef4393a6c741783d6ee9cf", + "sha256:ba2578f0ae582452c02ed9fac2dc477b08e80ce05d2c0885becf5fff6651ccb0", + "sha256:c69b0055c55702f5b0b6b354133e8325b9a56dbc80e1be2d240bead253fb9825", + "sha256:ca434e1858fe222380221ddeb81e86f45522773344c9da63c311d17161df5e06", + "sha256:d4b8ecfc3d92f114f04d5c40f60a65e5196198b827503341521dda12d8b14939", + "sha256:d706025c47b09a54f005953ebe206f6d07a22516776faa4f509aaff681cc5468", + "sha256:d8f27e958f8a2c0c8ffd4d8855c3ce8ac3fa1e105f0491ce31729aa2b3229740", + "sha256:dbd264298f76b9060ce537008eb989317ca787c857e23cbd1b3ddf89f190a9b1", + "sha256:e926d66f0df8fdbf03ba20583af0f215e475c667fb033d45fd031c66c63e34c9", + "sha256:efc3bd48237f973a749f7312f68062f1b4ca5c2032a0673ca3ea8e46aa77187b", + "sha256:f59bc782228777cbfe04555707a9c56d269c787ed25d6d28ed9d0fbb41cb1ad2", + "sha256:f8da5322f4ff5f667a0d5a27e871b560c6637153c81e318b35cb012b2a98835c" + ], + "index": "pypi", + "version": "==18.0.1" + }, + "raven": { + "hashes": [ + "sha256:3fa6de6efa2493a7c827472e984ce9b020797d0da16f1db67197bcc23c8fae54", + "sha256:44a13f87670836e153951af9a3c80405d36b43097db869a36e92809673692ce4" + ], + "index": "pypi", + "version": "==6.10.0" + }, + "requests": { + "hashes": [ + "sha256:11e007a8a2aa0323f5a921e9e6a2d7e4e67d9877e85773fba9ba6419025cbeb4", + "sha256:9cf5292fcd0f598c671cfc1e0d7d1a7f13bb8085e9a590f48c010551dc6c4b31" + ], + "index": "pypi", + "version": "==2.22.0" + }, + "setproctitle": { + "hashes": [ + "sha256:6283b7a58477dd8478fbb9e76defb37968ee4ba47b05ec1c053cb39638bd7398", + "sha256:6a035eddac62898786aed2c2eee7334c28cfc8106e8eb29fdd117cac56c6cdf0" + ], + "index": "pypi", + "version": "==1.1.10" + }, + "singledispatch": { + "hashes": [ + "sha256:5b06af87df13818d14f08a028e42f566640aef80805c3b50c5056b086e3c2b9c", + "sha256:833b46966687b3de7f438c761ac475213e53b306740f1abfaa86e1d1aae56aa8" + ], + "markers": "python_version < '3.4'", + "version": "==3.4.0.3" + }, + "six": { + "hashes": [ + "sha256:3350809f0555b11f552448330d0b52d5f24c91a322ea4a15ef22629740f3761c", + "sha256:d16a0141ec1a18405cd4ce8b4613101da75da0e9a7aec5bdd4fa804d0e0eba73" + ], + "index": "pypi", + "version": "==1.12.0" + }, + "smbus2": { + "hashes": [ + "sha256:4d5aae2f65d39056bb44e8906d5c503f8ee7e02fadb0a6433f1091a9ce528dde" + ], + "index": "pypi", + "version": "==0.2.3" + }, + "sympy": { + "hashes": [ + "sha256:71a11e5686ae7ab6cb8feb5bd2651ef4482f8fd43a7c27e645a165e4353b23e1", + "sha256:f9b00ec76151c98470e84f1da2d7d03633180b71fb318428ddccce1c867d3eaa" + ], + "index": "pypi", + "version": "==1.4" + }, + "tqdm": { + "hashes": [ + "sha256:0a860bf2683fdbb4812fe539a6c22ea3f1777843ea985cb8c3807db448a0f7ab", + "sha256:e288416eecd4df19d12407d0c913cbf77aa8009d7fddb18f632aded3bdbdda6b" + ], + "index": "pypi", + "version": "==4.32.1" + }, + "urllib3": { + "hashes": [ + "sha256:b246607a25ac80bedac05c6f282e3cdaf3afb65420fd024ac94435cabe6e18d1", + "sha256:dbe59173209418ae49d485b87d1681aefa36252ee85884c31346debd19463232" + ], + "index": "pypi", + "version": "==1.25.3" + }, + "utm": { + "hashes": [ + "sha256:a6608a67df84418fd959a79b228b90ab55b2ae877827f9c210947104c5a75d0e" + ], + "index": "pypi", + "version": "==0.4.2" + }, + "websocket-client": { + "hashes": [ + "sha256:1151d5fb3a62dc129164292e1227655e4bbc5dd5340a5165dfae61128ec50aa9", + "sha256:1fd5520878b68b84b5748bb30e592b10d0a91529d5383f74f4964e72b297fd3a" + ], + "index": "pypi", + "version": "==0.56.0" + }, + "werkzeug": { + "hashes": [ + "sha256:865856ebb55c4dcd0630cdd8f3331a1847a819dda7e8c750d3db6f2aa6c0209c", + "sha256:a0b915f0815982fb2a09161cb8f31708052d0951c3ba433ccc5e1aa276507ca6" + ], + "version": "==0.15.4" + }, + "wrapt": { + "hashes": [ + "sha256:4aea003270831cceb8a90ff27c4031da6ead7ec1886023b80ce0dfe0adf61533" + ], + "version": "==1.11.1" + } + }, + "develop": { + "absl-py": { + "hashes": [ + "sha256:b943d1c567743ed0455878fcd60bc28ac9fae38d129d1ccfad58079da00b8951" + ], + "version": "==0.7.1" + }, + "adal": { + "hashes": [ + "sha256:82e84fa0b442caf8131f1e87a7ebee2546f57ab16a8917a599a02b6e455cb1b0", + "sha256:b6edd095be66561382bdaa59d40b04490e93149fb3b7fa44c1fa5504eed5b8b9" + ], + "version": "==1.2.1" + }, + "aenum": { + "hashes": [ + "sha256:3df9b84cce5dc9ed77c337079f97b66c44c0053eb87d6f4d46b888dc45801e38", + "sha256:7a77c205c4bc9d7fe9bd73b3193002d724aebf5909fa0d297534208953891ec8", + "sha256:a3208e4b28db3a7b232ff69b934aef2ea1bf27286d9978e1e597d46f490e4687" + ], + "index": "pypi", + "version": "==2.1.2" + }, + "amqp": { + "hashes": [ + "sha256:aa4409446139676943a2eaa27d5f58caf750f4ca5a89f888c452afd86be6a67d", + "sha256:cbb6f87d53cac612a594f982b717cc1c54c6a1e17943a0a0d32dc6cc9e2120c8" + ], + "version": "==2.5.0" + }, + "asn1crypto": { + "hashes": [ + "sha256:2f1adbb7546ed199e3c90ef23ec95c5cf3585bac7d11fb7eb562a3fe89c64e87", + "sha256:9d5c20441baf0cb60a4ac34cc447c6c189024b6b4c6cd7877034f4965c464e49" + ], + "version": "==0.24.0" + }, + "astor": { + "hashes": [ + "sha256:0e41295809baf43ae8303350e031aff81ae52189b6f881f36d623fa8b2f1960e", + "sha256:37a6eed8b371f1228db08234ed7f6cfdc7817a3ed3824797e20cbb11dc2a7862" + ], + "version": "==0.8.0" + }, + "astroid": { + "hashes": [ + "sha256:87de48a92e29cedf7210ffa853d11441e7ad94cb47bacd91b023499b51cbc756", + "sha256:d25869fc7f44f1d9fb7d24fd7ea0639656f5355fc3089cd1f3d18c6ec6b124c7" + ], + "version": "==1.6.6" + }, + "attrs": { + "hashes": [ + "sha256:69c0dbf2ed392de1cb5ec704444b08a5ef81680a61cb899dc08127123af36a79", + "sha256:f0b870f674851ecbfbbbd364d6b5cbdff9dcedbc7f3f5e18a6891057f21fe399" + ], + "version": "==19.1.0" + }, + "azure-batch": { + "hashes": [ + "sha256:017be21a9e6db92473d2e33170d5dd445596fc70d706f73552ac9c6b57a6ef1c", + "sha256:cd71c7ebb5beab174b6225bbf79ae18d6db0c8d63227a7e514da0a75f138364c" + ], + "index": "pypi", + "version": "==4.1.3" + }, + "azure-common": { + "hashes": [ + "sha256:2606ae77ff81c0036965b92ec2efe03eaec02a66714140ca0f7aa401b8b9bbb0", + "sha256:c908621a71eb4ee9fab0962e35d3c27a18f09a854d8359c2f32c15b3f4fc576e" + ], + "index": "pypi", + "version": "==1.1.16" + }, + "azure-nspkg": { + "hashes": [ + "sha256:a908f96a695b12e31b6c56cda0bb8e6d2a054283c350881667f300b8563ece33", + "sha256:af81fd4512be5ad0834b8e82c43bbe80b016bd295a8794fac28d69bf243357e0", + "sha256:ce4173e06f2f423775c4ca8a635e9a89b5fe8e4ba9fefbbe2a1e0d525072392c" + ], + "index": "pypi", + "version": "==3.0.1" + }, + "azure-storage-blob": { + "hashes": [ + "sha256:308058abfd789f5830d91f6407eb00a7b04925b2b9af267aecfb46c335802cdc", + "sha256:8cab5420ba6646ead09fdb497646f735b12645cba8efed96a86f7b370e175ade" + ], + "index": "pypi", + "version": "==1.3.1" + }, + "azure-storage-common": { + "hashes": [ + "sha256:585658ebc784e843a285732a69aa69ef922e17c3063460c2c7b27c89f377004c", + "sha256:a412a78618e82bf99030ce56f1f2d5fc6c2c2eec7ee1beda86ce6ea5f2c9196b" + ], + "index": "pypi", + "version": "==1.3.0" + }, + "azure-storage-nspkg": { + "hashes": [ + "sha256:4fc4685aef941eab2f7fb53824254cca2e38f2a1bf33cda0c8ae654fe15827d6", + "sha256:855315c038c0e695868025127e1b3057a1f984af9ccfbaeac4fbfd6c5dd3b466" + ], + "index": "pypi", + "version": "==3.0.0" + }, + "backports-abc": { + "hashes": [ + "sha256:033be54514a03e255df75c5aee8f9e672f663f93abb723444caec8fe43437bde", + "sha256:52089f97fe7a9aa0d3277b220c1d730a85aefd64e1b2664696fe35317c5470a7" + ], + "index": "pypi", + "version": "==0.5" + }, + "backports.functools-lru-cache": { + "hashes": [ + "sha256:9d98697f088eb1b0fa451391f91afb5e3ebde16bbdb272819fd091151fda4f1a", + "sha256:f0b0e4eba956de51238e17573b7087e852dfe9854afd2e9c873f73fc0ca0a6dd" + ], + "markers": "python_version < '3.2'", + "version": "==1.5" + }, + "backports.lzma": { + "hashes": [ + "sha256:50829db66f0445442f6c796bba0ca62d1f87f54760c4682b6d1489e729a43744" + ], + "index": "pypi", + "version": "==0.0.13" + }, + "backports.shutil-get-terminal-size": { + "hashes": [ + "sha256:0975ba55054c15e346944b38956a4c9cbee9009391e41b86c68990effb8c1f64", + "sha256:713e7a8228ae80341c70586d1cc0a8caa5207346927e23d09dcbcaf18eadec80" + ], + "markers": "python_version == '2.7'", + "version": "==1.0.0" + }, + "backports.weakref": { + "hashes": [ + "sha256:81bc9b51c0abc58edc76aefbbc68c62a787918ffe943a37947e162c3f8e19e82", + "sha256:bc4170a29915f8b22c9e7c4939701859650f2eb84184aee80da329ac0b9825c2" + ], + "version": "==1.0.post1" + }, + "billiard": { + "hashes": [ + "sha256:756bf323f250db8bf88462cd042c992ba60d8f5e07fc5636c24ba7d6f4261d84" + ], + "version": "==3.6.0.0" + }, + "bincopy": { + "hashes": [ + "sha256:61d02c09910635599127056d2707c22bfa310cb31f935fbfdda406639017717e", + "sha256:a0e31dc5de70bffaf717bb76b136857eb78ea138fb49dc5a1bf06303f103dff8" + ], + "index": "pypi", + "version": "==16.0.0" + }, + "bleach": { + "hashes": [ + "sha256:978e758599b54cd3caa2e160d74102879b230ea8dc93871d0783721eef58bc65", + "sha256:e67f46adcec78dbc3c04462f3aba3213a673d5652eba2609ed1ef15492a44b8d" + ], + "index": "pypi", + "version": "==1.5.0" + }, + "boto": { + "hashes": [ + "sha256:147758d41ae7240dc989f0039f27da8ca0d53734be0eb869ef16e3adcfa462e8", + "sha256:ea0d3b40a2d852767be77ca343b58a9e3a4b00d9db440efb8da74b4e58025e5a" + ], + "index": "pypi", + "version": "==2.49.0" + }, + "boto3": { + "hashes": [ + "sha256:794a9a4b6a9e40c1ac57a377de609872d28d62afe4295c48cdc1b1c92f96ab8e", + "sha256:962b078568cc520869ea2842f307864c9abc30ad5ed160e12b2a89debf220161" + ], + "index": "pypi", + "version": "==1.9.168" + }, + "botocore": { + "hashes": [ + "sha256:675f2b66af486dd02f5825601bb0c8378773999f8705c6f75450849ca41fed80", + "sha256:c3fc314c0e0aa13aa024d272d991e23d37550050abf96b3c7dea889ed1743723" + ], + "version": "==1.12.168" + }, + "celery": { + "hashes": [ + "sha256:4c4532aa683f170f40bd76f928b70bc06ff171a959e06e71bf35f2f9d6031ef9", + "sha256:528e56767ae7e43a16cfef24ee1062491f5754368d38fcfffa861cdb9ef219be" + ], + "index": "pypi", + "version": "==4.3.0" + }, + "certifi": { + "hashes": [ + "sha256:59b7658e26ca9c7339e00f8f4636cdfe59d34fa37b9b04f6f9e9926b3cece1a5", + "sha256:b26104d6835d1f5e49452a26eb2ff87fe7090b89dfcaee5ea2212697e1e1d7ae" + ], + "version": "==2019.3.9" + }, + "cffi": { + "hashes": [ + "sha256:041c81822e9f84b1d9c401182e174996f0bae9991f33725d059b771744290774", + "sha256:046ef9a22f5d3eed06334d01b1e836977eeef500d9b78e9ef693f9380ad0b83d", + "sha256:066bc4c7895c91812eff46f4b1c285220947d4aa46fa0a2651ff85f2afae9c90", + "sha256:066c7ff148ae33040c01058662d6752fd73fbc8e64787229ea8498c7d7f4041b", + "sha256:2444d0c61f03dcd26dbf7600cf64354376ee579acad77aef459e34efcb438c63", + "sha256:300832850b8f7967e278870c5d51e3819b9aad8f0a2c8dbe39ab11f119237f45", + "sha256:34c77afe85b6b9e967bd8154e3855e847b70ca42043db6ad17f26899a3df1b25", + "sha256:46de5fa00f7ac09f020729148ff632819649b3e05a007d286242c4882f7b1dc3", + "sha256:4aa8ee7ba27c472d429b980c51e714a24f47ca296d53f4d7868075b175866f4b", + "sha256:4d0004eb4351e35ed950c14c11e734182591465a33e960a4ab5e8d4f04d72647", + "sha256:4e3d3f31a1e202b0f5a35ba3bc4eb41e2fc2b11c1eff38b362de710bcffb5016", + "sha256:50bec6d35e6b1aaeb17f7c4e2b9374ebf95a8975d57863546fa83e8d31bdb8c4", + "sha256:55cad9a6df1e2a1d62063f79d0881a414a906a6962bc160ac968cc03ed3efcfb", + "sha256:5662ad4e4e84f1eaa8efce5da695c5d2e229c563f9d5ce5b0113f71321bcf753", + "sha256:59b4dc008f98fc6ee2bb4fd7fc786a8d70000d058c2bbe2698275bc53a8d3fa7", + "sha256:73e1ffefe05e4ccd7bcea61af76f36077b914f92b76f95ccf00b0c1b9186f3f9", + "sha256:a1f0fd46eba2d71ce1589f7e50a9e2ffaeb739fb2c11e8192aa2b45d5f6cc41f", + "sha256:a2e85dc204556657661051ff4bab75a84e968669765c8a2cd425918699c3d0e8", + "sha256:a5457d47dfff24882a21492e5815f891c0ca35fefae8aa742c6c263dac16ef1f", + "sha256:a8dccd61d52a8dae4a825cdbb7735da530179fea472903eb871a5513b5abbfdc", + "sha256:ae61af521ed676cf16ae94f30fe202781a38d7178b6b4ab622e4eec8cefaff42", + "sha256:b012a5edb48288f77a63dba0840c92d0504aa215612da4541b7b42d849bc83a3", + "sha256:d2c5cfa536227f57f97c92ac30c8109688ace8fa4ac086d19d0af47d134e2909", + "sha256:d42b5796e20aacc9d15e66befb7a345454eef794fdb0737d1af593447c6c8f45", + "sha256:dee54f5d30d775f525894d67b1495625dd9322945e7fee00731952e0368ff42d", + "sha256:e070535507bd6aa07124258171be2ee8dfc19119c28ca94c9dfb7efd23564512", + "sha256:e1ff2748c84d97b065cc95429814cdba39bcbd77c9c85c89344b317dc0d9cbff", + "sha256:ed851c75d1e0e043cbf5ca9a8e1b13c4c90f3fbd863dacb01c0808e2b5204201" + ], + "index": "pypi", + "version": "==1.12.3" + }, + "chardet": { + "hashes": [ + "sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae", + "sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691" + ], + "index": "pypi", + "version": "==3.0.4" + }, + "click": { + "hashes": [ + "sha256:2335065e6395b9e67ca716de5f7526736bfa6ceead690adf616d925bdc622b13", + "sha256:5b94b49521f6456670fdb30cd82a4eca9412788a93fa6dd6df72c94d5a8ff2d7" + ], + "version": "==7.0" + }, + "cloudpickle": { + "hashes": [ + "sha256:603244e0f552b72a267d47a7d9b347b27a3430f58a0536037a290e7e0e212ecf", + "sha256:b8ba7e322f2394b9bbbdc1c976e6442c2c02acc784cb9e553cee9186166a6890" + ], + "version": "==1.2.1" + }, + "configparser": { + "hashes": [ + "sha256:8be81d89d6e7b4c0d4e44bcc525845f6da25821de80cb5e06e7e0238a2899e32", + "sha256:da60d0014fd8c55eb48c1c5354352e363e2d30bbf7057e5e171a468390184c75" + ], + "markers": "python_version == '2.7'", + "version": "==3.7.4" + }, + "control": { + "hashes": [ + "sha256:726e8c36a253a54c8886df31f860d740d70de4f8b041421d5df078c3bff3aadb" + ], + "index": "pypi", + "version": "==0.8.2" + }, + "cryptography": { + "hashes": [ + "sha256:24b61e5fcb506424d3ec4e18bca995833839bf13c59fc43e530e488f28d46b8c", + "sha256:25dd1581a183e9e7a806fe0543f485103232f940fcfc301db65e630512cce643", + "sha256:3452bba7c21c69f2df772762be0066c7ed5dc65df494a1d53a58b683a83e1216", + "sha256:41a0be220dd1ed9e998f5891948306eb8c812b512dc398e5a01846d855050799", + "sha256:5751d8a11b956fbfa314f6553d186b94aa70fdb03d8a4d4f1c82dcacf0cbe28a", + "sha256:5f61c7d749048fa6e3322258b4263463bfccefecb0dd731b6561cb617a1d9bb9", + "sha256:72e24c521fa2106f19623a3851e9f89ddfdeb9ac63871c7643790f872a305dfc", + "sha256:7b97ae6ef5cba2e3bb14256625423413d5ce8d1abb91d4f29b6d1a081da765f8", + "sha256:961e886d8a3590fd2c723cf07be14e2a91cf53c25f02435c04d39e90780e3b53", + "sha256:96d8473848e984184b6728e2c9d391482008646276c3ff084a1bd89e15ff53a1", + "sha256:ae536da50c7ad1e002c3eee101871d93abdc90d9c5f651818450a0d3af718609", + "sha256:b0db0cecf396033abb4a93c95d1602f268b3a68bb0a9cc06a7cff587bb9a7292", + "sha256:cfee9164954c186b191b91d4193989ca994703b2fff406f71cf454a2d3c7327e", + "sha256:e6347742ac8f35ded4a46ff835c60e68c22a536a8ae5c4422966d06946b6d4c6", + "sha256:f27d93f0139a3c056172ebb5d4f9056e770fdf0206c2f422ff2ebbad142e09ed", + "sha256:f57b76e46a58b63d1c6375017f4564a28f19a5ca912691fd2e4261b3414b618d" + ], + "index": "pypi", + "version": "==2.7" + }, + "cycler": { + "hashes": [ + "sha256:1d8a5ae1ff6c5cf9b93e8811e581232ad8920aeec647c37316ceac982b08cb2d", + "sha256:cd7b2d1018258d7247a71425e9f26463dfb444d411c39569972f4ce586b0c9d8" + ], + "version": "==0.10.0" + }, + "cython": { + "hashes": [ + "sha256:0afa0b121b89de619e71587e25702e2b7068d7da2164c47e6eee80c17823a62f", + "sha256:1c608ba76f7a20cc9f0c021b7fe5cb04bc1a70327ae93a9298b1bc3e0edddebe", + "sha256:26229570d6787ff3caa932fe9d802960f51a89239b990d275ae845405ce43857", + "sha256:2a9deafa437b6154cac2f25bb88e0bfd075a897c8dc847669d6f478d7e3ee6b1", + "sha256:2f28396fbce6d9d68a40edbf49a6729cf9d92a4d39ff0f501947a89188e9099f", + "sha256:3983dd7b67297db299b403b29b328d9e03e14c4c590ea90aa1ad1d7b35fb178b", + "sha256:4100a3f8e8bbe47d499cdac00e56d5fe750f739701ea52dc049b6c56f5421d97", + "sha256:51abfaa7b6c66f3f18028876713c8804e73d4c2b6ceddbcbcfa8ec62429377f0", + "sha256:61c24f4554efdb8fb1ac6c8e75dab301bcdf2b7b739ed0c2b267493bb43163c5", + "sha256:700ccf921b2fdc9b23910e95b5caae4b35767685e0812343fa7172409f1b5830", + "sha256:7b41eb2e792822a790cb2a171df49d1a9e0baaa8e81f58077b7380a273b93d5f", + "sha256:803987d3b16d55faa997bfc12e8b97f1091f145930dee229b020487aed8a1f44", + "sha256:99af5cfcd208c81998dcf44b3ca466dee7e17453cfb50e98b87947c3a86f8753", + "sha256:9faea1cca34501c7e139bc7ef8e504d532b77865c58592493e2c154a003b450f", + "sha256:a7ba4c9a174db841cfee9a0b92563862a0301d7ca543334666c7266b541f141a", + "sha256:b26071c2313d1880599c69fd831a07b32a8c961ba69d7ccbe5db1cd8d319a4ca", + "sha256:b49dc8e1116abde13a3e6a9eb8da6ab292c5a3325155fb872e39011b110b37e6", + "sha256:bd40def0fd013569887008baa6da9ca428e3d7247adeeaeada153006227bb2e7", + "sha256:bfd0db770e8bd4e044e20298dcae6dfc42561f85d17ee546dcd978c8b23066ae", + "sha256:c2fad1efae5889925c8fd7867fdd61f59480e4e0b510f9db096c912e884704f1", + "sha256:c81aea93d526ccf6bc0b842c91216ee9867cd8792f6725a00f19c8b5837e1715", + "sha256:da786e039b4ad2bce3d53d4799438cf1f5e01a0108f1b8d78ac08e6627281b1a", + "sha256:deab85a069397540987082d251e9c89e0e5b2e3e044014344ff81f60e211fc4b", + "sha256:e3f1e6224c3407beb1849bdc5ae3150929e593e4cffff6ca41c6ec2b10942c80", + "sha256:e74eb224e53aae3943d66e2d29fe42322d5753fd4c0641329bccb7efb3a46552", + "sha256:ee697c7ea65cb14915a64f36874da8ffc2123df43cf8bc952172e04a26656cd6", + "sha256:f37792b16d11606c28e428460bd6a3d14b8917b109e77cdbe4ca78b0b9a52c87", + "sha256:fd2906b54cbf879c09d875ad4e4687c58d87f5ed03496063fec1c9065569fd5d" + ], + "index": "pypi", + "version": "==0.29.10" + }, + "datadog": { + "hashes": [ + "sha256:0e33727bd9ef0b8201359accdf12f61fb58ab541bf4062693aca16653f8e7a0a", + "sha256:995e51d142ae3624c86c78369b268f23386bb207df5345d718c241718387875c" + ], + "index": "pypi", + "version": "==0.29.3" + }, + "decorator": { + "hashes": [ + "sha256:86156361c50488b84a3f148056ea716ca587df2f0de1d34750d35c21312725de", + "sha256:f069f3a01830ca754ba5258fde2278454a0b5b79e0d7f5c13b3b97e57d4acff6" + ], + "index": "pypi", + "version": "==4.4.0" + }, + "defusedxml": { + "hashes": [ + "sha256:6687150770438374ab581bb7a1b327a847dd9c5749e396102de3fad4e8a3ef93", + "sha256:f684034d135af4c6cbb949b8a4d2ed61634515257a67299e5f940fbaa34377f5" + ], + "version": "==0.6.0" + }, + "dlib": { + "hashes": [ + "sha256:92587c81b0165e933593f505fdf099dface0d0f8ec874b1d8655fc774598911f" + ], + "index": "pypi", + "version": "==19.17.0" + }, + "docutils": { + "hashes": [ + "sha256:02aec4bd92ab067f6ff27a38a38a41173bf01bed8f89157768c1573f53e474a6", + "sha256:51e64ef2ebfb29cae1faa133b3710143496eca21c530f3f71424d77687764274", + "sha256:7a4bd47eaf6596e1295ecb11361139febe29b084a87bf005bf899f9a42edc3c6" + ], + "version": "==0.14" + }, + "dominate": { + "hashes": [ + "sha256:4076735c0745fe771e57b2313dbb4bfeec42731816ee23cee509f66e8912aa51", + "sha256:4b9fd42d2824b79761799590697db45bf93daad511b130c50513af38da33df9b" + ], + "index": "pypi", + "version": "==2.3.5" + }, + "elasticsearch": { + "hashes": [ + "sha256:cbc73831c63fa2824538df76fcb2c4be007b43dbd9e7788ae70ea6d24109925b", + "sha256:d1b176b87a7fb75dca82978c82a4023e8b21cbc98f4018cb51190fb0b8b43764" + ], + "index": "pypi", + "version": "==7.0.2" + }, + "entium": { + "hashes": [ + "sha256:233f39c6b5477e0c6fffd8d5cb7fc9df9deab80c79c7fb77e91f6d046782b0ce", + "sha256:4b14b4810a97ab041b629a0b59d21a98f5e197ee623d7b14925755ec4fd6888a" + ], + "index": "pypi", + "version": "==0.1.4" + }, + "entrypoints": { + "hashes": [ + "sha256:589f874b313739ad35be6e0cd7efde2a4e9b6fea91edcc34e58ecbb8dbe56d19", + "sha256:c70dd71abe5a8c85e55e12c19bd91ccfeec11a6e99044204511f9ed547d48451" + ], + "version": "==0.3" + }, + "enum34": { + "hashes": [ + "sha256:2d81cbbe0e73112bdfe6ef8576f2238f2ba27dd0d55752a776c41d38b7da2850", + "sha256:644837f692e5f550741432dd3f223bbb9852018674981b1664e5dc339387588a", + "sha256:6bd0f6ad48ec2aa117d3d141940d484deccda84d4fcd884f5c3d93c23ecd8c79", + "sha256:8ad8c4783bf61ded74527bffb48ed9b54166685e4230386a9ed9b1279e2df5b1" + ], + "markers": "python_version < '3'", + "version": "==1.1.6" + }, + "fastcluster": { + "hashes": [ + "sha256:0024b1304d4618a32900473b809265694bc6d0a10bfbc272407443318644d405", + "sha256:0b33b076ea98939742e0734e944c903c8c67af3eecd5a9f8b4349407c1affdd3", + "sha256:244d400a81d23b48f2b825e50e99e1ff3c7d2be2acc40942e3359b4deef68483", + "sha256:2bb3bf8e1c7af42e47ef24bc2386a1d3e6ec8dc5e6be4123a491a36b89227b49", + "sha256:539d84d43fbe541a38d94c84bf0469c430cb7cda488364941ce57f680a07b091", + "sha256:5e7d81385bbc2148c554c4aaa32e26a00fbadc1190d5bad9c8719f6432629307", + "sha256:642e4d92220c1deede1e89409c5ad366e4a3f3ed55fff0a4e325d4eb2574d65a", + "sha256:66c868fdfc161e5c45cdf399f1274216602ea82c9fc46c632c9602dbaa149840", + "sha256:6952c9d25b3ea60d6a53ee92205e7f16cc6baf7caa4776fb1e55dc6e8e2965f2", + "sha256:8606da6f6f51f81c3b4e000edeb8668711a1769a6ebf3c99ab98f9c6d2fb7534", + "sha256:8d552d29ed054ce20f5bb0445b51bd7b6b8088fdae334625b4a9950189dcc2bf", + "sha256:922735fde2848a6f0478c6968048a16a5d3d6ba6e1d1a9596d578b59dce719d7", + "sha256:9f3cd227a9ebeec090e4186a63e46cd87d121968bd1d45ea8a7c2d483bc082fb", + "sha256:a382cb411610ca06a69e7b131239f0bb02961fec762d5b6804e653a32cd5ab52", + "sha256:a986b3afe823bcaea3dad9de1485b176c6dd5b0e2f154ede71aaf6635e82e159", + "sha256:b1902ab52418c6f4c2f3f7439aea711c6b5aa9bbb4c97b6d4b0c6f5e5c894342", + "sha256:bb56f6c7343bbb68beb1ffd13abdb87ce7a84ab391b3a4e63ed5c02b2d1ce46f", + "sha256:c2e5d11f5f96e6861fd632246f18bc6592ac439f236caffd4d2a75697a6f8969", + "sha256:c61973bb16117ee16b7642ff9da8e0899fb4d5eb5d0cc9c56d3269551ccd6307", + "sha256:d2deec11a6625c5578325f4dd10980e2981d1f1d1e658c7c79f2497377f92bdf", + "sha256:e0f2feb03f67b12f25538aa05b1150c7a2c1cd1c21ad7d0bde94e8169ef46627", + "sha256:e32e7287c47291eca2c83cd5cc6a5007eff2da00c12ac21fd721a16d0c428059", + "sha256:e889ea36c4e469ff3fb2a6a868c8e557fc988a81cd1cf3d09876107e59ee9cbd", + "sha256:e96f3b65e3748f2be06aa0977a00872ddeca4f8959703126f2b103978243bbdd" + ], + "index": "pypi", + "version": "==1.1.25" + }, + "fasteners": { + "hashes": [ + "sha256:007e4d2b2d4a10093f67e932e5166722d2eab83b77724156e92ad013c6226574", + "sha256:3a176da6b70df9bb88498e1a18a9e4a8579ed5b9141207762368a1017bf8f5ef" + ], + "index": "pypi", + "version": "==0.15" + }, + "flask": { + "hashes": [ + "sha256:ad7c6d841e64296b962296c2c2dabc6543752985727af86a975072dea984b6f3", + "sha256:e7d32475d1de5facaa55e3958bc4ec66d3762076b074296aa50ef8fdc5b9df61" + ], + "index": "pypi", + "version": "==1.0.3" + }, + "flask-cors": { + "hashes": [ + "sha256:72170423eb4612f0847318afff8c247b38bd516b7737adfc10d1c2cdbb382d16", + "sha256:f4d97201660e6bbcff2d89d082b5b6d31abee04b1b3003ee073a6fd25ad1d69a" + ], + "index": "pypi", + "version": "==3.0.8" + }, + "flask-socketio": { + "hashes": [ + "sha256:aced332903522a52822fb1e21744549510ce8b26e074422d4cd9aff68e43be5b", + "sha256:f6f7e0205f0dd92d98a87e3f6d26d94ade29ca380ba383b505070674c804ae2e" + ], + "index": "pypi", + "version": "==4.1.0" + }, + "funcsigs": { + "hashes": [ + "sha256:330cc27ccbf7f1e992e69fef78261dc7c6569012cf397db8d3de0234e6c937ca", + "sha256:a7bb0f2cf3a3fd1ab2732cb49eba4252c2af4240442415b4abce3b87022a8f50" + ], + "markers": "python_version < '3.3'", + "version": "==1.0.2" + }, + "functools32": { + "hashes": [ + "sha256:89d824aa6c358c421a234d7f9ee0bd75933a67c29588ce50aaa3acdf4d403fa0", + "sha256:f6253dfbe0538ad2e387bd8fdfd9293c925d63553f5813c4e587745416501e6d" + ], + "markers": "python_version < '3'", + "version": "==3.2.3.post2" + }, + "future": { + "hashes": [ + "sha256:67045236dcfd6816dc439556d009594abf643e5eb48992e36beac09c2ca659b8" + ], + "index": "pypi", + "version": "==0.17.1" + }, + "futures": { + "hashes": [ + "sha256:9ec02aa7d674acb8618afb127e27fde7fc68994c0437ad759fa094a574adb265", + "sha256:ec0a6cb848cc212002b9828c3e34c675e0c9ff6741dc445cab6fdd4e1085d1f1" + ], + "markers": "python_version < '3.2'", + "version": "==3.2.0" + }, + "gast": { + "hashes": [ + "sha256:fe939df4583692f0512161ec1c880e0a10e71e6a232da045ab8edd3756fbadf0" + ], + "version": "==0.2.2" + }, + "geoalchemy2": { + "hashes": [ + "sha256:0d1c9ea3ec13f6a522ccc3ffd2569ac524a6c6e80bab883e8805b28c48e77143", + "sha256:4dc4c6c2bda0fc82cccab4aaff185a6570e13a5351d85e29e12984a55d4138ee" + ], + "index": "pypi", + "version": "==0.6.3" + }, + "gevent": { + "hashes": [ + "sha256:0774babec518a24d9a7231d4e689931f31b332c4517a771e532002614e270a64", + "sha256:0e1e5b73a445fe82d40907322e1e0eec6a6745ca3cea19291c6f9f50117bb7ea", + "sha256:0ff2b70e8e338cf13bedf146b8c29d475e2a544b5d1fe14045aee827c073842c", + "sha256:107f4232db2172f7e8429ed7779c10f2ed16616d75ffbe77e0e0c3fcdeb51a51", + "sha256:14b4d06d19d39a440e72253f77067d27209c67e7611e352f79fe69e0f618f76e", + "sha256:1b7d3a285978b27b469c0ff5fb5a72bcd69f4306dbbf22d7997d83209a8ba917", + "sha256:1eb7fa3b9bd9174dfe9c3b59b7a09b768ecd496debfc4976a9530a3e15c990d1", + "sha256:2711e69788ddb34c059a30186e05c55a6b611cb9e34ac343e69cf3264d42fe1c", + "sha256:28a0c5417b464562ab9842dd1fb0cc1524e60494641d973206ec24d6ec5f6909", + "sha256:3249011d13d0c63bea72d91cec23a9cf18c25f91d1f115121e5c9113d753fa12", + "sha256:44089ed06a962a3a70e96353c981d628b2d4a2f2a75ea5d90f916a62d22af2e8", + "sha256:4bfa291e3c931ff3c99a349d8857605dca029de61d74c6bb82bd46373959c942", + "sha256:50024a1ee2cf04645535c5ebaeaa0a60c5ef32e262da981f4be0546b26791950", + "sha256:53b72385857e04e7faca13c613c07cab411480822ac658d97fd8a4ddbaf715c8", + "sha256:74b7528f901f39c39cdbb50cdf08f1a2351725d9aebaef212a29abfbb06895ee", + "sha256:7d0809e2991c9784eceeadef01c27ee6a33ca09ebba6154317a257353e3af922", + "sha256:896b2b80931d6b13b5d9feba3d4eebc67d5e6ec54f0cf3339d08487d55d93b0e", + "sha256:8d9ec51cc06580f8c21b41fd3f2b3465197ba5b23c00eb7d422b7ae0380510b0", + "sha256:9f7a1e96fec45f70ad364e46de32ccacab4d80de238bd3c2edd036867ccd48ad", + "sha256:ab4dc33ef0e26dc627559786a4fba0c2227f125db85d970abbf85b77506b3f51", + "sha256:d1e6d1f156e999edab069d79d890859806b555ce4e4da5b6418616322f0a3df1", + "sha256:d752bcf1b98174780e2317ada12013d612f05116456133a6acf3e17d43b71f05", + "sha256:e5bcc4270671936349249d26140c267397b7b4b1381f5ec8b13c53c5b53ab6e1" + ], + "index": "pypi", + "version": "==1.4.0" + }, + "git-pylint-commit-hook": { + "hashes": [ + "sha256:e1d39e7856b3ef0a0269121ca210dc3f5a97da158b322411e8e1185918a91b3c" + ], + "index": "pypi", + "version": "==2.5.1" + }, + "greenlet": { + "hashes": [ + "sha256:000546ad01e6389e98626c1367be58efa613fa82a1be98b0c6fc24b563acc6d0", + "sha256:0d48200bc50cbf498716712129eef819b1729339e34c3ae71656964dac907c28", + "sha256:23d12eacffa9d0f290c0fe0c4e81ba6d5f3a5b7ac3c30a5eaf0126bf4deda5c8", + "sha256:37c9ba82bd82eb6a23c2e5acc03055c0e45697253b2393c9a50cef76a3985304", + "sha256:51503524dd6f152ab4ad1fbd168fc6c30b5795e8c70be4410a64940b3abb55c0", + "sha256:8041e2de00e745c0e05a502d6e6db310db7faa7c979b3a5877123548a4c0b214", + "sha256:81fcd96a275209ef117e9ec91f75c731fa18dcfd9ffaa1c0adbdaa3616a86043", + "sha256:853da4f9563d982e4121fed8c92eea1a4594a2299037b3034c3c898cb8e933d6", + "sha256:8b4572c334593d449113f9dc8d19b93b7b271bdbe90ba7509eb178923327b625", + "sha256:9416443e219356e3c31f1f918a91badf2e37acf297e2fa13d24d1cc2380f8fbc", + "sha256:9854f612e1b59ec66804931df5add3b2d5ef0067748ea29dc60f0efdcda9a638", + "sha256:99a26afdb82ea83a265137a398f570402aa1f2b5dfb4ac3300c026931817b163", + "sha256:a19bf883b3384957e4a4a13e6bd1ae3d85ae87f4beb5957e35b0be287f12f4e4", + "sha256:a9f145660588187ff835c55a7d2ddf6abfc570c2651c276d3d4be8a2766db490", + "sha256:ac57fcdcfb0b73bb3203b58a14501abb7e5ff9ea5e2edfa06bb03035f0cff248", + "sha256:bcb530089ff24f6458a81ac3fa699e8c00194208a724b644ecc68422e1111939", + "sha256:beeabe25c3b704f7d56b573f7d2ff88fc99f0138e43480cecdfcaa3b87fe4f87", + "sha256:d634a7ea1fc3380ff96f9e44d8d22f38418c1c381d5fac680b272d7d90883720", + "sha256:d97b0661e1aead761f0ded3b769044bb00ed5d33e1ec865e891a8b128bf7c656" + ], + "markers": "platform_python_implementation == 'CPython'", + "version": "==0.4.15" + }, + "grpcio": { + "hashes": [ + "sha256:0232add03144dd3cf9b660e2718244cb8e175370dca4d3855cb4e489a7811b53", + "sha256:0f20e6dcb1b8662cdca033bb97c0a8116a5343e3ebc7f71c5fe7f89039978350", + "sha256:10b07a623d33d4966f45c85d410bc6a79c5ac6341f06c3beda6c22be12cbfe07", + "sha256:10c0476d5a52d21f402fc073745dc43b87cc8e080a1f49bbff4e1059019310fb", + "sha256:289dae0b35c59d191c524e976dd0a6f8c995d2062e72621eb866ad0f4472a635", + "sha256:2be726f16142d358a0df1e81d583d6820ee561a7856a79cca2fbe49989308be7", + "sha256:4338d2a81f5b4ca022e085040b3cfce19419a5ce44aa7e6810ac1df05365bed7", + "sha256:4c535b46f20e66bee3097583231977e721acdfcb1671d1490c99b7be8902ce18", + "sha256:557154aef70a0e979700cc9528bc8b606b668084a29a0d57dbc4b06b078a2f1c", + "sha256:5bfdd7e6647498f979dc46583723c852d97b25afe995d55aa1c76a5f9816bc1f", + "sha256:87d8943ae7aa6ca5bbad732867d7f17d2550e4966a0c15b52088e8b579422e47", + "sha256:89d8719d8de4d137678f7caa979e1b0a6fd4026f8096ceef8c2d164bbabefaf2", + "sha256:9c3f4af989ce860710ac1864dc2e867dd87e6cee51a2368df1b253596868e52f", + "sha256:9da52c3c728883aee429bb7c315049f50b2139f680cd86bb1165418e4f93a982", + "sha256:9e9736659987beab42d18525ed10d21f80a1ba8389eac03425fbfd5684e6bbf0", + "sha256:9ebcbb1a054cab362d29d3be571d43d6b9b23302d9fc4b43e5327000da1680a9", + "sha256:a93e08636623e24c939851e2e0c0140b14f524b2980c9cdc4ea52b70a871c7e0", + "sha256:ac322d86d1a079e0a118d544443ee16f320af0062c191b4754c0c6ec2fc79310", + "sha256:b1fb101459868f52df6b61e7bb13375e50badf17a160e39fe1d51ae19e53f461", + "sha256:b39aac96cceac624a23d540473835086a3ffa77c91030189988c073488434493", + "sha256:b65507bc273c6dbf539175a786a344cc0ac78d50e5584f72c6599733f8a3301f", + "sha256:be5bb6e47417e537c884a2e2ff2e1a8b2c064a998fcfdfcc67528d4e63e7ebaf", + "sha256:c92de6a28a909c4f460dc1bbbcb50d676cf0b1f40224b222761f73fdd851b522", + "sha256:c9f5962eb7fa7607b20eb0e4f59ed35829bd600fc0eacb626a6db83229a3e445", + "sha256:d00bdf9c546ed6e649f785c55b05288e8b2dbb6bf2eb74b6c579fa0d591d35bd", + "sha256:da804b1dd8293bd9d61b1e6ea989c887ba042a808a4fbdd80001cfa059aafed2", + "sha256:ead6c5aa3e807345913649c3be395aaca2bbb2d225f18b8f31f37eab225508f6", + "sha256:eb4d81550ce6f826af4ec6e8d98be347fe96291d718bf115c3f254621ae8d98d", + "sha256:ef6a18ec8fd32ec81748fe720544ea2fb2d2dc50fd6d06739d5e2eb8f0626a1c", + "sha256:fad42835656e0b6d3b7ffc900598e776722e30f43b7234a48f2576ca30f31a47", + "sha256:fb98dbfee0d963b49ae5754554028cf62e6bd695f22de16d242ba9d2f0b7339b", + "sha256:fb9cd9bb8d26dc17c2dd715a46bca3a879ec8283879b164e85863110dc6e3b2a" + ], + "version": "==1.21.1" + }, + "gunicorn": { + "hashes": [ + "sha256:aa8e0b40b4157b36a5df5e599f45c9c76d6af43845ba3b3b0efe2c70473c2471", + "sha256:fa2662097c66f920f53f70621c6c58ca4a3c4d3434205e608e121b5b3b71f4f3" + ], + "index": "pypi", + "version": "==19.9.0" + }, + "h5py": { + "hashes": [ + "sha256:05750b91640273c69989c657eaac34b091abdd75efc8c4824c82aaf898a2da0a", + "sha256:082a27208aa3a2286e7272e998e7e225b2a7d4b7821bd840aebf96d50977abbb", + "sha256:08e2e8297195f9e813e894b6c63f79372582787795bba2014a2db6a2de95f713", + "sha256:0dd2adeb2e9de5081eb8dcec88874e7fd35dae9a21557be3a55a3c7d491842a4", + "sha256:0f94de7a10562b991967a66bbe6dda9808e18088676834c0a4dcec3fdd3bcc6f", + "sha256:106e42e2e01e486a3d32eeb9ba0e3a7f65c12fa8998d63625fa41fb8bdc44cdb", + "sha256:1606c66015f04719c41a9863c156fc0e6b992150de21c067444bcb82e7d75579", + "sha256:1854c4beff9961e477e133143c5e5e355dac0b3ebf19c52cf7cc1b1ef757703c", + "sha256:1e9fb6f1746500ea91a00193ce2361803c70c6b13f10aae9a33ad7b5bd28e800", + "sha256:2cca17e80ddb151894333377675db90cd0279fa454776e0a4f74308376afd050", + "sha256:30e365e8408759db3778c361f1e4e0fe8e98a875185ae46c795a85e9bafb9cdf", + "sha256:3206bac900e16eda81687d787086f4ffd4f3854980d798e191a9868a6510c3ae", + "sha256:3c23d72058647cee19b30452acc7895621e2de0a0bd5b8a1e34204b9ea9ed43c", + "sha256:407b5f911a83daa285bbf1ef78a9909ee5957f257d3524b8606be37e8643c5f0", + "sha256:4162953714a9212d373ac953c10e3329f1e830d3c7473f2a2e4f25dd6241eef0", + "sha256:5fc7aba72a51b2c80605eba1c50dbf84224dcd206279d30a75c154e5652e1fe4", + "sha256:713ac19307e11de4d9833af0c4bd6778bde0a3d967cafd2f0f347223711c1e31", + "sha256:71b946d80ef3c3f12db157d7778b1fe74a517ca85e94809358b15580983c2ce2", + "sha256:8cc4aed71e20d87e0a6f02094d718a95252f11f8ed143bc112d22167f08d4040", + "sha256:9d41ca62daf36d6b6515ab8765e4c8c4388ee18e2a665701fef2b41563821002", + "sha256:a744e13b000f234cd5a5b2a1f95816b819027c57f385da54ad2b7da1adace2f3", + "sha256:b087ee01396c4b34e9dc41e3a6a0442158206d383c19c7d0396d52067b17c1cb", + "sha256:b0f03af381d33306ce67d18275b61acb4ca111ced645381387a02c8a5ee1b796", + "sha256:b9e4b8dfd587365bdd719ae178fa1b6c1231f81280b1375eef8626dfd8761bf3", + "sha256:c5dd4ec75985b99166c045909e10f0534704d102848b1d9f0992720e908928e7", + "sha256:d2b82f23cd862a9d05108fe99967e9edfa95c136f532a71cb3d28dc252771f50", + "sha256:e58a25764472af07b7e1c4b10b0179c8ea726446c7141076286e41891bf3a563", + "sha256:f3b49107fbfc77333fc2b1ef4d5de2abcd57e7ea3a1482455229494cf2da56ce" + ], + "index": "pypi", + "version": "==2.9.0" + }, + "hexdump": { + "hashes": [ + "sha256:d781a43b0c16ace3f9366aade73e8ad3a7bd5137d58f0b45ab2d3f54876f20db" + ], + "index": "pypi", + "version": "==3.3" + }, + "html5lib": { + "hashes": [ + "sha256:2612a191a8d5842bfa057e41ba50bbb9dcb722419d2408c78cff4758d0754868" + ], + "index": "pypi", + "version": "==0.9999999" + }, + "humanfriendly": { + "hashes": [ + "sha256:23057b10ad6f782e7bc3a20e3cb6768ab919f619bbdc0dd75691121bbde5591d", + "sha256:33ee8ceb63f1db61cce8b5c800c531e1a61023ac5488ccde2ba574a85be00a85" + ], + "version": "==4.18" + }, + "idna": { + "hashes": [ + "sha256:c357b3f628cf53ae2c4c05627ecc484553142ca23264e593d327bcde5e9c3407", + "sha256:ea8b7f6188e6fa117537c3df7da9fc686d485087abf6ac197f9c46432f7e4a3c" + ], + "index": "pypi", + "version": "==2.8" + }, + "imageio": { + "hashes": [ + "sha256:1a2bbbb7cd38161340fa3b14d806dfbf914abf3ee6fd4592af2afb87d049f209", + "sha256:42e65aadfc3d57a1043615c92bdf6319b67589e49a0aae2b985b82144aceacad" + ], + "index": "pypi", + "version": "==2.5.0" + }, + "intervaltree": { + "hashes": [ + "sha256:cb4f61c81dcb4fea6c09903f3599015a83c9bdad1f0bbd232495e6681e19e273" + ], + "index": "pypi", + "version": "==3.0.2" + }, + "ipaddress": { + "hashes": [ + "sha256:64b28eec5e78e7510698f6d4da08800a5c575caa4a286c93d651c5d3ff7b6794", + "sha256:b146c751ea45cad6188dd6cf2d9b757f6f4f8d6ffb96a023e6f2e26eea02a72c" + ], + "markers": "python_version < '3'", + "version": "==1.0.22" + }, + "ipykernel": { + "hashes": [ + "sha256:56d82987472f4b14ab0214e4aef55def006671885d285cd8821f2600861215a6", + "sha256:59b0855082d021f533cff477e1bb619e663b6aab11309a05bf88eaec9f53faed", + "sha256:699103c8e64886e3ec7053f2a6aa83bb90426063526f63a818732ff385202bad" + ], + "index": "pypi", + "version": "==4.10.0" + }, + "ipython": { + "hashes": [ + "sha256:0371b7e4bd74954a35086eac949beeac5b1c9f5ce231e2e77df2286a293765e3", + "sha256:37101b8cbe072fe17bff100bc03d096404e4a9a0357097aeb5b61677c042cab1", + "sha256:4bac649857611baaaf76bc82c173aa542f7486446c335fe1a6c05d0d491c8906" + ], + "index": "pypi", + "version": "==5.8.0" + }, + "ipython-genutils": { + "hashes": [ + "sha256:72dd37233799e619666c9f639a9da83c34013a73e8bbc79a7a6348d93c61fab8", + "sha256:eb2e116e75ecef9d4d228fdc66af54269afa26ab4463042e33785b887c628ba8" + ], + "version": "==0.2.0" + }, + "ipywidgets": { + "hashes": [ + "sha256:0f2b5cde9f272cb49d52f3f0889fdd1a7ae1e74f37b48dac35a83152780d2b7b", + "sha256:a3e224f430163f767047ab9a042fc55adbcab0c24bbe6cf9f306c4f89fdf0ba3" + ], + "version": "==7.4.2" + }, + "isodate": { + "hashes": [ + "sha256:2e364a3d5759479cdb2d37cce6b9376ea504db2ff90252a2e5b7cc89cc9ff2d8", + "sha256:aa4d33c06640f5352aca96e4b81afd8ab3b47337cc12089822d6f322ac772c81" + ], + "version": "==0.6.0" + }, + "isort": { + "hashes": [ + "sha256:c40744b6bc5162bbb39c1257fe298b7a393861d50978b565f3ccd9cb9de0182a", + "sha256:f57abacd059dc3bd666258d1efb0377510a89777fda3e3274e3c01f7c03ae22d" + ], + "version": "==4.3.20" + }, + "itsdangerous": { + "hashes": [ + "sha256:321b033d07f2a4136d3ec762eac9f16a10ccd60f53c0c91af90217ace7ba1f19", + "sha256:b12271b2047cb23eeb98c8b5622e2e5c5e9abd9784a153e9d8ef9cb4dd09d749" + ], + "version": "==1.1.0" + }, + "jinja2": { + "hashes": [ + "sha256:065c4f02ebe7f7cf559e49ee5a95fb800a9e4528727aec6f24402a5374c65013", + "sha256:14dd6caf1527abb21f08f86c784eac40853ba93edb79552aa1e4b8aef1b61c7b" + ], + "index": "pypi", + "version": "==2.10.1" + }, + "jmespath": { + "hashes": [ + "sha256:3720a4b1bd659dd2eecad0666459b9788813e032b83e7ba58578e48254e0a0e6", + "sha256:bde2aef6f44302dfb30320115b17d030798de8c4110e28d5cf6cf91a7a31074c" + ], + "version": "==0.9.4" + }, + "joblib": { + "hashes": [ + "sha256:21e0c34a69ad7fde4f2b1f3402290e9ec46f545f15f1541c582edfe05d87b63a", + "sha256:315d6b19643ec4afd4c41c671f9f2d65ea9d787da093487a81ead7b0bac94524" + ], + "index": "pypi", + "version": "==0.13.2" + }, + "json-logging-py": { + "hashes": [ + "sha256:118b1fe1f4eacaea6370e5b9710d0f6d0c0a4599aef9d5b9875a6a579974fc9a" + ], + "index": "pypi", + "version": "==0.2" + }, + "jsonschema": { + "hashes": [ + "sha256:0c0a81564f181de3212efa2d17de1910f8732fa1b71c42266d983cd74304e20d", + "sha256:a5f6559964a3851f59040d3b961de5e68e70971afb88ba519d27e6a039efff1a" + ], + "version": "==3.0.1" + }, + "jupyter": { + "hashes": [ + "sha256:3e1f86076bbb7c8c207829390305a2b1fe836d471ed54be66a3b8c41e7f46cc7", + "sha256:5b290f93b98ffbc21c0c7e749f054b3267782166d72fa5e3ed1ed4eaf34a2b78", + "sha256:d9dc4b3318f310e34c82951ea5d6683f67bed7def4b259fafbfe4f1beb1d8e5f" + ], + "index": "pypi", + "version": "==1.0.0" + }, + "jupyter-client": { + "hashes": [ + "sha256:b5f9cb06105c1d2d30719db5ffb3ea67da60919fb68deaefa583deccd8813551", + "sha256:c44411eb1463ed77548bc2d5ec0d744c9b81c4a542d9637c7a52824e2121b987" + ], + "version": "==5.2.4" + }, + "jupyter-console": { + "hashes": [ + "sha256:3f928b817fc82cda95e431eb4c2b5eb21be5c483c2b43f424761a966bb808094", + "sha256:545dedd3aaaa355148093c5609f0229aeb121b4852995c2accfa64fe3e0e55cd" + ], + "version": "==5.2.0" + }, + "jupyter-core": { + "hashes": [ + "sha256:927d713ffa616ea11972534411544589976b2493fc7e09ad946e010aa7eb9970", + "sha256:ba70754aa680300306c699790128f6fbd8c306ee5927976cbe48adacf240c0b7" + ], + "version": "==4.4.0" + }, + "keras": { + "hashes": [ + "sha256:794d0c92c6c4122f1f0fcf3a7bc2f49054c6a54ddbef8d8ffafca62795d760b6", + "sha256:90b610a3dbbf6d257b20a079eba3fdf2eed2158f64066a7c6f7227023fd60bc9" + ], + "index": "pypi", + "version": "==2.2.4" + }, + "keras-applications": { + "hashes": [ + "sha256:5579f9a12bcde9748f4a12233925a59b93b73ae6947409ff34aa2ba258189fe5", + "sha256:df4323692b8c1174af821bf906f1e442e63fa7589bf0f1230a0b6bdc5a810c95" + ], + "version": "==1.0.8" + }, + "keras-maskrcnn": { + "hashes": [ + "sha256:7cbadcf5d8a41e64ebd19157253f0357f2c46f289584c6f58fd38a19f7cc3509" + ], + "index": "pypi", + "version": "==0.2.1" + }, + "keras-preprocessing": { + "hashes": [ + "sha256:44aee5f2c4d80c3b29f208359fcb336df80f293a0bb6b1c738da43ca206656fb", + "sha256:5a8debe01d840de93d49e05ccf1c9b81ae30e210d34dacbcc47aeb3049b528e5" + ], + "version": "==1.1.0" + }, + "keras-resnet": { + "hashes": [ + "sha256:8ce27ba782d1b45b127af51208aefdceb2de8d2c54646bac5fc786506ce558c0" + ], + "version": "==0.2.0" + }, + "keras-retinanet": { + "hashes": [ + "sha256:257b77ca46c6846d8e9260e4eb1c77ab9b564c512bb5ebe23e72fc46b5c41899" + ], + "index": "pypi", + "version": "==0.5.0" + }, + "kiwisolver": { + "hashes": [ + "sha256:05b5b061e09f60f56244adc885c4a7867da25ca387376b02c1efc29cc16bcd0f", + "sha256:26f4fbd6f5e1dabff70a9ba0d2c4bd30761086454aa30dddc5b52764ee4852b7", + "sha256:3b2378ad387f49cbb328205bda569b9f87288d6bc1bf4cd683c34523a2341efe", + "sha256:400599c0fe58d21522cae0e8b22318e09d9729451b17ee61ba8e1e7c0346565c", + "sha256:47b8cb81a7d18dbaf4fed6a61c3cecdb5adec7b4ac292bddb0d016d57e8507d5", + "sha256:53eaed412477c836e1b9522c19858a8557d6e595077830146182225613b11a75", + "sha256:58e626e1f7dfbb620d08d457325a4cdac65d1809680009f46bf41eaf74ad0187", + "sha256:5a52e1b006bfa5be04fe4debbcdd2688432a9af4b207a3f429c74ad625022641", + "sha256:5c7ca4e449ac9f99b3b9d4693debb1d6d237d1542dd6a56b3305fe8a9620f883", + "sha256:682e54f0ce8f45981878756d7203fd01e188cc6c8b2c5e2cf03675390b4534d5", + "sha256:79bfb2f0bd7cbf9ea256612c9523367e5ec51d7cd616ae20ca2c90f575d839a2", + "sha256:7f4dd50874177d2bb060d74769210f3bce1af87a8c7cf5b37d032ebf94f0aca3", + "sha256:8944a16020c07b682df861207b7e0efcd2f46c7488619cb55f65882279119389", + "sha256:8aa7009437640beb2768bfd06da049bad0df85f47ff18426261acecd1cf00897", + "sha256:939f36f21a8c571686eb491acfffa9c7f1ac345087281b412d63ea39ca14ec4a", + "sha256:9733b7f64bd9f807832d673355f79703f81f0b3e52bfce420fc00d8cb28c6a6c", + "sha256:a02f6c3e229d0b7220bd74600e9351e18bc0c361b05f29adae0d10599ae0e326", + "sha256:a0c0a9f06872330d0dd31b45607197caab3c22777600e88031bfe66799e70bb0", + "sha256:acc4df99308111585121db217681f1ce0eecb48d3a828a2f9bbf9773f4937e9e", + "sha256:b64916959e4ae0ac78af7c3e8cef4becee0c0e9694ad477b4c6b3a536de6a544", + "sha256:d3fcf0819dc3fea58be1fd1ca390851bdb719a549850e708ed858503ff25d995", + "sha256:d52e3b1868a4e8fd18b5cb15055c76820df514e26aa84cc02f593d99fef6707f", + "sha256:db1a5d3cc4ae943d674718d6c47d2d82488ddd94b93b9e12d24aabdbfe48caee", + "sha256:e3a21a720791712ed721c7b95d433e036134de6f18c77dbe96119eaf7aa08004", + "sha256:e8bf074363ce2babeb4764d94f8e65efd22e6a7c74860a4f05a6947afc020ff2", + "sha256:f16814a4a96dc04bf1da7d53ee8d5b1d6decfc1a92a63349bb15d37b6a263dd9", + "sha256:f2b22153870ca5cf2ab9c940d7bc38e8e9089fa0f7e5856ea195e1cf4ff43d5a", + "sha256:f790f8b3dff3d53453de6a7b7ddd173d2e020fb160baff578d578065b108a05f" + ], + "version": "==1.1.0" + }, + "kombu": { + "hashes": [ + "sha256:056a31cc95b10ca4eb0d4ebcba714007b1db1c6c45c8e2d139fe91933481b00b", + "sha256:af5b0f892b081f49d95c772a241fb7687f4cc3e42c94328f118dffb1f4e161e5" + ], + "version": "==4.6.1" + }, + "lazy-object-proxy": { + "hashes": [ + "sha256:159a745e61422217881c4de71f9eafd9d703b93af95618635849fe469a283661", + "sha256:23f63c0821cc96a23332e45dfaa83266feff8adc72b9bcaef86c202af765244f", + "sha256:3b11be575475db2e8a6e11215f5aa95b9ec14de658628776e10d96fa0b4dac13", + "sha256:3f447aff8bc61ca8b42b73304f6a44fa0d915487de144652816f950a3f1ab821", + "sha256:4ba73f6089cd9b9478bc0a4fa807b47dbdb8fad1d8f31a0f0a5dbf26a4527a71", + "sha256:4f53eadd9932055eac465bd3ca1bd610e4d7141e1278012bd1f28646aebc1d0e", + "sha256:64483bd7154580158ea90de5b8e5e6fc29a16a9b4db24f10193f0c1ae3f9d1ea", + "sha256:6f72d42b0d04bfee2397aa1862262654b56922c20a9bb66bb76b6f0e5e4f9229", + "sha256:7c7f1ec07b227bdc561299fa2328e85000f90179a2f44ea30579d38e037cb3d4", + "sha256:7c8b1ba1e15c10b13cad4171cfa77f5bb5ec2580abc5a353907780805ebe158e", + "sha256:8559b94b823f85342e10d3d9ca4ba5478168e1ac5658a8a2f18c991ba9c52c20", + "sha256:a262c7dfb046f00e12a2bdd1bafaed2408114a89ac414b0af8755c696eb3fc16", + "sha256:acce4e3267610c4fdb6632b3886fe3f2f7dd641158a843cf6b6a68e4ce81477b", + "sha256:be089bb6b83fac7f29d357b2dc4cf2b8eb8d98fe9d9ff89f9ea6012970a853c7", + "sha256:bfab710d859c779f273cc48fb86af38d6e9210f38287df0069a63e40b45a2f5c", + "sha256:c10d29019927301d524a22ced72706380de7cfc50f767217485a912b4c8bd82a", + "sha256:dd6e2b598849b3d7aee2295ac765a578879830fb8966f70be8cd472e6069932e", + "sha256:e408f1eacc0a68fed0c08da45f31d0ebb38079f043328dce69ff133b95c29dc1" + ], + "version": "==1.4.1" + }, + "libarchive": { + "hashes": [ + "sha256:37e8cca1eb85d30583cdcffc58116d83abc09be7549d5d6c9ead563c0a8d7b04" + ], + "index": "pypi", + "version": "==0.4.6" + }, + "lru-dict": { + "hashes": [ + "sha256:365457660e3d05b76f1aba3e0f7fedbfcd6528e97c5115a351ddd0db488354cc" + ], + "index": "pypi", + "version": "==1.1.6" + }, + "lxml": { + "hashes": [ + "sha256:06c7616601430aa140a69f97e3116308fffe0848f543b639a5ec2e8920ae72fd", + "sha256:177202792f9842374a8077735c69c41a4282183f7851443d2beb8ee310720819", + "sha256:19317ad721ceb9e39847d11131903931e2794e447d4751ebb0d9236f1b349ff2", + "sha256:36d206e62f3e5dbaafd4ec692b67157e271f5da7fd925fda8515da675eace50d", + "sha256:387115b066c797c85f9861a9613abf50046a15aac16759bc92d04f94acfad082", + "sha256:3ce1c49d4b4a7bc75fb12acb3a6247bb7a91fe420542e6d671ba9187d12a12c2", + "sha256:4d2a5a7d6b0dbb8c37dab66a8ce09a8761409c044017721c21718659fa3365a1", + "sha256:58d0a1b33364d1253a88d18df6c0b2676a1746d27c969dc9e32d143a3701dda5", + "sha256:62a651c618b846b88fdcae0533ec23f185bb322d6c1845733f3123e8980c1d1b", + "sha256:69ff21064e7debc9b1b1e2eee8c2d686d042d4257186d70b338206a80c5bc5ea", + "sha256:7060453eba9ba59d821625c6af6a266bd68277dce6577f754d1eb9116c094266", + "sha256:7d26b36a9c4bce53b9cfe42e67849ae3c5c23558bc08363e53ffd6d94f4ff4d2", + "sha256:83b427ad2bfa0b9705e02a83d8d607d2c2f01889eb138168e462a3a052c42368", + "sha256:923d03c84534078386cf50193057aae98fa94cace8ea7580b74754493fda73ad", + "sha256:b773715609649a1a180025213f67ffdeb5a4878c784293ada300ee95a1f3257b", + "sha256:baff149c174e9108d4a2fee192c496711be85534eab63adb122f93e70aa35431", + "sha256:bca9d118b1014b4c2d19319b10a3ebed508ff649396ce1855e1c96528d9b2fa9", + "sha256:ce580c28845581535dc6000fc7c35fdadf8bea7ccb57d6321b044508e9ba0685", + "sha256:d34923a569e70224d88e6682490e24c842907ba2c948c5fd26185413cbe0cd96", + "sha256:dd9f0e531a049d8b35ec5e6c68a37f1ba6ec3a591415e6804cbdf652793d15d7", + "sha256:ecb805cbfe9102f3fd3d2ef16dfe5ae9e2d7a7dfbba92f4ff1e16ac9784dbfb0", + "sha256:ede9aad2197a0202caff35d417b671f5f91a3631477441076082a17c94edd846", + "sha256:ef2d1fc370400e0aa755aab0b20cf4f1d0e934e7fd5244f3dd4869078e4942b9", + "sha256:f2fec194a49bfaef42a548ee657362af5c7a640da757f6f452a35da7dd9f923c" + ], + "index": "pypi", + "version": "==4.3.4" + }, + "markdown": { + "hashes": [ + "sha256:2e50876bcdd74517e7b71f3e7a76102050edec255b3983403f1a63e7c8a41e7a", + "sha256:56a46ac655704b91e5b7e6326ce43d5ef72411376588afa1dd90e881b83c7e8c" + ], + "version": "==3.1.1" + }, + "markupsafe": { + "hashes": [ + "sha256:00bc623926325b26bb9605ae9eae8a215691f33cae5df11ca5424f06f2d1f473", + "sha256:09027a7803a62ca78792ad89403b1b7a73a01c8cb65909cd876f7fcebd79b161", + "sha256:09c4b7f37d6c648cb13f9230d847adf22f8171b1ccc4d5682398e77f40309235", + "sha256:1027c282dad077d0bae18be6794e6b6b8c91d58ed8a8d89a89d59693b9131db5", + "sha256:24982cc2533820871eba85ba648cd53d8623687ff11cbb805be4ff7b4c971aff", + "sha256:29872e92839765e546828bb7754a68c418d927cd064fd4708fab9fe9c8bb116b", + "sha256:43a55c2930bbc139570ac2452adf3d70cdbb3cfe5912c71cdce1c2c6bbd9c5d1", + "sha256:46c99d2de99945ec5cb54f23c8cd5689f6d7177305ebff350a58ce5f8de1669e", + "sha256:500d4957e52ddc3351cabf489e79c91c17f6e0899158447047588650b5e69183", + "sha256:535f6fc4d397c1563d08b88e485c3496cf5784e927af890fb3c3aac7f933ec66", + "sha256:62fe6c95e3ec8a7fad637b7f3d372c15ec1caa01ab47926cfdf7a75b40e0eac1", + "sha256:6dd73240d2af64df90aa7c4e7481e23825ea70af4b4922f8ede5b9e35f78a3b1", + "sha256:717ba8fe3ae9cc0006d7c451f0bb265ee07739daf76355d06366154ee68d221e", + "sha256:79855e1c5b8da654cf486b830bd42c06e8780cea587384cf6545b7d9ac013a0b", + "sha256:7c1699dfe0cf8ff607dbdcc1e9b9af1755371f92a68f706051cc8c37d447c905", + "sha256:88e5fcfb52ee7b911e8bb6d6aa2fd21fbecc674eadd44118a9cc3863f938e735", + "sha256:8defac2f2ccd6805ebf65f5eeb132adcf2ab57aa11fdf4c0dd5169a004710e7d", + "sha256:98c7086708b163d425c67c7a91bad6e466bb99d797aa64f965e9d25c12111a5e", + "sha256:9add70b36c5666a2ed02b43b335fe19002ee5235efd4b8a89bfcf9005bebac0d", + "sha256:9bf40443012702a1d2070043cb6291650a0841ece432556f784f004937f0f32c", + "sha256:ade5e387d2ad0d7ebf59146cc00c8044acbd863725f887353a10df825fc8ae21", + "sha256:b00c1de48212e4cc9603895652c5c410df699856a2853135b3967591e4beebc2", + "sha256:b1282f8c00509d99fef04d8ba936b156d419be841854fe901d8ae224c59f0be5", + "sha256:b2051432115498d3562c084a49bba65d97cf251f5a331c64a12ee7e04dacc51b", + "sha256:ba59edeaa2fc6114428f1637ffff42da1e311e29382d81b339c1817d37ec93c6", + "sha256:c8716a48d94b06bb3b2524c2b77e055fb313aeb4ea620c8dd03a105574ba704f", + "sha256:cd5df75523866410809ca100dc9681e301e3c27567cf498077e8551b6d20e42f", + "sha256:e249096428b3ae81b08327a63a485ad0878de3fb939049038579ac0ef61e17e7" + ], + "version": "==1.1.1" + }, + "matplotlib": { + "hashes": [ + "sha256:0ba8e3ec1b0feddc6b068fe70dc38dcf2917e301ad8d2b3f848c14ad463a4157", + "sha256:10a48e33e64dbd95f0776ba162f379c5cc55301c2d155506e79ce0c26b52f2ce", + "sha256:1376535fe731adbba55ab9e48896de226b7e89dbb55390c5fbd8f7161b7ae3be", + "sha256:16f0f8ba22df1e2c9f06c87088de45742322fde282a93b5c744c0f969cf7932e", + "sha256:1c6c999f2212858021329537f8e0f98f3f29086ec3683511dd1ecec84409f51d", + "sha256:2316dc177fc7b3d8848b49365498de0c385b4c9bba511edddd24c34fbe3d37a4", + "sha256:3398bfb533482bf21974cecf28224dd23784ad4e4848be582903f7a2436ec12e", + "sha256:3477cb1e1061b34210acc43d20050be8444478ff50b8adfac5fe2b45fc97df01", + "sha256:3cc06333b8264428d02231804e2e726b902e9161dc16f573183dee6cb7ef621f", + "sha256:4259ea7cb2c238355ee13275eddd261d869cefbdeb18a65f35459589d6d17def", + "sha256:4addcf93234b6122f530f90f485fd3d00d158911fbc1ed24db3fa66cd49fe565", + "sha256:50c0e24bcbce9c54346f4a2f4e97b0ed111f0413ac3fe9954061ae1c8aa7021f", + "sha256:62ed7597d9e54db6e133420d779c642503c25eba390e1178d85dfb2ba0d05948", + "sha256:69f6d51e41a17f6a5f70c56bb10b8ded9f299609204495a7fa2782a3a755ffc5", + "sha256:6d232e49b74e3d2db22c63c25a9a0166d965e87e2b057f795487f1f244b61d9d", + "sha256:7355bf757ecacd5f0ac9dd9523c8e1a1103faadf8d33c22664178e17533f8ce5", + "sha256:886b1045c5105631f10c1cbc999f910e44d33af3e9c7efd68c2123efc06ab636", + "sha256:9e1f353edd7fc7e5e9101abd5bc0201946f77a1b59e0da49095086c03db856ed", + "sha256:b3a343dfcbe296dbe0f26c731beee72a792ff948407e6979524298ae7bc3234e", + "sha256:d93675af09ca497a25f4f8d62f3313cf0f21e45427a87487049fe84898b99909", + "sha256:e2409ef9d37804dfb566f39c962e6ed70f281ff516b8131b3e6b4e6442711ff1", + "sha256:f8b653b0f89938ba72e92ab080c2f3aa24c1b72e2f61add22880cd1b9a6e3cdd" + ], + "index": "pypi", + "version": "==2.2.3" + }, + "mccabe": { + "hashes": [ + "sha256:ab8a6258860da4b6677da4bd2fe5dc2c659cff31b3ee4f7f5d64e79735b80d42", + "sha256:dd8d182285a0fe56bace7f45b5e7d1a6ebcbf524e8f3bd87eb0f125271b8831f" + ], + "version": "==0.6.1" + }, + "meld3": { + "hashes": [ + "sha256:b28a9bfac342aadb4557aa144bea9f8e6208bfb0596190570d10a892d35ff7dc", + "sha256:f7b754a0fde7a4429b2ebe49409db240b5699385a572501bb0d5627d299f9558" + ], + "version": "==1.0.2" + }, + "mistune": { + "hashes": [ + "sha256:59a3429db53c50b5c6bcc8a07f8848cb00d7dc8bdb431a4ab41920d201d4756e", + "sha256:88a1051873018da288eee8538d476dffe1262495144b33ecb586c4ab266bb8d4" + ], + "version": "==0.8.4" + }, + "mock": { + "hashes": [ + "sha256:83657d894c90d5681d62155c82bda9c1187827525880eda8ff5df4ec813437c3", + "sha256:d157e52d4e5b938c550f39eb2fd15610db062441a9c2747d3dbfa9298211d0f8" + ], + "version": "==3.0.5" + }, + "monotonic": { + "hashes": [ + "sha256:23953d55076df038541e648a53676fb24980f7a1be290cdda21300b3bc21dfb0", + "sha256:552a91f381532e33cbd07c6a2655a21908088962bb8fa7239ecbcc6ad1140cc7" + ], + "markers": "python_version == '2.7'", + "version": "==1.5" + }, + "mpld3": { + "hashes": [ + "sha256:4d455884a211bf99b37ecc760759435c7bb6a5955de47d8daf4967e301878ab7" + ], + "index": "pypi", + "version": "==0.3" + }, + "msgpack-python": { + "hashes": [ + "sha256:378cc8a6d3545b532dfd149da715abae4fda2a3adb6d74e525d0d5e51f46909b" + ], + "index": "pypi", + "version": "==0.5.6" + }, + "msrest": { + "hashes": [ + "sha256:05538c68251eb0c81bd2010524d8ff36d4266ec0669338fbdcecfd23c733231c", + "sha256:8143093308975f815f968b0d2a1ac8e26ba217eb6d03f3f27aac616aa3a25bd0" + ], + "version": "==0.6.7" + }, + "msrestazure": { + "hashes": [ + "sha256:070220fa9c86b55026360435b655d1d67ff4306fd1412687c400dc549e9647b7", + "sha256:e9d525b11d88f1073744e128ae19a4e023e4085893cfcfd02483fdd4cee25091" + ], + "version": "==0.6.1" + }, + "nbconvert": { + "hashes": [ + "sha256:138381baa41d83584459b5cfecfc38c800ccf1f37d9ddd0bd440783346a4c39c", + "sha256:4a978548d8383f6b2cfca4a3b0543afb77bc7cb5a96e8b424337ab58c12da9bc" + ], + "version": "==5.5.0" + }, + "nbformat": { + "hashes": [ + "sha256:b9a0dbdbd45bb034f4f8893cafd6f652ea08c8c1674ba83f2dc55d3955743b0b", + "sha256:f7494ef0df60766b7cabe0a3651556345a963b74dbc16bc7c18479041170d402" + ], + "version": "==4.4.0" + }, + "nbstripout": { + "hashes": [ + "sha256:814efbe00988445b2c3f3d1944c9f296a556e2b14a060f7b25372881c2e497d4", + "sha256:8f085e26e60e9d9c0710748510d1c763c8f63905cb16df7658b35a2936e8ca2b" + ], + "index": "pypi", + "version": "==0.3.5" + }, + "networkx": { + "hashes": [ + "sha256:45e56f7ab6fe81652fb4bc9f44faddb0e9025f469f602df14e3b2551c2ea5c8b" + ], + "version": "==2.2" + }, + "nose": { + "hashes": [ + "sha256:9ff7c6cc443f8c51994b34a667bbcf45afd6d945be7477b52e97516fd17c53ac", + "sha256:dadcddc0aefbf99eea214e0f1232b94f2fa9bd98fa8353711dacb112bfcbbb2a", + "sha256:f1bffef9cbc82628f6e7d7b40d7e255aefaa1adb6a1b1d26c69a8b79e6208a98" + ], + "index": "pypi", + "version": "==1.3.7" + }, + "nose-parameterized": { + "hashes": [ + "sha256:8f519b9739ac67e3d95f69c15cc80416eea4d63559530d01a37b9565eb629277", + "sha256:d35e677aba2f15135b6b7ea7feb88f792b899492ba5365ec0e269015df5214ce" + ], + "index": "pypi", + "version": "==0.6.0" + }, + "notebook": { + "hashes": [ + "sha256:573e0ae650c5d76b18b6e564ba6d21bf321d00847de1d215b418acb64f056eb8", + "sha256:f64fa6624d2323fbef6210a621817d6505a45d0d4a9367f1843b20a38a4666ee" + ], + "version": "==5.7.8" + }, + "numpy": { + "hashes": [ + "sha256:0778076e764e146d3078b17c24c4d89e0ecd4ac5401beff8e1c87879043a0633", + "sha256:141c7102f20abe6cf0d54c4ced8d565b86df4d3077ba2343b61a6db996cefec7", + "sha256:14270a1ee8917d11e7753fb54fc7ffd1934f4d529235beec0b275e2ccf00333b", + "sha256:27e11c7a8ec9d5838bc59f809bfa86efc8a4fd02e58960fa9c49d998e14332d5", + "sha256:2a04dda79606f3d2f760384c38ccd3d5b9bb79d4c8126b67aff5eb09a253763e", + "sha256:3c26010c1b51e1224a3ca6b8df807de6e95128b0908c7e34f190e7775455b0ca", + "sha256:52c40f1a4262c896420c6ea1c6fda62cf67070e3947e3307f5562bd783a90336", + "sha256:6e4f8d9e8aa79321657079b9ac03f3cf3fd067bf31c1cca4f56d49543f4356a5", + "sha256:7242be12a58fec245ee9734e625964b97cf7e3f2f7d016603f9e56660ce479c7", + "sha256:7dc253b542bfd4b4eb88d9dbae4ca079e7bf2e2afd819ee18891a43db66c60c7", + "sha256:94f5bd885f67bbb25c82d80184abbf7ce4f6c3c3a41fbaa4182f034bba803e69", + "sha256:a89e188daa119ffa0d03ce5123dee3f8ffd5115c896c2a9d4f0dbb3d8b95bfa3", + "sha256:ad3399da9b0ca36e2f24de72f67ab2854a62e623274607e37e0ce5f5d5fa9166", + "sha256:b0348be89275fd1d4c44ffa39530c41a21062f52299b1e3ee7d1c61f060044b8", + "sha256:b5554368e4ede1856121b0dfa35ce71768102e4aa55e526cb8de7f374ff78722", + "sha256:cbddc56b2502d3f87fda4f98d948eb5b11f36ff3902e17cb6cc44727f2200525", + "sha256:d79f18f41751725c56eceab2a886f021d70fd70a6188fd386e29a045945ffc10", + "sha256:dc2ca26a19ab32dc475dbad9dfe723d3a64c835f4c23f625c2b6566ca32b9f29", + "sha256:dd9bcd4f294eb0633bb33d1a74febdd2b9018b8b8ed325f861fffcd2c7660bb8", + "sha256:e8baab1bc7c9152715844f1faca6744f2416929de10d7639ed49555a85549f52", + "sha256:ec31fe12668af687b99acf1567399632a7c47b0e17cfb9ae47c098644ef36797", + "sha256:f12b4f7e2d8f9da3141564e6737d79016fe5336cc92de6814eba579744f65b0a", + "sha256:f58ac38d5ca045a377b3b377c84df8175ab992c970a53332fa8ac2373df44ff7" + ], + "index": "pypi", + "version": "==1.16.4" + }, + "oauthlib": { + "hashes": [ + "sha256:0ce32c5d989a1827e3f1148f98b9085ed2370fc939bf524c9c851d8714797298", + "sha256:3e1e14f6cde7e5475128d30e97edc3bfb4dc857cb884d8714ec161fdbb3b358e" + ], + "version": "==3.0.1" + }, + "opencv-python": { + "hashes": [ + "sha256:1703a296a96d3d46615e5053f224867977accb4240bcaa0fcabcb0768bf5ac13", + "sha256:1777ce7535ee7a1995cae168a107a1320e9df13648b930e72a1a2c2eccd64cda", + "sha256:1e5520482fb18fbd64d079e7f17ac0018f195fd75f6360a53bb82d7903106b50", + "sha256:25522dcf2529614750a71112a6659759080b4bdc2323f19d47f4d895960fd796", + "sha256:2af5f2842ad44c65ae2647377e0ff198719e1a1cfc9c6a19bc0c525c035d4bd8", + "sha256:31ec48d7eca13fc25c287dea7cecab453976e372cad8f50d55c054a247efda21", + "sha256:47cf48ff5dbd554e9f58cc9e98cf0b5de3f6a971172612bffa06bc5fb79ce872", + "sha256:494f98366bb5d6c2ac7e50e6617139f353704fd97a6d12ec9d392e72817d5cb0", + "sha256:4a9845870739e640e3350a8d98d511c92c087fe3d66090e83be7bf94e0ac64f7", + "sha256:4ac29cc0847d948a6636899014e84e165c30cc8779d6218394d44363462a01ce", + "sha256:5857ace03b7854221abf8072462d306c2c2ce4e366190b21d90ee8ee8aaf5bb4", + "sha256:5b4a23d99d5a2874767034466f5a8fd37b9f93ac14955a01b1a208983c76b9ad", + "sha256:734d87a5021c037064beb62133e135e66c7128e401a63b8b842b809ae2093749", + "sha256:78005c1c5d15ef4e32e0f485557bd15b5b6d87f49c19db7fe3e9246a61ebe7e4", + "sha256:81ae2283225c5c52fc3d72debd4241c30ccff2bb922578bf7867f9851cce3acb", + "sha256:88dbf900f297fdae0f62b899d6a784d8868ec2135854c5f8a9abbad00a6f0c5b", + "sha256:8c98ea7b8d327a31cd6028782a06147d0e0329ae8e829e881fb5d02f7ed8aec9", + "sha256:937d4686fef6967921145290f5b50c01c00c5b5d3542a6519e8a85cd88448723", + "sha256:a057958c0e362b3c4f03b9af1cbdb6d5af035fd22ecd7fd794eba8fdeb049eb8", + "sha256:c41eab31fa2c641226c6187caa391a688d064c99f078d604574f1912296b771f", + "sha256:cf4f7e62d1f80d1fa85a1693a3500def5cde54b2b75212b3609e552e4c25acfb", + "sha256:d90d60143e18334330c149f293071c9f2f3c79c896f33dc4ec65099e58baaaa7", + "sha256:db3106b7ca86999a7bd1f2fcc93e49314e5e6e451356774e421a69428df5020b", + "sha256:dbaf264db56f4771dfac6624f438bc4dc670aa94f61a6138848fcab7e9e77380", + "sha256:e65206c4cf651dc9cf0829962fae8bec986767c9f123d6a1ad17f9356bf7257e", + "sha256:eac94ddc78c58e891cff7180274317dad2938a4ddfc6ced1c04846c7f50e77e9", + "sha256:f2e828711f044a965509c862b3a59b3181e9c56c145a950cb53d43fec54e66d2" + ], + "version": "==4.1.0.25" + }, + "osmium": { + "hashes": [ + "sha256:008f89720d833a28ff875893bc90ca6314ed27f23dedbff6b8e7e0224c058076", + "sha256:0811d5453e9828f14dc14f7380570a71b2ac2e9fbfc849fb1485a198e1bc0825", + "sha256:08a427a7c3fe3dceb84e19bcef6edada0dde9a675f75189d89dd7f4b0cab3539", + "sha256:0a1e4200e678e18db9b291a6498385b4c8f66dc3898be8fc6d0c232fe7600360", + "sha256:2183610dfbd7831b819e5990ec47a9c25dec76084dbae1d55bdc092bfba9177c", + "sha256:227ab38197d45fced6e18a5000e27b7bc7ef2970f7adcb856370661340a03b8e", + "sha256:2928713aaadaeab38fa8d546d274c9545b20440f2019425b3a6bab9444bd935a", + "sha256:2a3a42252afcf7fd3558c582e6a38df63df038a027b6d5fe1eaf8dac66969d37", + "sha256:4617fc74d13e2373b239597c6a875b90f95f40ec0d0977f68ca4beb3383a6f63", + "sha256:4ea02b36332585b66fb52b49468fac7426a257d0ffeaf0e0aa7ef7205f0fc442", + "sha256:56f269587578fcdd406af43dc276f3a59c4763821f9e41ce7b777f6f97cdede4", + "sha256:62688a1a662bc2ef7f0b05908c9e68ba11926fc79f3d1df13cd62cee74a6ca66", + "sha256:72d1d43834610c3d802316b526c204ecf428d5bbd5dab189b0e469bc67858db1", + "sha256:8a316b6bba0f33250c232c8a10f550d8578b639857e286159e1e0767d5ac7107", + "sha256:8b4802472d974b4f05ee960c40ccd0c14881b73cd68a669f23ce9b35fe313157", + "sha256:8c6b5c489d78d398786547480f87a7d51ad51cf0044479f13ecb0c74fb5616c7", + "sha256:91baacc2b7ad28574ec8c204ba812c5bdd9b0fae79f8b6787bea450441cba52f", + "sha256:b0b2f925c45fdd1af4a79d3051359c3bc70e7e83939c6096ab91f80b3e2e8cf8", + "sha256:b96ab16db2537edf7fd36f5b819f4575b7be0dce6ac857a813822b85c790c8c3", + "sha256:ce9f170aa8cf03a497e3a42fff785e4ddd6937a0a074e480d03b2ae90b60f80d", + "sha256:d5ebe6bf0e2afc943125ab01980cd0762b3cae8bb47c50aa14ee1a934caf0c85" + ], + "index": "pypi", + "version": "==2.15.0" + }, + "pandocfilters": { + "hashes": [ + "sha256:b3dd70e169bb5449e6bc6ff96aea89c5eea8c5f6ab5e207fc2f521a2cf4a0da9" + ], + "version": "==1.4.2" + }, + "pathlib2": { + "hashes": [ + "sha256:25199318e8cc3c25dcb45cbe084cc061051336d5a9ea2a12448d3d8cb748f742", + "sha256:5887121d7f7df3603bca2f710e7219f3eca0eb69e0b7cc6e0a022e155ac931a7" + ], + "markers": "python_version in '2.6 2.7 3.2 3.3'", + "version": "==2.3.3" + }, + "pbr": { + "hashes": [ + "sha256:8257baf496c8522437e8a6cfe0f15e00aedc6c0e0e7c9d55eeeeab31e0853843", + "sha256:8c361cc353d988e4f5b998555c88098b9d5964c2e11acf7b0d21925a66bb5824" + ], + "index": "pypi", + "version": "==5.1.3" + }, + "percache": { + "hashes": [ + "sha256:b60043937aece6d154ccd1fd7380fc01ea482335716c2bd41efb85b097bc88df" + ], + "index": "pypi", + "version": "==0.3.0" + }, + "pexpect": { + "hashes": [ + "sha256:2094eefdfcf37a1fdbfb9aa090862c1a4878e5c7e0e7e7088bdb511c558e5cd1", + "sha256:9e2c1fd0e6ee3a49b28f95d4b33bc389c89b20af6a1255906e90ff1262ce62eb" + ], + "markers": "sys_platform != 'win32'", + "version": "==4.7.0" + }, + "pickleshare": { + "hashes": [ + "sha256:87683d47965c1da65cdacaf31c8441d12b8044cdec9aca500cd78fc2c683afca", + "sha256:9649af414d74d4df115d5d718f82acb59c9d418196b7b4290ed47a12ce62df56" + ], + "version": "==0.7.5" + }, + "pillow": { + "hashes": [ + "sha256:15c056bfa284c30a7f265a41ac4cbbc93bdbfc0dfe0613b9cb8a8581b51a9e55", + "sha256:1a4e06ba4f74494ea0c58c24de2bb752818e9d504474ec95b0aa94f6b0a7e479", + "sha256:1c3c707c76be43c9e99cb7e3d5f1bee1c8e5be8b8a2a5eeee665efbf8ddde91a", + "sha256:1fd0b290203e3b0882d9605d807b03c0f47e3440f97824586c173eca0aadd99d", + "sha256:24114e4a6e1870c5a24b1da8f60d0ba77a0b4027907860188ea82bd3508c80eb", + "sha256:258d886a49b6b058cd7abb0ab4b2b85ce78669a857398e83e8b8e28b317b5abb", + "sha256:33c79b6dd6bc7f65079ab9ca5bebffb5f5d1141c689c9c6a7855776d1b09b7e8", + "sha256:367385fc797b2c31564c427430c7a8630db1a00bd040555dfc1d5c52e39fcd72", + "sha256:3c1884ff078fb8bf5f63d7d86921838b82ed4a7d0c027add773c2f38b3168754", + "sha256:44e5240e8f4f8861d748f2a58b3f04daadab5e22bfec896bf5434745f788f33f", + "sha256:46aa988e15f3ea72dddd81afe3839437b755fffddb5e173886f11460be909dce", + "sha256:74d90d499c9c736d52dd6d9b7221af5665b9c04f1767e35f5dd8694324bd4601", + "sha256:809c0a2ce9032cbcd7b5313f71af4bdc5c8c771cb86eb7559afd954cab82ebb5", + "sha256:85d1ef2cdafd5507c4221d201aaf62fc9276f8b0f71bd3933363e62a33abc734", + "sha256:8c3889c7681af77ecfa4431cd42a2885d093ecb811e81fbe5e203abc07e0995b", + "sha256:9218d81b9fca98d2c47d35d688a0cea0c42fd473159dfd5612dcb0483c63e40b", + "sha256:9aa4f3827992288edd37c9df345783a69ef58bd20cc02e64b36e44bcd157bbf1", + "sha256:9d80f44137a70b6f84c750d11019a3419f409c944526a95219bea0ac31f4dd91", + "sha256:b7ebd36128a2fe93991293f997e44be9286503c7530ace6a55b938b20be288d8", + "sha256:c4c78e2c71c257c136cdd43869fd3d5e34fc2162dc22e4a5406b0ebe86958239", + "sha256:c6a842537f887be1fe115d8abb5daa9bc8cc124e455ff995830cc785624a97af", + "sha256:cf0a2e040fdf5a6d95f4c286c6ef1df6b36c218b528c8a9158ec2452a804b9b8", + "sha256:cfd28aad6fc61f7a5d4ee556a997dc6e5555d9381d1390c00ecaf984d57e4232", + "sha256:dca5660e25932771460d4688ccbb515677caaf8595f3f3240ec16c117deff89a", + "sha256:de7aedc85918c2f887886442e50f52c1b93545606317956d65f342bd81cb4fc3", + "sha256:e6c0bbf8e277b74196e3140c35f9a1ae3eafd818f7f2d3a15819c49135d6c062" + ], + "version": "==6.0.0" + }, + "pprofile": { + "hashes": [ + "sha256:3469102f462f9fc2d889970afcf73d89c0d89a36c49a4c262c3edc302b4a22da" + ], + "index": "pypi", + "version": "==2.0.2" + }, + "progressbar2": { + "hashes": [ + "sha256:9ecb2d35edaa30ed86eb92fb0135eb19a6ef9b3657be4350cc3d0d3563e6af65", + "sha256:c086fc1f718839c0ec95caaeb7bd5a1d0268a8775960b8f9dee06f2a04c84628" + ], + "version": "==3.42.0" + }, + "prometheus-client": { + "hashes": [ + "sha256:ee0c90350595e4a9f36591f291e6f9933246ea67d7cd7d1d6139a9781b14eaae" + ], + "version": "==0.7.0" + }, + "prompt-toolkit": { + "hashes": [ + "sha256:1e71341526efa4b11bb44d323e687a5d9cef204aabe2907e3f0dc1534cda0ecc", + "sha256:955d81315bb7a049f19cd17d1a73f1a40861483260f7dffd825e98303a8bd6b6", + "sha256:c1cedd626e08b8ee830ee65897de754113ff3f3035880030c08b01674d85c5b4" + ], + "version": "==1.0.16" + }, + "protobuf": { + "hashes": [ + "sha256:03f43eac9d5b651f976e91cf46a25b75e5779d98f0f4114b0abfed83376d75f8", + "sha256:0c94b21e6de01362f91a86b372555d22a60b59708599ca9d5032ae9fdf8e3538", + "sha256:2d2a9f30f61f4063fadd7fb68a2510a6939b43c0d6ceeec5c4704f22225da28e", + "sha256:34a0b05fca061e4abb77dd180209f68d8637115ff319f51e28a6a9382d69853a", + "sha256:358710fd0db25372edcf1150fa691f48376a134a6c69ce29f38f185eea7699e6", + "sha256:41e47198b94c27ba05a08b4a95160656105745c462af574e4bcb0807164065c0", + "sha256:8c61cc8a76e9d381c665aecc5105fa0f1878cf7db8b5cd17202603bcb386d0fc", + "sha256:a6eebc4db759e58fdac02efcd3028b811effac881d8a5bad1996e4e8ee6acb47", + "sha256:a9c12f7c98093da0a46ba76ec40ace725daa1ac4038c41e4b1466afb5c45bb01", + "sha256:cb95068492ba0859b8c9e61fa8ba206a83c64e5d0916fb4543700b2e2b214115", + "sha256:cd98476ce7bb4dcd6a7b101f5eecdc073dafea19f311e36eb8fba1a349346277", + "sha256:ce64cfbea18c535176bdaa10ba740c0fc4c6d998a3f511c17bedb0ae4b3b167c", + "sha256:dcbb59eac73fd454e8f2c5fba9e3d3320fd4707ed6a9d3ea3717924a6f0903ea", + "sha256:dd67f34458ae716029e2a71ede998e9092493b62a519236ca52e3c5202096c87", + "sha256:e3c96056eb5b7284a20e256cb0bf783c8f36ad82a4ae5434a7b7cd02384144a7", + "sha256:f612d584d7a27e2f39e7b17878430a959c1bc09a74ba09db096b468558e5e126", + "sha256:f6de8a7d6122297b81566e5bd4df37fd5d62bec14f8f90ebff8ede1c9726cd0a", + "sha256:fa529d9261682b24c2aaa683667253175c9acebe0a31105394b221090da75832" + ], + "version": "==3.8.0" + }, + "psutil": { + "hashes": [ + "sha256:028a1ec3c6197eadd11e7b46e8cc2f0720dc18ac6d7aabdb8e8c0d6c9704f000", + "sha256:503e4b20fa9d3342bcf58191bbc20a4a5ef79ca7df8972e6197cc14c5513e73d", + "sha256:863a85c1c0a5103a12c05a35e59d336e1d665747e531256e061213e2e90f63f3", + "sha256:954f782608bfef9ae9f78e660e065bd8ffcfaea780f9f2c8a133bb7cb9e826d7", + "sha256:b6e08f965a305cd84c2d07409bc16fbef4417d67b70c53b299116c5b895e3f45", + "sha256:bc96d437dfbb8865fc8828cf363450001cb04056bbdcdd6fc152c436c8a74c61", + "sha256:cf49178021075d47c61c03c0229ac0c60d5e2830f8cab19e2d88e579b18cdb76", + "sha256:d5350cb66690915d60f8b233180f1e49938756fb2d501c93c44f8fb5b970cc63", + "sha256:eba238cf1989dfff7d483c029acb0ac4fcbfc15de295d682901f0e2497e6781a" + ], + "index": "pypi", + "version": "==5.6.3" + }, + "ptyprocess": { + "hashes": [ + "sha256:923f299cc5ad920c68f2bc0bc98b75b9f838b93b599941a6b63ddbc2476394c0", + "sha256:d7cc528d76e76342423ca640335bd3633420dc1366f258cb31d05e865ef5ca1f" + ], + "markers": "os_name != 'nt'", + "version": "==0.6.0" + }, + "pycocotools": { + "git": "https://github.com/cocodataset/cocoapi.git", + "ref": "aca78bcd6b4345d25405a64fdba1120dfa5da1ab", + "subdirectory": "PythonAPI" + }, + "pycparser": { + "hashes": [ + "sha256:a988718abfad80b6b157acce7bf130a30876d27603738ac39f140993246b25b3" + ], + "version": "==2.19" + }, + "pycurl": { + "hashes": [ + "sha256:0f0cdfc7a92d4f2a5c44226162434e34f7d6967d3af416a6f1448649c09a25a4", + "sha256:10510a0016c862af467c6e069e051409f15f5831552bed03f5104b395a5d7dd1", + "sha256:208dd2c89e80d32a69397ba8a5cdb3bc0dc60f961a4f2a9662e5e1624dc799d1", + "sha256:6dc6ee5e7628400083471cba8044010860fe8b22e4dee05e42150a68047d7d9d", + "sha256:794bda39ea6fe434b6e1f58ab3bea9f0e6123fb43702fecd760eed6f1547b20a", + "sha256:dae7277e7c06da00947f3cd32c095b1e65eae09f07478ada4ea9dfa57020b646", + "sha256:eccea049aef47decc380746b3ff242d95636d578c907d0eab3b00918292d6c48" + ], + "index": "pypi", + "version": "==7.43.0.2" + }, + "pygame": { + "hashes": [ + "sha256:0480fe82cd41a43e3eea497fa2c059c72ac54cb5d003d5aa2ed06a04541c384e", + "sha256:136a3b5711d9ec369a0407e4e08ffced3ba61aa41059e9280ffffa79c8614f65", + "sha256:2622b9dd95f445c887a36a57eade42c672598589f69a8052ccdb8eeeffa4dbb1", + "sha256:301c6428c0880ecd4a9e3951b80e539c33863b6ff356a443db1758de4f297957", + "sha256:398c42b605ecc514e62f68f1944a2d21e247938309f598de6cb0ad3c207324a8", + "sha256:4aaff572a273a32e70ec3593d213e59ab11c183a9916616562247930f17a5447", + "sha256:4e1065577f1b29111113be5deb2ea88553551a5e1cf33e0c08fa32768f285809", + "sha256:5f052dc2975a399aa1830c1f04c5f72856aa416bf3cd4b31375a058015a5c620", + "sha256:68ea43e51150316b9fb08e251209d4e2b4e76a340b5b6fc8cdf1a898c78f7e5b", + "sha256:698433a9fcefca0527244dc44dff9503eb26157494730b1cc80e6e4dbb246e92", + "sha256:6f714986f7987f10cb94f1be0753318e341a7ea6b12d66f37a4d5d6dd4695023", + "sha256:73cd9df328c7e72638dbcc1d18e7155225faed880a53db6bad90d1d7c0a71dfd", + "sha256:7876d1f29f66d3d7cac46479503891ee1ef409b0fbce54b0d74f3a6b33a46dba", + "sha256:854e87b8b2b76e3ed11d64985fcfdd7af919659503de99fc2b0a717b314c3cf0", + "sha256:8da13704ad45b7d5de8a8cca135a7f44c7fc6aa9f691abe7b0392468a34a8013", + "sha256:9ce22fb72298ea33dbb3a1c6c60a4a4e19d9698df6f3f5782eba4dada7b7736d", + "sha256:a37b6c59e7b8feadc51db5197052b86ceb6443f9fb2a6f7d6527620e707c558c", + "sha256:a6e8d2f99dbe1dfe72d0c019693c14d93c410f702d0b04ec9a81b36dacd55a23", + "sha256:a9ac862dd7159861f2c6443b0029089e1c0c4ec762a8074022914ec52fe4dfac", + "sha256:ae1bc3e78ed28f20878e7ca2c98663a6634e9c00d7746d39413fc18e907dc162", + "sha256:be7e70f91bd4eb35ae081062f16bf434619b3292358d9b061f8159ddc570c7f0", + "sha256:c895cf9c1b6d1cbba8cb8cc3f5427febcf8aa41a9333697741abeea1c537a350", + "sha256:f1f5714d2c23f6a64ef2ac4fcd36a2dd2689da85978d951a99a6ae5dfdf9bdbc", + "sha256:fa788f775680fc5d268ab00a2da29c9a22830032cfab732730298a2952cd87f3" + ], + "index": "pypi", + "version": "==1.9.6" + }, + "pygments": { + "hashes": [ + "sha256:71e430bc85c88a430f000ac1d9b331d2407f681d6f6aec95e8bcfbc3df5b0127", + "sha256:881c4c157e45f30af185c1ffe8d549d48ac9127433f2c380c24b84572ad66297" + ], + "index": "pypi", + "version": "==2.4.2" + }, + "pyjwt": { + "hashes": [ + "sha256:5c6eca3c2940464d106b99ba83b00c6add741c9becaec087fb7ccdefea71350e", + "sha256:8d59a976fb773f3e6a39c85636357c4f0e242707394cadadd9814f5cbaa20e96" + ], + "index": "pypi", + "version": "==1.7.1" + }, + "pylint": { + "hashes": [ + "sha256:02c2b6d268695a8b64ad61847f92e611e6afcff33fd26c3a2125370c4662905d", + "sha256:ee1e85575587c5b58ddafa25e1c1b01691ef172e139fc25585e5d3f02451da93" + ], + "index": "pypi", + "version": "==1.9.4" + }, + "pymongo": { + "hashes": [ + "sha256:32421df60d06f479d71b6b539642e410ece3006e8910688e68df962c8eb40a21", + "sha256:324b22a8443e11faca44c96b20e7ec8a9e59a1e664457edeeb4f796080b31cde", + "sha256:4505ff8b7923dd7a8bed1bf25c9c4d0df5ab0b8b2821f2296533f2149a55f401", + "sha256:460b224681ea711e48e3638d15be2249024031b7dcb9622ba19c2e85bd5a26cc", + "sha256:47473b70c5f3cd5ddd2c49ab3b9ceafdafbbed5bc963f147df22a9343d7978f5", + "sha256:49375839af76834e9c5c3cc78c78386873fd0b2ad9a0860a7dc4ec9fe73af9dd", + "sha256:4a65f0f71ece86c860d30a1436b646db8ea32aec518845ef2903ca569faec32e", + "sha256:530621906c5dd6d27305b39c4e017701e5f4299aa68b93cde70eb985f94ca26f", + "sha256:54f4770b5810e8dc3cbeed675874195f02bb2bc4e95a9d665068edfb3baff4f7", + "sha256:5ed9382410e938b0ff76041c34018210504729a83bcf4f6a70c7092c28169f6f", + "sha256:61cad83637ae12c1c825130d7f9325cd6c162e3a64e8747a8144866020be3ff4", + "sha256:61e8e1c58b4fdf47ab79b7c7db8bb022c1e40b3b5fcbbaeea5fc94dc5c75638d", + "sha256:6e04e496af7d156b66cce70460011c621ecbadf5dcdce325c7acbb3cd6ea245d", + "sha256:7ef89ec435e89da902451dde6845066fe2770befaf0301fe2a1ac426b51fced3", + "sha256:854e8425e5eb775ccfffad04ecd094c99923d60a2c2d49babb5c435e836a91fa", + "sha256:9569796d48498e4db4e1d56284b626a8ed15f641ce3a8b2085f06bb03f4c2c88", + "sha256:9d50c99c6388863cbfdc5db9bad62e3a7c2e5fc151554a07c7f3c2530334a34f", + "sha256:9ea016c2c011df21f77c1f806ce45129a344ba2d414bd50f9e065b13a4a134be", + "sha256:a8421f0823174888fb12a5fa675322e756499d71e77ff712b4412d4b8f3c6503", + "sha256:aef7d88384ada699976350a285c7a333f96ebc959e98e7d2c98589f47bbf3b7f", + "sha256:b4d7ff9957ee770cf03bd7156a68a2f2e838e60712d9608eadc8741c15d01e72", + "sha256:c1db85c39e6a60588f855dbc7bd68fb0dab796096148ab5aa4abecaff19e1c6e", + "sha256:cee2fc0b94e66e7230da12fc4b3d34793c49957e16ee04f6468a94e264a1e41d", + "sha256:cf1dea28379a16b23e47db312883f07b3ba8d9d6abc1c59e51d4c8ae1820ab43", + "sha256:d1cd175df7c8b5fc976bade78bf4d9fb5aa7ab465c0f59931e380bbe188ef8fc", + "sha256:d48a94edf3cdd34524936a72ea01b352682b337f33a42db10ba29a96c37147d3", + "sha256:d9cc103a4e97f78bc77a1d72759ab3722f6cdf0374ad4fb4b0c53bd3238bdf98", + "sha256:fcb9ae8aa9158106c5d98a4349ec0d90b68f052d620b2d24622ba03b91e4d81d" + ], + "index": "pypi", + "version": "==3.8.0" + }, + "pymysql": { + "hashes": [ + "sha256:95f057328357e0e13a30e67857a8c694878b0175797a9a203ee7adbfb9b1ec5f", + "sha256:9ec760cbb251c158c19d6c88c17ca00a8632bac713890e465b2be01fdc30713f" + ], + "index": "pypi", + "version": "==0.9.2" + }, + "pynacl": { + "hashes": [ + "sha256:05c26f93964373fc0abe332676cb6735f0ecad27711035b9472751faa8521255", + "sha256:0c6100edd16fefd1557da078c7a31e7b7d7a52ce39fdca2bec29d4f7b6e7600c", + "sha256:0d0a8171a68edf51add1e73d2159c4bc19fc0718e79dec51166e940856c2f28e", + "sha256:1c780712b206317a746ace34c209b8c29dbfd841dfbc02aa27f2084dd3db77ae", + "sha256:2424c8b9f41aa65bbdbd7a64e73a7450ebb4aa9ddedc6a081e7afcc4c97f7621", + "sha256:2d23c04e8d709444220557ae48ed01f3f1086439f12dbf11976e849a4926db56", + "sha256:30f36a9c70450c7878053fa1344aca0145fd47d845270b43a7ee9192a051bf39", + "sha256:37aa336a317209f1bb099ad177fef0da45be36a2aa664507c5d72015f956c310", + "sha256:4943decfc5b905748f0756fdd99d4f9498d7064815c4cf3643820c9028b711d1", + "sha256:57ef38a65056e7800859e5ba9e6091053cd06e1038983016effaffe0efcd594a", + "sha256:5bd61e9b44c543016ce1f6aef48606280e45f892a928ca7068fba30021e9b786", + "sha256:6482d3017a0c0327a49dddc8bd1074cc730d45db2ccb09c3bac1f8f32d1eb61b", + "sha256:7d3ce02c0784b7cbcc771a2da6ea51f87e8716004512493a2b69016326301c3b", + "sha256:a14e499c0f5955dcc3991f785f3f8e2130ed504fa3a7f44009ff458ad6bdd17f", + "sha256:a39f54ccbcd2757d1d63b0ec00a00980c0b382c62865b61a505163943624ab20", + "sha256:aabb0c5232910a20eec8563503c153a8e78bbf5459490c49ab31f6adf3f3a415", + "sha256:bd4ecb473a96ad0f90c20acba4f0bf0df91a4e03a1f4dd6a4bdc9ca75aa3a715", + "sha256:e2da3c13307eac601f3de04887624939aca8ee3c9488a0bb0eca4fb9401fc6b1", + "sha256:f67814c38162f4deb31f68d590771a29d5ae3b1bd64b75cf232308e5c74777e0" + ], + "index": "pypi", + "version": "==1.3.0" + }, + "pynmea2": { + "hashes": [ + "sha256:8b83fa7e3e668af5e182ef1c2fd4a535433ecadf60d7b627280172d695a1646b", + "sha256:fe786594299588d1bfbd346ece2c2c1e5b24e160dcb740813c34bfa70d0a141d" + ], + "index": "pypi", + "version": "==1.15.0" + }, + "pyparsing": { + "hashes": [ + "sha256:1873c03321fc118f4e9746baf201ff990ceb915f433f23b395f5580d1840cb2a", + "sha256:9b6323ef4ab914af344ba97510e966d64ba91055d6b9afa6b30799340e89cc03" + ], + "version": "==2.4.0" + }, + "pypolyline": { + "hashes": [ + "sha256:09cc2192bc12063c7afa2d2718b739cd4bf3f8ec29eacde0cb728c9f5f7f7858", + "sha256:21acee0e31d867bde04583907ccb7afe4b21d33a63c23adc7cf0d82b6f2feab3", + "sha256:5e0643454b4471f4f23d38530467ee7093d3b375898d5e1b054876e5a50a6b89", + "sha256:6b0a1b573fe84c9ed0aa3a4eb9903d44864f37e405cdcc7396b61e6d00a937d6", + "sha256:6bdbc9210f29d4fd44c3e4d510ffcc1276e46a50d63365831e2e422dc0b3cb43", + "sha256:8efb93097c92c5894dcaf9e784b888f9426d170ae51d62164341bbb2b832c09a", + "sha256:9c843a35b2d02b04c1226db851834b55f0de30eef47ba057fd6f8623cdef6f2d", + "sha256:ad01fedf427536f391776b329c95e5f80f2b1a5d25c54ea7713c8cdb56947106", + "sha256:e4e4c857790f6a3067dab3ae661edda99d5cee55d107b3b4d0186159431165ef", + "sha256:f8c84f0d2aa6bd9ed14bdb671fab80f79b4ba93b4347b530ae4d3b56a3fb269a" + ], + "index": "pypi", + "version": "==0.1.17" + }, + "pyrsistent": { + "hashes": [ + "sha256:16692ee739d42cf5e39cef8d27649a8c1fdb7aa99887098f1460057c5eb75c3a" + ], + "version": "==0.15.2" + }, + "pysdl2": { + "hashes": [ + "sha256:b52acab5493a77b08c2afee1f385769fc2005f17cfeaf1886eff22dc78da2123" + ], + "index": "pypi", + "version": "==0.9.6" + }, + "pysendfile": { + "hashes": [ + "sha256:510a414b270986fba3c79cb76d90a4c910c701bfb43ff983a5d4e92846050e17" + ], + "index": "pypi", + "version": "==2.0.1" + }, + "python-dateutil": { + "hashes": [ + "sha256:7e6584c74aeed623791615e26efd690f29817a27c73085b78e4bad02493df2fb", + "sha256:c89805f6f4d64db21ed966fda138f8a5ed7a4fdbc1a8ee329ce1b74e3c74da9e" + ], + "index": "pypi", + "version": "==2.8.0" + }, + "python-engineio": { + "hashes": [ + "sha256:9e4e7109d05d80ce5414f13b16f66725c2b5d574099fd43d37b024e7ea1c4354", + "sha256:d3315d3f972bd9bd32e0738d45801a912f522177ff75094762f31a8c341d1f41" + ], + "version": "==3.8.1" + }, + "python-logstash": { + "hashes": [ + "sha256:10943e5df83f592b4d61b63ad1afff855ccc8c9467f78718f0a59809ba1fe68c" + ], + "index": "pypi", + "version": "==0.4.6" + }, + "python-socketio": { + "hashes": [ + "sha256:89a48591a8850c1f30d735f8e5a0294846da245a9b8940c39e1106e460c7a14e", + "sha256:c7ffeac3d81f2d8d63b3ec7ed1e2d4478cc84aa1da666c1934c19432f4b8c0f8" + ], + "version": "==4.1.0" + }, + "python-utils": { + "hashes": [ + "sha256:34aaf26b39b0b86628008f2ae0ac001b30e7986a8d303b61e1357dfcdad4f6d3", + "sha256:e25f840564554eaded56eaa395bca507b0b9e9f0ae5ecb13a8cb785305c56d25" + ], + "version": "==2.3.0" + }, + "pytz": { + "hashes": [ + "sha256:303879e36b721603cc54604edcac9d20401bdbe31e1e4fdee5b9f98d5d31dfda", + "sha256:d747dd3d23d77ef44c6a3526e274af6efeb0a6f1afd5a69ba4d5be4098c8e141" + ], + "version": "==2019.1" + }, + "pyvcd": { + "hashes": [ + "sha256:791fd7608fb8113c9658f699cb6292d66d7fb90bcab9ebc00b05adc40da7a5ce", + "sha256:bdcb848b79cea2196ebf317178eff2c9c7d6354b85f9eb4991e9175f98e26937" + ], + "index": "pypi", + "version": "==0.1.4" + }, + "pywavelets": { + "hashes": [ + "sha256:18b193b67937e805a8e79c036bd2aa4ea3a357737256efeefdabd19c95083c3b", + "sha256:1d7ba03baa81938b17d4819db36f018e680d929af329062af4d4b6d6236d02ba", + "sha256:21f39d86cc35e003576fc1400b15534e2999570418fcdb17ea62d1ff8773b076", + "sha256:250412f482d5cb358b7ec323b2a783d91e5cfc337fdf8fde3c59bf2c35d6366f", + "sha256:25c0c592bf43eaffb4d3c6b6444b14c7407db750b6f2d344d809d4af934319d9", + "sha256:2f2cdd96e4882b0c18e75cc90c4710de429ac226ce53b58a90c7420e3e307631", + "sha256:3abed8dcd3e94ead72ee8010b494df5a9bdbdd5e39129d52fbf8066efa323a51", + "sha256:3e99ab8feeb47755738fb8deb8154c9604c4a7996b1b7db6b090475105ca7c92", + "sha256:64926c4c78dd690ec0d61be20f7c27cfbde6de9fa66ab8205eb079d9db6927fc", + "sha256:687ec8877c10e3a03595ad167d1ea2662bc1ab13ef43d63a6e207a53b2ee4c26", + "sha256:6af0077c7a4c9935aa64301f6942468b494656b8812e801d4a635cf42088f96c", + "sha256:7215856a5d2e1a2dccca1f71d912ee6a7387086f3b3adcb55d7c41314c6abb0c", + "sha256:9e47b241533add77961093b1e40cfff031597d429e91ad7c675838be0f7cc0df", + "sha256:9e782f49dca57bc0fd2a40c0917949d77be2ecc999ccd44fff57fb10aa214135", + "sha256:a12c7a6258c0015d2c75d88b87393ee015494551f049009e8b63eafed2d78efc", + "sha256:a5027d47484498e70391b311a2688c4f74294de629b982ed17be57be4c77ade7", + "sha256:ab02363467ee3cb222c5b425bc53453270ddae72bce313e72fd14616692d725a", + "sha256:adc79308c65a2007bdbd5846fda70088e7ead0ef0a5a6f44d08829e9478a907f", + "sha256:afaaee392450785a346d9e5e5f6e5307b13958d8b0633818632cb38972a7752a", + "sha256:b26b836c7f71df7b2779e62d1338367cfe37b98324e9b0d54b428ac030e3d1f0", + "sha256:b9adbc27d70a2626c235a18b41315de2832c384651d03383db7a58c2a2bccc6f", + "sha256:bd6e62efb7839fd6bf894b7b9aec6d58be0c44a38ea0c9f3c5bea834d84d05eb", + "sha256:de083a3a71576a9c3d8ba73b6f0425e4690d6ac6e480562f30bec5cb20667324", + "sha256:e89551257233a3da717a9e6e2e303243df75faffe0b6781d21c15eb9d682ec6d", + "sha256:eafb7d609c41a04028144f4b6697792f448554960ef353244aaf0a5883263543", + "sha256:fb3ee9f65d25ee5c89104e533d5f341c253cdb9543ef6fcd6dfa599b12e84f1c" + ], + "version": "==1.0.3" + }, + "pyyaml": { + "hashes": [ + "sha256:57acc1d8533cbe51f6662a55434f0dbecfa2b9eaf115bede8f6fd00115a0c0d3", + "sha256:588c94b3d16b76cfed8e0be54932e5729cc185caffaa5a451e7ad2f7ed8b4043", + "sha256:68c8dd247f29f9a0d09375c9c6b8fdc64b60810ebf07ba4cdd64ceee3a58c7b7", + "sha256:70d9818f1c9cd5c48bb87804f2efc8692f1023dac7f1a1a5c61d454043c1d265", + "sha256:86a93cccd50f8c125286e637328ff4eef108400dd7089b46a7be3445eecfa391", + "sha256:a0f329125a926876f647c9fa0ef32801587a12328b4a3c741270464e3e4fa778", + "sha256:a3c252ab0fa1bb0d5a3f6449a4826732f3eb6c0270925548cac342bc9b22c225", + "sha256:b4bb4d3f5e232425e25dda21c070ce05168a786ac9eda43768ab7f3ac2770955", + "sha256:cd0618c5ba5bda5f4039b9398bb7fb6a317bb8298218c3de25c47c4740e4b95e", + "sha256:ceacb9e5f8474dcf45b940578591c7f3d960e82f926c707788a570b51ba59190", + "sha256:fe6a88094b64132c4bb3b631412e90032e8cfe9745a58370462240b8cb7553cd" + ], + "index": "pypi", + "version": "==5.1.1" + }, + "pyzmq": { + "hashes": [ + "sha256:1651e52ed91f0736afd6d94ef9f3259b5534ce8beddb054f3d5ca989c4ef7c4f", + "sha256:5ccb9b3d4cd20c000a9b75689d5add8cd3bce67fcbd0f8ae1b59345247d803af", + "sha256:5e120c4cd3872e332fb35d255ad5998ebcee32ace4387b1b337416b6b90436c7", + "sha256:5e2a3707c69a7281a9957f83718815fd74698cba31f6d69f9ed359921f662221", + "sha256:63d51add9af8d0442dc90f916baf98fdc04e3b0a32afec4bfc83f8d85e72959f", + "sha256:65c5a0bdc49e20f7d6b03a661f71e2fda7a99c51270cafe71598146d09810d0d", + "sha256:66828fabe911aa545d919028441a585edb7c9c77969a5fea6722ef6e6ece38ab", + "sha256:7d79427e82d9dad6e9b47c0b3e7ae5f9d489b1601e3a36ea629bb49501a4daf3", + "sha256:824ee5d3078c4eae737ffc500fbf32f2b14e6ec89b26b435b7834febd70120cf", + "sha256:89dc0a83cccec19ff3c62c091e43e66e0183d1e6b4658c16ee4e659518131494", + "sha256:8b319805f6f7c907b101c864c3ca6cefc9db8ce0791356f180b1b644c7347e4c", + "sha256:90facfb379ab47f94b19519c1ecc8ec8d10813b69d9c163117944948bdec5d15", + "sha256:a0a178c7420021fc0730180a914a4b4b3092ce9696ceb8e72d0f60f8ce1655dd", + "sha256:a7a89591ae315baccb8072f216614b3e59aed7385aef4393a6c741783d6ee9cf", + "sha256:ba2578f0ae582452c02ed9fac2dc477b08e80ce05d2c0885becf5fff6651ccb0", + "sha256:c69b0055c55702f5b0b6b354133e8325b9a56dbc80e1be2d240bead253fb9825", + "sha256:ca434e1858fe222380221ddeb81e86f45522773344c9da63c311d17161df5e06", + "sha256:d4b8ecfc3d92f114f04d5c40f60a65e5196198b827503341521dda12d8b14939", + "sha256:d706025c47b09a54f005953ebe206f6d07a22516776faa4f509aaff681cc5468", + "sha256:d8f27e958f8a2c0c8ffd4d8855c3ce8ac3fa1e105f0491ce31729aa2b3229740", + "sha256:dbd264298f76b9060ce537008eb989317ca787c857e23cbd1b3ddf89f190a9b1", + "sha256:e926d66f0df8fdbf03ba20583af0f215e475c667fb033d45fd031c66c63e34c9", + "sha256:efc3bd48237f973a749f7312f68062f1b4ca5c2032a0673ca3ea8e46aa77187b", + "sha256:f59bc782228777cbfe04555707a9c56d269c787ed25d6d28ed9d0fbb41cb1ad2", + "sha256:f8da5322f4ff5f667a0d5a27e871b560c6637153c81e318b35cb012b2a98835c" + ], + "index": "pypi", + "version": "==18.0.1" + }, + "qtconsole": { + "hashes": [ + "sha256:4af84facdd6f00a6b9b2927255f717bb23ae4b7a20ba1d9ef0a5a5a8dbe01ae2", + "sha256:60d61d93f7d67ba2b265c6d599d413ffec21202fec999a952f658ff3a73d252b" + ], + "version": "==4.5.1" + }, + "redis": { + "hashes": [ + "sha256:6946b5dca72e86103edc8033019cc3814c031232d339d5f4533b02ea85685175", + "sha256:8ca418d2ddca1b1a850afa1680a7d2fd1f3322739271de4b704e0d4668449273" + ], + "index": "pypi", + "version": "==3.2.1" + }, + "redlock": { + "hashes": [ + "sha256:b718646239d300745475a76e81d350ec523e7146cf84d696b3c4a7dfdd5dd4d4", + "sha256:ce7e6ab404882b64a9c5017c7a78b1a3714f2c712635bcb22cbb74d20719bbd1" + ], + "index": "pypi", + "version": "==1.2.0" + }, + "requests": { + "hashes": [ + "sha256:11e007a8a2aa0323f5a921e9e6a2d7e4e67d9877e85773fba9ba6419025cbeb4", + "sha256:9cf5292fcd0f598c671cfc1e0d7d1a7f13bb8085e9a590f48c010551dc6c4b31" + ], + "index": "pypi", + "version": "==2.22.0" + }, + "requests-oauthlib": { + "hashes": [ + "sha256:bd6533330e8748e94bf0b214775fed487d309b8b8fe823dc45641ebcd9a32f57", + "sha256:d3ed0c8f2e3bbc6b344fa63d6f933745ab394469da38db16bdddb461c7e25140" + ], + "version": "==1.2.0" + }, + "reverse-geocoder": { + "hashes": [ + "sha256:2a2e781b5f69376d922b78fe8978f1350c84fce0ddb07e02c834ecf98b57c75c" + ], + "index": "pypi", + "version": "==1.5.1" + }, + "s2sphere": { + "hashes": [ + "sha256:c2478c1ff7c601a59a7151a57b605435897514578fa6bdb8730721c182adbbaf", + "sha256:d2340c9cf458ddc9a89afd1d8048a4195ce6fa6b0095ab900d4be5271e537401" + ], + "index": "pypi", + "version": "==0.2.5" + }, + "s3transfer": { + "hashes": [ + "sha256:6efc926738a3cd576c2a79725fed9afde92378aa5c6a957e3af010cb019fac9d", + "sha256:b780f2411b824cb541dbcd2c713d0cb61c7d1bcadae204cdddda2b35cef493ba" + ], + "version": "==0.2.1" + }, + "scandir": { + "hashes": [ + "sha256:2586c94e907d99617887daed6c1d102b5ca28f1085f90446554abf1faf73123e", + "sha256:2ae41f43797ca0c11591c0c35f2f5875fa99f8797cb1a1fd440497ec0ae4b022", + "sha256:2b8e3888b11abb2217a32af0766bc06b65cc4a928d8727828ee68af5a967fa6f", + "sha256:2c712840c2e2ee8dfaf36034080108d30060d759c7b73a01a52251cc8989f11f", + "sha256:4d4631f6062e658e9007ab3149a9b914f3548cb38bfb021c64f39a025ce578ae", + "sha256:67f15b6f83e6507fdc6fca22fedf6ef8b334b399ca27c6b568cbfaa82a364173", + "sha256:7d2d7a06a252764061a020407b997dd036f7bd6a175a5ba2b345f0a357f0b3f4", + "sha256:8c5922863e44ffc00c5c693190648daa6d15e7c1207ed02d6f46a8dcc2869d32", + "sha256:92c85ac42f41ffdc35b6da57ed991575bdbe69db895507af88b9f499b701c188", + "sha256:b24086f2375c4a094a6b51e78b4cf7ca16c721dcee2eddd7aa6494b42d6d519d", + "sha256:cb925555f43060a1745d0a321cca94bcea927c50114b623d73179189a4e100ac" + ], + "markers": "python_version < '3.5'", + "version": "==1.10.0" + }, + "scikit-image": { + "hashes": [ + "sha256:056632aa964528c484758829d295f11c86a405aa0294f2578eac4acd945d4300", + "sha256:1600628c96b76f265dede2393115f77d93a427c617202622dfd6ba27e075efcc", + "sha256:1e85573ed37e0205ea918475c1fbd12e6c118c6f1e166dd159af04bcd9d4fa30", + "sha256:1fc4a596d6b7295bd05dce3df1105d1c7c7abe9c65f5d3ced2eace1cd746c15e", + "sha256:24ebe2a9cf40f2196393bc575345bc514bc845366545361785696a76e3aeb89b", + "sha256:331ee6db27e434e467831e21c8489bec23038ede790c53e0b6040e1e638fff45", + "sha256:4c17f2919029bd68907e2bf80dfecfb8b601bee4f392ef01f835ba4aa8c616e9", + "sha256:4e59c25be3e9760ba181832b9b33e27ff3cea9c362842260ac06644ae08b23c8", + "sha256:4f12cdf72155f77b736902e87c6b4544e311241070e9548c03ac0fcf9aa0bbed", + "sha256:62718e67f1f058501055c7e6b7206eea96f792039ea4c87af8e6b706a22ae11e", + "sha256:6b88c64f8351f1755ccc7feec26a7e55359acba2375498409fa1380bd3789b6f", + "sha256:755ee87e4b0332fd1645c67fd1e5780908937f35d28a6bd3377af304fd54a8d9", + "sha256:8508b9a2fccaa52a30785316ae4b29aaf339ef8fc3dab1bb35d36468397e0b0d", + "sha256:8541cefddad87b08105583e946132e822b196fff437f407afa92742e1e763387", + "sha256:8d76474ad59e5339584a9c4317868e51c0fbf2c2d11a936e836279fc281633d6", + "sha256:b26462abeee13ee249c814723a3038ccd74af2144349422d1b344e1378f9f702", + "sha256:b7b5605c7737073c1bdffbfea1f6a257dd6e96ab109fc37f43a7bd3d1d581e2a", + "sha256:c7afc4231e9bb9d0d2b44958e6e403117e6823bb16bca61ab95540e737f2941f", + "sha256:cc97cfc239f1f7ee8cc5129e3cb29fe553237fa62380b62d6f7c0909974d1400", + "sha256:ce114f536941348998665360ea6fbbf1577a3c49a5c2b4d416c71d3edde05ab7", + "sha256:db9f4fb00db5ce5855737c22abbdc22d9663d44643cbdad674e2c9fc32ba9c16", + "sha256:e312e914d6f97e525460268cd0d215cd9c9c4fe131457316bd32c6c760171660", + "sha256:e50d053133c292efe0e70eefc6a6481002b32d7b4b72ef38bd7caae6b24fb7d6", + "sha256:ef3fb33404fbf1717e3d268e1cc0983264fc3154036b29950fbc9c3fbed98ee3", + "sha256:f05eab2df885fb6fde3df0e4d24c9c620d6474ea0eb949fd45f6f634925dd514", + "sha256:fb1de3dabbc7a429b38a016d01502920226b59d277578291fb18a28888ed5792" + ], + "index": "pypi", + "version": "==0.14.3" + }, + "scipy": { + "hashes": [ + "sha256:0bcababa06ff83138a7f30a68f334dee034ce1cc7604f9278b96f62265fe7fd7", + "sha256:162b803984ebb76927990d7233cab825d146be8e2a3f6a0efb1b3a61ebacae73", + "sha256:271c6e56c8f9a3d6c3f0bc857d7a6e7cf7a8415c879a3915701cd011e82a83a3", + "sha256:2eb255b30dac7516c6f3c5237f2e0ad1f1213b5364de409d932249c9a8c5bffb", + "sha256:447c40d33ec5e0020750fadbb8599220b9eb9fd8798030efe9b308247800f364", + "sha256:4686d699f76068757a81269f1a111c0db689bf048a56b131a339803121534fa8", + "sha256:47d4623efa71948dc4a92f978fbf6b9fb69dac5b0f0fae4c1a1f3d955ac8aea9", + "sha256:49dcebc6f57bce0bd23cb55dbc6144f4990e5cbce9aab3128af03d6b1b4eab6a", + "sha256:5fa84b467b5f77c243c5701628ed7a4238e53bc4120db87be7dafa416e842fb9", + "sha256:67d2210c7f6f585e1055bee3dc9f15610b5ebb04e80bfaa757868937ee744fec", + "sha256:682b210ff7a65f6f5245fdf73d26a348b57e42d2059bc5fcf7ed25d063f35c45", + "sha256:7f58faa422aa493d7b70dd56d6e8783223e84dd6e7f4b4161bd776b39ecbac92", + "sha256:7fb4efff9895116428ad65564d2232fb1cac4b9d84398512a858b09dd4a7fd59", + "sha256:922e2370674c82dd1367fc13a08c8765f4e5281a584d871e7cb454828d84600f", + "sha256:97f26b4b5d4456f44849fd35cad8801f7cae4e64b75fc4e522d26a54aef17391", + "sha256:9a21d64d002cb3a9239a55c0aa100b48d58b5e38382c0fdfcdfc68cf417d8142", + "sha256:a4331e0b8dab1ff75d2c67b5158a8bb9a83c799d7140094dda936d876c7cfbb1", + "sha256:a9fc1fcaa560edf771d4545d7e6dd865a213fc5b485bb127de5dfd32f40094e1", + "sha256:b074a83299a82eae617dc46a830cfa7aaa588d07523990507848ee1ded3c52ce", + "sha256:bcd0d4b2de5cb3fab69007214a39737e917267f56f887ce9c7732ba3278fc33d", + "sha256:c390f1721757ec983616149f00e1bd0432aa32d2c1d9398930d7e7cc9542c922", + "sha256:c5b9db9e3f6537bf7b308de12c185b27f22fb9a66fd12efc7aefbcfa0adb4d82", + "sha256:d0d41a9ee3264f95820138170b447f5d3e453e5ebd10b411bca37c99237aac69", + "sha256:d18d1575d4a54f128c0f34422bd73ce0f177e462d6124f074388e211d8dc2616", + "sha256:e99cd49daffe7384fd35046c3b14bee98ce87d97c95865469227001905534e13", + "sha256:f4e355afa8fdda11010de308c2376edda29e064cec699974097364115f71e16f", + "sha256:f64e29a8b32d672fb6078f456bfff3cae8f36b6c8b64c337ad0942f29404b03f", + "sha256:fbdff021643c2dfa35efd29218e0318c4b4987f48ea432be7e8c02bdb1b0c314" + ], + "index": "pypi", + "version": "==1.2.2" + }, + "send2trash": { + "hashes": [ + "sha256:60001cc07d707fe247c94f74ca6ac0d3255aabcb930529690897ca2a39db28b2", + "sha256:f1691922577b6fa12821234aeb57599d887c4900b9ca537948d2dac34aea888b" + ], + "version": "==1.5.0" + }, + "shapely": { + "hashes": [ + "sha256:0378964902f89b8dbc332e5bdfa08e0bc2f7ab39fecaeb17fbb2a7699a44fe71", + "sha256:34e7c6f41fb27906ccdf2514ee44a5774b90b39a256b6511a6a57d11ffe64999", + "sha256:3ca69d4b12e2b05b549465822744b6a3a1095d8488cc27b2728a06d3c07d0eee", + "sha256:3e9388f29bd81fcd4fa5c35125e1fbd4975ee36971a87a90c093f032d0e9de24", + "sha256:3ef28e3f20a1c37f5b99ea8cf8dcb58e2f1a8762d65ed2d21fd92bf1d4811182", + "sha256:523c94403047eb6cacd7fc1863ebef06e26c04d8a4e7f8f182d49cd206fe787e", + "sha256:5d22a1a705c2f70f61ccadc696e33d922c1a92e00df8e1d58a6ade14dd7e3b4f", + "sha256:714b6680215554731389a1bbdae4cec61741aa4726921fa2b2b96a6f578a2534", + "sha256:7dfe1528650c3f0dc82f41a74cf4f72018288db9bfb75dcd08f6f04233ec7e78", + "sha256:ba58b21b9cf3c33725f7f530febff9ed6a6846f9d0bf8a120fc74683ff919f89", + "sha256:c4b87bb61fc3de59fc1f85e71a79b0c709dc68364d9584473697aad4aa13240f", + "sha256:ebb4d2bee7fac3f6c891fcdafaa17f72ab9c6480f6d00de0b2dc9a5137dfe342" + ], + "index": "pypi", + "version": "==1.6.4.post2" + }, + "simplegeneric": { + "hashes": [ + "sha256:dc972e06094b9af5b855b3df4a646395e43d1c9d0d39ed345b7393560d0b9173" + ], + "version": "==0.8.1" + }, + "simplejson": { + "hashes": [ + "sha256:067a7177ddfa32e1483ba5169ebea1bc2ea27f224853211ca669325648ca5642", + "sha256:2fc546e6af49fb45b93bbe878dea4c48edc34083729c0abd09981fe55bdf7f91", + "sha256:354fa32b02885e6dae925f1b5bbf842c333c1e11ea5453ddd67309dc31fdb40a", + "sha256:37e685986cf6f8144607f90340cff72d36acf654f3653a6c47b84c5c38d00df7", + "sha256:3af610ee72efbe644e19d5eaad575c73fb83026192114e5f6719f4901097fce2", + "sha256:3b919fc9cf508f13b929a9b274c40786036b31ad28657819b3b9ba44ba651f50", + "sha256:3dd289368bbd064974d9a5961101f080e939cbe051e6689a193c99fb6e9ac89b", + "sha256:6c3258ffff58712818a233b9737fe4be943d306c40cf63d14ddc82ba563f483a", + "sha256:75e3f0b12c28945c08f54350d91e624f8dd580ab74fd4f1bbea54bc6b0165610", + "sha256:b1f329139ba647a9548aa05fb95d046b4a677643070dc2afc05fa2e975d09ca5", + "sha256:ee9625fc8ee164902dfbb0ff932b26df112da9f871c32f0f9c1bcf20c350fe2a", + "sha256:fb2530b53c28f0d4d84990e945c2ebb470edb469d63e389bf02ff409012fe7c5" + ], + "index": "pypi", + "version": "==3.16.0" + }, + "singledispatch": { + "hashes": [ + "sha256:5b06af87df13818d14f08a028e42f566640aef80805c3b50c5056b086e3c2b9c", + "sha256:833b46966687b3de7f438c761ac475213e53b306740f1abfaa86e1d1aae56aa8" + ], + "markers": "python_version < '3.4'", + "version": "==3.4.0.3" + }, + "six": { + "hashes": [ + "sha256:3350809f0555b11f552448330d0b52d5f24c91a322ea4a15ef22629740f3761c", + "sha256:d16a0141ec1a18405cd4ce8b4613101da75da0e9a7aec5bdd4fa804d0e0eba73" + ], + "index": "pypi", + "version": "==1.12.0" + }, + "sortedcontainers": { + "hashes": [ + "sha256:974e9a32f56b17c1bac2aebd9dcf197f3eb9cd30553c5852a3187ad162e1a03a", + "sha256:d9e96492dd51fae31e60837736b38fe42a187b5404c16606ff7ee7cd582d4c60" + ], + "version": "==2.1.0" + }, + "sqlalchemy": { + "hashes": [ + "sha256:d6cda03b0187d6ed796ff70e87c9a7dce2c2c9650a7bc3c022cd331416853c31" + ], + "index": "pypi", + "version": "==1.2.7" + }, + "subprocess32": { + "hashes": [ + "sha256:88e37c1aac5388df41cc8a8456bb49ebffd321a3ad4d70358e3518176de3a56b", + "sha256:eb2937c80497978d181efa1b839ec2d9622cf9600a039a79d0e108d1f9aec79d" + ], + "index": "pypi", + "version": "==3.5.4" + }, + "supervisor": { + "hashes": [ + "sha256:a3289b9124e59aee1621d43b55cd1634468cb3212d09c5b0114a3183cc080cca", + "sha256:f768abc073e8702892718938b8a0ab98ebcb91c2afcb39bf2cb570d3eb51149e" + ], + "index": "pypi", + "version": "==4.0.3" + }, + "tenacity": { + "hashes": [ + "sha256:a0c3c5f7ae0c33f5556c775ca059c12d6fd8ab7121613a713e8b7d649908571b", + "sha256:b87c1934daa0b2ccc7db153c37b8bf91d12f165936ade8628e7b962b92dc7705" + ], + "index": "pypi", + "version": "==5.0.4" + }, + "tensorboard": { + "hashes": [ + "sha256:6f194519f41762bfdf5eb410ccf33226d1c252caf5ad8893288648bfbcf4d135", + "sha256:81170f66bf8f95c2e9f6b3fefe0ddc5472655a9e3793e73b5b5d4ec0ba395e76" + ], + "version": "==1.12.2" + }, + "tensorflow-estimator": { + "hashes": [ + "sha256:7cfdaa3e83e3532f31713713feb98be7ea9f3065722be4267e49b6c301271419" + ], + "version": "==1.13.0" + }, + "tensorflow-gpu": { + "hashes": [ + "sha256:0c2fa74a53009f72eb73da46ef8e78ffc09514349ba3de179c6b419b69a4bf09", + "sha256:17460b5f3525ddbbb1fb9f639955d3a999f9656cc7bf1be65bc78dea1a0cedea", + "sha256:2f85fdfee4eb93432bf8ef11428f2b5e17fb3e1b733599612329e165bb74a3fd", + "sha256:38be54cb1e757f95f24b2e03e71d7bcab359429267ff36c9e32de2ed17943a42", + "sha256:42c13cf5538125d93177b7901f23a1f6759b64f9f3f2d8680099b1fbfec37b83", + "sha256:b771297d3b93f93a20af1d2d7dc049bb9617e2c2ab25c36156b011bf1a49bd7c", + "sha256:ca68f7eb91e6101300ffc59a59c3b5600359a0ab6f2e1e8cde4a8a65ec21bb92" + ], + "index": "pypi", + "version": "==1.13.0rc0" + }, + "termcolor": { + "hashes": [ + "sha256:1d6d69ce66211143803fbc56652b41d73b4a400a2891d7bf7a1cdf4c02de613b" + ], + "version": "==1.1.0" + }, + "terminado": { + "hashes": [ + "sha256:d9d012de63acb8223ac969c17c3043337c2fcfd28f3aea1ee429b345d01ef460", + "sha256:de08e141f83c3a0798b050ecb097ab6259c3f0331b2f7b7750c9075ced2c20c2" + ], + "version": "==0.8.2" + }, + "testpath": { + "hashes": [ + "sha256:46c89ebb683f473ffe2aab0ed9f12581d4d078308a3cb3765d79c6b2317b0109", + "sha256:b694b3d9288dbd81685c5d2e7140b81365d46c29f5db4bc659de5aa6b98780f8" + ], + "version": "==0.4.2" + }, + "theano": { + "hashes": [ + "sha256:35c9bbef56b61ffa299265a42a4e8f8cb5a07b2997dabaef0f8830b397086913" + ], + "index": "pypi", + "version": "==1.0.4" + }, + "torchfile": { + "hashes": [ + "sha256:a53dfe134b737845a9f2cb24fe0585317874f965932cebdb0439d13c8da4136e" + ], + "version": "==0.1.0" + }, + "tornado": { + "hashes": [ + "sha256:0662d28b1ca9f67108c7e3b77afabfb9c7e87bde174fbda78186ecedc2499a9d", + "sha256:4e5158d97583502a7e2739951553cbd88a72076f152b4b11b64b9a10c4c49409", + "sha256:732e836008c708de2e89a31cb2fa6c0e5a70cb60492bee6f1ea1047500feaf7f", + "sha256:8154ec22c450df4e06b35f131adc4f2f3a12ec85981a203301d310abf580500f", + "sha256:8e9d728c4579682e837c92fdd98036bd5cdefa1da2aaf6acf26947e6dd0c01c5", + "sha256:d4b3e5329f572f055b587efc57d29bd051589fb5a43ec8898c77a47ec2fa2bbb", + "sha256:e5f2585afccbff22390cddac29849df463b252b711aa2ce7c5f3f342a5b3b444" + ], + "version": "==5.1.1" + }, + "traitlets": { + "hashes": [ + "sha256:9c4bd2d267b7153df9152698efb1050a5d84982d3384a37b2c1f7723ba3e7835", + "sha256:c6cb5e6f57c5a9bdaa40fa71ce7b4af30298fbab9ece9815b5d995ab6217c7d9" + ], + "version": "==4.3.2" + }, + "transforms3d": { + "hashes": [ + "sha256:404c7797c78aa461cb8043081901fc5517cef342d5ff56becd74a7967ba88d78" + ], + "index": "pypi", + "version": "==0.3.1" + }, + "typing": { + "hashes": [ + "sha256:4027c5f6127a6267a435201981ba156de91ad0d1d98e9ddc2aa173453453492d", + "sha256:57dcf675a99b74d64dacf6fba08fb17cf7e3d5fdff53d4a30ea2a5e7e52543d4", + "sha256:a4c8473ce11a65999c8f59cb093e70686b6c84c98df58c1dae9b3b196089858a" + ], + "markers": "python_version < '3.5'", + "version": "==3.6.6" + }, + "urllib3": { + "hashes": [ + "sha256:b246607a25ac80bedac05c6f282e3cdaf3afb65420fd024ac94435cabe6e18d1", + "sha256:dbe59173209418ae49d485b87d1681aefa36252ee85884c31346debd19463232" + ], + "index": "pypi", + "version": "==1.25.3" + }, + "utm": { + "hashes": [ + "sha256:a6608a67df84418fd959a79b228b90ab55b2ae877827f9c210947104c5a75d0e" + ], + "index": "pypi", + "version": "==0.4.2" + }, + "uwsgi": { + "hashes": [ + "sha256:4972ac538800fb2d421027f49b4a1869b66048839507ccf0aa2fda792d99f583" + ], + "index": "pypi", + "version": "==2.0.18" + }, + "v4l2": { + "hashes": [ + "sha256:0d8f31f9d554ded4d0b50a31a7be5590b861df9e1ba256ee757e1c09175dd4a2" + ], + "index": "pypi", + "version": "==0.2" + }, + "vine": { + "hashes": [ + "sha256:133ee6d7a9016f177ddeaf191c1f58421a1dcc6ee9a42c58b34bed40e1d2cd87", + "sha256:ea4947cc56d1fd6f2095c8d543ee25dad966f78692528e68b4fada11ba3f98af" + ], + "version": "==1.3.0" + }, + "visdom": { + "hashes": [ + "sha256:77edd6811471282740846672a996348e963b5fa4220780f126c71481ad21d5a5" + ], + "index": "pypi", + "version": "==0.1.8.8" + }, + "wcwidth": { + "hashes": [ + "sha256:3df37372226d6e63e1b1e1eda15c594bca98a22d33a23832a90998faa96bc65e", + "sha256:f4ebe71925af7b40a864553f761ed559b43544f8f71746c2d756c7fe788ade7c" + ], + "version": "==0.1.7" + }, + "websocket-client": { + "hashes": [ + "sha256:1151d5fb3a62dc129164292e1227655e4bbc5dd5340a5165dfae61128ec50aa9", + "sha256:1fd5520878b68b84b5748bb30e592b10d0a91529d5383f74f4964e72b297fd3a" + ], + "index": "pypi", + "version": "==0.56.0" + }, + "werkzeug": { + "hashes": [ + "sha256:865856ebb55c4dcd0630cdd8f3331a1847a819dda7e8c750d3db6f2aa6c0209c", + "sha256:a0b915f0815982fb2a09161cb8f31708052d0951c3ba433ccc5e1aa276507ca6" + ], + "version": "==0.15.4" + }, + "wheel": { + "hashes": [ + "sha256:5e79117472686ac0c4aef5bad5172ea73a1c2d1646b808c35926bd26bdfb0c08", + "sha256:62fcfa03d45b5b722539ccbc07b190e4bfff4bb9e3a4d470dd9f6a0981002565" + ], + "markers": "python_version < '3'", + "version": "==0.33.4" + }, + "widgetsnbextension": { + "hashes": [ + "sha256:14b2c65f9940c9a7d3b70adbe713dbd38b5ec69724eebaba034d1036cf3d4740", + "sha256:fa618be8435447a017fd1bf2c7ae922d0428056cfc7449f7a8641edf76b48265" + ], + "version": "==3.4.2" + }, + "wrapt": { + "hashes": [ + "sha256:4aea003270831cceb8a90ff27c4031da6ead7ec1886023b80ce0dfe0adf61533" + ], + "version": "==1.11.1" + } + } +} diff --git a/README.md b/README.md index bf9f280928..7776587faf 100644 --- a/README.md +++ b/README.md @@ -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 | Custom6| | Kia | Sorento 2018 | All | Yes | Stock | 0mph | 0mph | Custom6| | Kia | Stinger 2018 | SCC + LKAS | Yes | Stock | 0mph | 0mph | Custom6| +| Lexus | ES Hybrid 2019 | All | Yes | Yes | 0mph | 0mph | Toyota | | Lexus | RX Hybrid 2016-19 | All | Yes | Yes2| 0mph | 0mph | Toyota | | Subaru | Crosstrek 2018 | EyeSight | Yes | Stock | 0mph | 0mph | Custom4| | Subaru | Impreza 2019 | EyeSight | Yes | Stock | 0mph | 0mph | Custom4| | Toyota | Avalon 2016 | TSS-P | Yes | Yes2| 20mph1| 0mph | Toyota | | Toyota | Camry 2018 | All | Yes | Stock | 0mph5 | 0mph | Toyota | | Toyota | C-HR 2017-18 | All | Yes | Stock | 0mph | 0mph | Toyota | -| Toyota | Corolla 2017-18 | All | Yes | Yes2| 20mph1| 0mph | Toyota | +| Toyota | Corolla 2017-19 | All | Yes | Yes2| 20mph1| 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 | Yes2| 0mph | 0mph | Toyota | | Toyota | Highlander Hybrid 2018 | All | Yes | Yes2| 0mph | 0mph | Toyota | diff --git a/RELEASES.md b/RELEASES.md index 50e71874b5..f73b8daf83 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -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) diff --git a/apk/ai.comma.plus.black.apk b/apk/ai.comma.plus.black.apk index b9243077f3..94b3a6a191 100644 Binary files a/apk/ai.comma.plus.black.apk and b/apk/ai.comma.plus.black.apk differ diff --git a/apk/ai.comma.plus.frame.apk b/apk/ai.comma.plus.frame.apk index b561d3fd78..374862a792 100644 Binary files a/apk/ai.comma.plus.frame.apk and b/apk/ai.comma.plus.frame.apk differ diff --git a/apk/ai.comma.plus.offroad.apk b/apk/ai.comma.plus.offroad.apk index 4ab1da4ce8..41920230b4 100644 Binary files a/apk/ai.comma.plus.offroad.apk and b/apk/ai.comma.plus.offroad.apk differ diff --git a/common/fingerprints.py b/common/fingerprints.py index 5a29c9555c..ddc3bceb66 100644 --- a/common/fingerprints.py +++ b/common/fingerprints.py @@ -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')]: diff --git a/common/kalman/Makefile b/common/kalman/Makefile index cb8f092650..88b032af1b 100644 --- a/common/kalman/Makefile +++ b/common/kalman/Makefile @@ -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 diff --git a/common/params.py b/common/params.py index cde03156f3..c374d5233e 100755 --- a/common/params.py +++ b/common/params.py @@ -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], diff --git a/common/realtime.py b/common/realtime.py index 21204db0dd..8bcd06966f 100644 --- a/common/realtime.py +++ b/common/realtime.py @@ -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) diff --git a/common/transformations/camera.py b/common/transformations/camera.py index 1ac9bc5b28..2e04c5ac22 100644 --- a/common/transformations/camera.py +++ b/common/transformations/camera.py @@ -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) - diff --git a/installer/updater/Makefile b/installer/updater/Makefile new file mode 100644 index 0000000000..d9444e6c59 --- /dev/null +++ b/installer/updater/Makefile @@ -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) diff --git a/installer/updater/update.json b/installer/updater/update.json new file mode 100644 index 0000000000..827a44b10d --- /dev/null +++ b/installer/updater/update.json @@ -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" +} diff --git a/installer/updater/updater b/installer/updater/updater index 84a8614d51..857a78e6f5 100755 Binary files a/installer/updater/updater and b/installer/updater/updater differ diff --git a/installer/updater/updater.cc b/installer/updater/updater.cc new file mode 100644 index 0000000000..58fab32413 --- /dev/null +++ b/installer/updater/updater.cc @@ -0,0 +1,675 @@ +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#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 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 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 guard(lock); + progress_text = text; + } + + void set_error(std::string text) { + std::lock_guard 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 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 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 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; +} diff --git a/launch_chffrplus.sh b/launch_chffrplus.sh index 4b7c4c0369..4aa9d402b7 100755 --- a/launch_chffrplus.sh +++ b/launch_chffrplus.sh @@ -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 diff --git a/models/driving_model.dlc b/models/driving_model.dlc index a33c1feb08..3cceccf116 100644 Binary files a/models/driving_model.dlc and b/models/driving_model.dlc differ diff --git a/phonelibs/android_frameworks_native/get.txt b/phonelibs/android_frameworks_native/get.txt new file mode 100644 index 0000000000..31f42ebe0e --- /dev/null +++ b/phonelibs/android_frameworks_native/get.txt @@ -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/ diff --git a/phonelibs/android_frameworks_native/include/android/asset_manager.h b/phonelibs/android_frameworks_native/include/android/asset_manager.h new file mode 100644 index 0000000000..d65483968e --- /dev/null +++ b/phonelibs/android_frameworks_native/include/android/asset_manager.h @@ -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 + +/** @} */ diff --git a/phonelibs/android_frameworks_native/include/android/asset_manager_jni.h b/phonelibs/android_frameworks_native/include/android/asset_manager_jni.h new file mode 100644 index 0000000000..dcee17e10f --- /dev/null +++ b/phonelibs/android_frameworks_native/include/android/asset_manager_jni.h @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @addtogroup Asset + * @{ + */ + +/** + * @file asset_manager_jni.h + */ + +#ifndef ANDROID_ASSET_MANAGER_JNI_H +#define ANDROID_ASSET_MANAGER_JNI_H + +#include +#include + +#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 + +/** @} */ diff --git a/phonelibs/android_frameworks_native/include/android/bitmap.h b/phonelibs/android_frameworks_native/include/android/bitmap.h new file mode 100644 index 0000000000..261e64fac9 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/android/bitmap.h @@ -0,0 +1,112 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @addtogroup Bitmap + * @{ + */ + +/** + * @file bitmap.h + */ + +#ifndef ANDROID_BITMAP_H +#define ANDROID_BITMAP_H + +#include +#include + +#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 + +/** @} */ diff --git a/phonelibs/android_frameworks_native/include/android/configuration.h b/phonelibs/android_frameworks_native/include/android/configuration.h new file mode 100644 index 0000000000..81f71a92cb --- /dev/null +++ b/phonelibs/android_frameworks_native/include/android/configuration.h @@ -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 + +#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 + * port + * resource qualifier. + */ + ACONFIGURATION_ORIENTATION_PORT = 0x0001, + /** + * Orientation: value corresponding to the + * land + * 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 + * notouch + * resource qualifier. + */ + ACONFIGURATION_TOUCHSCREEN_NOTOUCH = 0x0001, + /** @deprecated Not currently supported or used. */ + ACONFIGURATION_TOUCHSCREEN_STYLUS = 0x0002, + /** + * Touchscreen: value corresponding to the + * finger + * resource qualifier. + */ + ACONFIGURATION_TOUCHSCREEN_FINGER = 0x0003, + + /** Density: default density. */ + ACONFIGURATION_DENSITY_DEFAULT = 0, + /** + * Density: value corresponding to the + * ldpi + * resource qualifier. + */ + ACONFIGURATION_DENSITY_LOW = 120, + /** + * Density: value corresponding to the + * mdpi + * resource qualifier. + */ + ACONFIGURATION_DENSITY_MEDIUM = 160, + /** + * Density: value corresponding to the + * tvdpi + * resource qualifier. + */ + ACONFIGURATION_DENSITY_TV = 213, + /** + * Density: value corresponding to the + * hdpi + * resource qualifier. + */ + ACONFIGURATION_DENSITY_HIGH = 240, + /** + * Density: value corresponding to the + * xhdpi + * resource qualifier. + */ + ACONFIGURATION_DENSITY_XHIGH = 320, + /** + * Density: value corresponding to the + * xxhdpi + * resource qualifier. + */ + ACONFIGURATION_DENSITY_XXHIGH = 480, + /** + * Density: value corresponding to the + * xxxhdpi + * 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 + * nokeys + * resource qualifier. + */ + ACONFIGURATION_KEYBOARD_NOKEYS = 0x0001, + /** + * Keyboard: value corresponding to the + * qwerty + * resource qualifier. + */ + ACONFIGURATION_KEYBOARD_QWERTY = 0x0002, + /** + * Keyboard: value corresponding to the + * 12key + * resource qualifier. + */ + ACONFIGURATION_KEYBOARD_12KEY = 0x0003, + + /** Navigation: not specified. */ + ACONFIGURATION_NAVIGATION_ANY = 0x0000, + /** + * Navigation: value corresponding to the + * nonav + * resource qualifier. + */ + ACONFIGURATION_NAVIGATION_NONAV = 0x0001, + /** + * Navigation: value corresponding to the + * dpad + * resource qualifier. + */ + ACONFIGURATION_NAVIGATION_DPAD = 0x0002, + /** + * Navigation: value corresponding to the + * trackball + * resource qualifier. + */ + ACONFIGURATION_NAVIGATION_TRACKBALL = 0x0003, + /** + * Navigation: value corresponding to the + * wheel + * resource qualifier. + */ + ACONFIGURATION_NAVIGATION_WHEEL = 0x0004, + + /** Keyboard availability: not specified. */ + ACONFIGURATION_KEYSHIDDEN_ANY = 0x0000, + /** + * Keyboard availability: value corresponding to the + * keysexposed + * resource qualifier. + */ + ACONFIGURATION_KEYSHIDDEN_NO = 0x0001, + /** + * Keyboard availability: value corresponding to the + * keyshidden + * resource qualifier. + */ + ACONFIGURATION_KEYSHIDDEN_YES = 0x0002, + /** + * Keyboard availability: value corresponding to the + * keyssoft + * resource qualifier. + */ + ACONFIGURATION_KEYSHIDDEN_SOFT = 0x0003, + + /** Navigation availability: not specified. */ + ACONFIGURATION_NAVHIDDEN_ANY = 0x0000, + /** + * Navigation availability: value corresponding to the + * navexposed + * resource qualifier. + */ + ACONFIGURATION_NAVHIDDEN_NO = 0x0001, + /** + * Navigation availability: value corresponding to the + * navhidden + * 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 + * small + * resource qualifier. + */ + ACONFIGURATION_SCREENSIZE_SMALL = 0x01, + /** + * Screen size: value indicating the screen is at least + * approximately 320x470 dp units, corresponding to the + * normal + * resource qualifier. + */ + ACONFIGURATION_SCREENSIZE_NORMAL = 0x02, + /** + * Screen size: value indicating the screen is at least + * approximately 480x640 dp units, corresponding to the + * large + * resource qualifier. + */ + ACONFIGURATION_SCREENSIZE_LARGE = 0x03, + /** + * Screen size: value indicating the screen is at least + * approximately 720x960 dp units, corresponding to the + * xlarge + * resource qualifier. + */ + ACONFIGURATION_SCREENSIZE_XLARGE = 0x04, + + /** Screen layout: not specified. */ + ACONFIGURATION_SCREENLONG_ANY = 0x00, + /** + * Screen layout: value that corresponds to the + * notlong + * resource qualifier. + */ + ACONFIGURATION_SCREENLONG_NO = 0x1, + /** + * Screen layout: value that corresponds to the + * long + * 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 + * no + * UI mode type resource qualifier specified. + */ + ACONFIGURATION_UI_MODE_TYPE_NORMAL = 0x01, + /** + * UI mode: value that corresponds to + * desk resource qualifier specified. + */ + ACONFIGURATION_UI_MODE_TYPE_DESK = 0x02, + /** + * UI mode: value that corresponds to + * car resource qualifier specified. + */ + ACONFIGURATION_UI_MODE_TYPE_CAR = 0x03, + /** + * UI mode: value that corresponds to + * television resource qualifier specified. + */ + ACONFIGURATION_UI_MODE_TYPE_TELEVISION = 0x04, + /** + * UI mode: value that corresponds to + * appliance resource qualifier specified. + */ + ACONFIGURATION_UI_MODE_TYPE_APPLIANCE = 0x05, + /** + * UI mode: value that corresponds to + * watch 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 + * notnight resource qualifier specified. + */ + ACONFIGURATION_UI_MODE_NIGHT_NO = 0x1, + /** + * UI night mode: value that corresponds to + * night 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 + * ldltr resource qualifier specified. + */ + ACONFIGURATION_LAYOUTDIR_LTR = 0x01, + /** + * Layout direction: value that corresponds to + * ldrtl resource qualifier specified. + */ + ACONFIGURATION_LAYOUTDIR_RTL = 0x02, + + /** + * Bit mask for + * mcc + * configuration. + */ + ACONFIGURATION_MCC = 0x0001, + /** + * Bit mask for + * mnc + * configuration. + */ + ACONFIGURATION_MNC = 0x0002, + /** + * Bit mask for + * locale + * configuration. + */ + ACONFIGURATION_LOCALE = 0x0004, + /** + * Bit mask for + * touchscreen + * configuration. + */ + ACONFIGURATION_TOUCHSCREEN = 0x0008, + /** + * Bit mask for + * keyboard + * configuration. + */ + ACONFIGURATION_KEYBOARD = 0x0010, + /** + * Bit mask for + * keyboardHidden + * configuration. + */ + ACONFIGURATION_KEYBOARD_HIDDEN = 0x0020, + /** + * Bit mask for + * navigation + * configuration. + */ + ACONFIGURATION_NAVIGATION = 0x0040, + /** + * Bit mask for + * orientation + * configuration. + */ + ACONFIGURATION_ORIENTATION = 0x0080, + /** + * Bit mask for + * density + * configuration. + */ + ACONFIGURATION_DENSITY = 0x0100, + /** + * Bit mask for + * screen size + * configuration. + */ + ACONFIGURATION_SCREEN_SIZE = 0x0200, + /** + * Bit mask for + * platform version + * configuration. + */ + ACONFIGURATION_VERSION = 0x0400, + /** + * Bit mask for screen layout configuration. + */ + ACONFIGURATION_SCREEN_LAYOUT = 0x0800, + /** + * Bit mask for + * ui mode + * configuration. + */ + ACONFIGURATION_UI_MODE = 0x1000, + /** + * Bit mask for + * smallest screen width + * configuration. + */ + ACONFIGURATION_SMALLEST_SCREEN_SIZE = 0x2000, + /** + * Bit mask for + * layout direction + * 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 + +/** @} */ diff --git a/phonelibs/android_frameworks_native/include/android/input.h b/phonelibs/android_frameworks_native/include/android/input.h new file mode 100644 index 0000000000..46cf89c7e1 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/android/input.h @@ -0,0 +1,1317 @@ +/* + * 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 input.h + */ + +#ifndef _ANDROID_INPUT_H +#define _ANDROID_INPUT_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 input events in + * native code. + * + * NOTE: These functions MUST be implemented by /system/lib/libui.so + */ + +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Key states (may be returned by queries about the current state of a + * particular key code, scan code or switch). + */ +enum { + /** The key state is unknown or the requested key itself is not supported. */ + AKEY_STATE_UNKNOWN = -1, + + /** The key is up. */ + AKEY_STATE_UP = 0, + + /** The key is down. */ + AKEY_STATE_DOWN = 1, + + /** The key is down but is a virtual key press that is being emulated by the system. */ + AKEY_STATE_VIRTUAL = 2 +}; + +/** + * Meta key / modifer state. + */ +enum { + /** No meta keys are pressed. */ + AMETA_NONE = 0, + + /** This mask is used to check whether one of the ALT meta keys is pressed. */ + AMETA_ALT_ON = 0x02, + + /** This mask is used to check whether the left ALT meta key is pressed. */ + AMETA_ALT_LEFT_ON = 0x10, + + /** This mask is used to check whether the right ALT meta key is pressed. */ + AMETA_ALT_RIGHT_ON = 0x20, + + /** This mask is used to check whether one of the SHIFT meta keys is pressed. */ + AMETA_SHIFT_ON = 0x01, + + /** This mask is used to check whether the left SHIFT meta key is pressed. */ + AMETA_SHIFT_LEFT_ON = 0x40, + + /** This mask is used to check whether the right SHIFT meta key is pressed. */ + AMETA_SHIFT_RIGHT_ON = 0x80, + + /** This mask is used to check whether the SYM meta key is pressed. */ + AMETA_SYM_ON = 0x04, + + /** This mask is used to check whether the FUNCTION meta key is pressed. */ + AMETA_FUNCTION_ON = 0x08, + + /** This mask is used to check whether one of the CTRL meta keys is pressed. */ + AMETA_CTRL_ON = 0x1000, + + /** This mask is used to check whether the left CTRL meta key is pressed. */ + AMETA_CTRL_LEFT_ON = 0x2000, + + /** This mask is used to check whether the right CTRL meta key is pressed. */ + AMETA_CTRL_RIGHT_ON = 0x4000, + + /** This mask is used to check whether one of the META meta keys is pressed. */ + AMETA_META_ON = 0x10000, + + /** This mask is used to check whether the left META meta key is pressed. */ + AMETA_META_LEFT_ON = 0x20000, + + /** This mask is used to check whether the right META meta key is pressed. */ + AMETA_META_RIGHT_ON = 0x40000, + + /** This mask is used to check whether the CAPS LOCK meta key is on. */ + AMETA_CAPS_LOCK_ON = 0x100000, + + /** This mask is used to check whether the NUM LOCK meta key is on. */ + AMETA_NUM_LOCK_ON = 0x200000, + + /** This mask is used to check whether the SCROLL LOCK meta key is on. */ + AMETA_SCROLL_LOCK_ON = 0x400000, +}; + +struct AInputEvent; +/** + * Input events. + * + * Input events are opaque structures. Use the provided accessors functions to + * read their properties. + */ +typedef struct AInputEvent AInputEvent; + +/** + * Input event types. + */ +enum { + /** Indicates that the input event is a key event. */ + AINPUT_EVENT_TYPE_KEY = 1, + + /** Indicates that the input event is a motion event. */ + AINPUT_EVENT_TYPE_MOTION = 2 +}; + +/** + * Key event actions. + */ +enum { + /** The key has been pressed down. */ + AKEY_EVENT_ACTION_DOWN = 0, + + /** The key has been released. */ + AKEY_EVENT_ACTION_UP = 1, + + /** + * Multiple duplicate key events have occurred in a row, or a + * complex string is being delivered. The repeat_count property + * of the key event contains the number of times the given key + * code should be executed. + */ + AKEY_EVENT_ACTION_MULTIPLE = 2 +}; + +/** + * Key event flags. + */ +enum { + /** This mask is set if the device woke because of this key event. */ + AKEY_EVENT_FLAG_WOKE_HERE = 0x1, + + /** This mask is set if the key event was generated by a software keyboard. */ + AKEY_EVENT_FLAG_SOFT_KEYBOARD = 0x2, + + /** This mask is set if we don't want the key event to cause us to leave touch mode. */ + AKEY_EVENT_FLAG_KEEP_TOUCH_MODE = 0x4, + + /** + * This mask is set if an event was known to come from a trusted + * part of the system. That is, the event is known to come from + * the user, and could not have been spoofed by a third party + * component. + */ + AKEY_EVENT_FLAG_FROM_SYSTEM = 0x8, + + /** + * This mask is used for compatibility, to identify enter keys that are + * coming from an IME whose enter key has been auto-labelled "next" or + * "done". This allows TextView to dispatch these as normal enter keys + * for old applications, but still do the appropriate action when + * receiving them. + */ + AKEY_EVENT_FLAG_EDITOR_ACTION = 0x10, + + /** + * When associated with up key events, this indicates that the key press + * has been canceled. Typically this is used with virtual touch screen + * keys, where the user can slide from the virtual key area on to the + * display: in that case, the application will receive a canceled up + * event and should not perform the action normally associated with the + * key. Note that for this to work, the application can not perform an + * action for a key until it receives an up or the long press timeout has + * expired. + */ + AKEY_EVENT_FLAG_CANCELED = 0x20, + + /** + * This key event was generated by a virtual (on-screen) hard key area. + * Typically this is an area of the touchscreen, outside of the regular + * display, dedicated to "hardware" buttons. + */ + AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY = 0x40, + + /** + * This flag is set for the first key repeat that occurs after the + * long press timeout. + */ + AKEY_EVENT_FLAG_LONG_PRESS = 0x80, + + /** + * Set when a key event has AKEY_EVENT_FLAG_CANCELED set because a long + * press action was executed while it was down. + */ + AKEY_EVENT_FLAG_CANCELED_LONG_PRESS = 0x100, + + /** + * Set for AKEY_EVENT_ACTION_UP when this event's key code is still being + * tracked from its initial down. That is, somebody requested that tracking + * started on the key down and a long press has not caused + * the tracking to be canceled. + */ + AKEY_EVENT_FLAG_TRACKING = 0x200, + + /** + * Set when a key event has been synthesized to implement default behavior + * for an event that the application did not handle. + * Fallback key events are generated by unhandled trackball motions + * (to emulate a directional keypad) and by certain unhandled key presses + * that are declared in the key map (such as special function numeric keypad + * keys when numlock is off). + */ + AKEY_EVENT_FLAG_FALLBACK = 0x400, +}; + +/** + * Bit shift for the action bits holding the pointer index as + * defined by AMOTION_EVENT_ACTION_POINTER_INDEX_MASK. + */ +#define AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT 8 + +/** Motion event actions */ +enum { + /** Bit mask of the parts of the action code that are the action itself. */ + AMOTION_EVENT_ACTION_MASK = 0xff, + + /** + * Bits in the action code that represent a pointer index, used with + * AMOTION_EVENT_ACTION_POINTER_DOWN and AMOTION_EVENT_ACTION_POINTER_UP. Shifting + * down by AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT provides the actual pointer + * index where the data for the pointer going up or down can be found. + */ + AMOTION_EVENT_ACTION_POINTER_INDEX_MASK = 0xff00, + + /** A pressed gesture has started, the motion contains the initial starting location. */ + AMOTION_EVENT_ACTION_DOWN = 0, + + /** + * A pressed gesture has finished, the motion contains the final release location + * as well as any intermediate points since the last down or move event. + */ + AMOTION_EVENT_ACTION_UP = 1, + + /** + * A change has happened during a press gesture (between AMOTION_EVENT_ACTION_DOWN and + * AMOTION_EVENT_ACTION_UP). The motion contains the most recent point, as well as + * any intermediate points since the last down or move event. + */ + AMOTION_EVENT_ACTION_MOVE = 2, + + /** + * The current gesture has been aborted. + * You will not receive any more points in it. You should treat this as + * an up event, but not perform any action that you normally would. + */ + AMOTION_EVENT_ACTION_CANCEL = 3, + + /** + * A movement has happened outside of the normal bounds of the UI element. + * This does not provide a full gesture, but only the initial location of the movement/touch. + */ + AMOTION_EVENT_ACTION_OUTSIDE = 4, + + /** + * A non-primary pointer has gone down. + * The bits in AMOTION_EVENT_ACTION_POINTER_INDEX_MASK indicate which pointer changed. + */ + AMOTION_EVENT_ACTION_POINTER_DOWN = 5, + + /** + * A non-primary pointer has gone up. + * The bits in AMOTION_EVENT_ACTION_POINTER_INDEX_MASK indicate which pointer changed. + */ + AMOTION_EVENT_ACTION_POINTER_UP = 6, + + /** + * A change happened but the pointer is not down (unlike AMOTION_EVENT_ACTION_MOVE). + * The motion contains the most recent point, as well as any intermediate points since + * the last hover move event. + */ + AMOTION_EVENT_ACTION_HOVER_MOVE = 7, + + /** + * The motion event contains relative vertical and/or horizontal scroll offsets. + * Use getAxisValue to retrieve the information from AMOTION_EVENT_AXIS_VSCROLL + * and AMOTION_EVENT_AXIS_HSCROLL. + * The pointer may or may not be down when this event is dispatched. + * This action is always delivered to the winder under the pointer, which + * may not be the window currently touched. + */ + AMOTION_EVENT_ACTION_SCROLL = 8, + + /** The pointer is not down but has entered the boundaries of a window or view. */ + AMOTION_EVENT_ACTION_HOVER_ENTER = 9, + + /** The pointer is not down but has exited the boundaries of a window or view. */ + AMOTION_EVENT_ACTION_HOVER_EXIT = 10, + + /* One or more buttons have been pressed. */ + AMOTION_EVENT_ACTION_BUTTON_PRESS = 11, + + /* One or more buttons have been released. */ + AMOTION_EVENT_ACTION_BUTTON_RELEASE = 12, +}; + +/** + * Motion event flags. + */ +enum { + /** + * This flag indicates that the window that received this motion event is partly + * or wholly obscured by another visible window above it. This flag is set to true + * even if the event did not directly pass through the obscured area. + * A security sensitive application can check this flag to identify situations in which + * a malicious application may have covered up part of its content for the purpose + * of misleading the user or hijacking touches. An appropriate response might be + * to drop the suspect touches or to take additional precautions to confirm the user's + * actual intent. + */ + AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED = 0x1, +}; + +/** + * Motion event edge touch flags. + */ +enum { + /** No edges intersected. */ + AMOTION_EVENT_EDGE_FLAG_NONE = 0, + + /** Flag indicating the motion event intersected the top edge of the screen. */ + AMOTION_EVENT_EDGE_FLAG_TOP = 0x01, + + /** Flag indicating the motion event intersected the bottom edge of the screen. */ + AMOTION_EVENT_EDGE_FLAG_BOTTOM = 0x02, + + /** Flag indicating the motion event intersected the left edge of the screen. */ + AMOTION_EVENT_EDGE_FLAG_LEFT = 0x04, + + /** Flag indicating the motion event intersected the right edge of the screen. */ + AMOTION_EVENT_EDGE_FLAG_RIGHT = 0x08 +}; + +/** + * Constants that identify each individual axis of a motion event. + * @anchor AMOTION_EVENT_AXIS + */ +enum { + /** + * Axis constant: X axis of a motion event. + * + * - For a touch screen, reports the absolute X screen position of the center of + * the touch contact area. The units are display pixels. + * - For a touch pad, reports the absolute X surface position of the center of the touch + * contact area. The units are device-dependent. + * - For a mouse, reports the absolute X screen position of the mouse pointer. + * The units are display pixels. + * - For a trackball, reports the relative horizontal displacement of the trackball. + * The value is normalized to a range from -1.0 (left) to 1.0 (right). + * - For a joystick, reports the absolute X position of the joystick. + * The value is normalized to a range from -1.0 (left) to 1.0 (right). + */ + AMOTION_EVENT_AXIS_X = 0, + /** + * Axis constant: Y axis of a motion event. + * + * - For a touch screen, reports the absolute Y screen position of the center of + * the touch contact area. The units are display pixels. + * - For a touch pad, reports the absolute Y surface position of the center of the touch + * contact area. The units are device-dependent. + * - For a mouse, reports the absolute Y screen position of the mouse pointer. + * The units are display pixels. + * - For a trackball, reports the relative vertical displacement of the trackball. + * The value is normalized to a range from -1.0 (up) to 1.0 (down). + * - For a joystick, reports the absolute Y position of the joystick. + * The value is normalized to a range from -1.0 (up or far) to 1.0 (down or near). + */ + AMOTION_EVENT_AXIS_Y = 1, + /** + * Axis constant: Pressure axis of a motion event. + * + * - For a touch screen or touch pad, reports the approximate pressure applied to the surface + * by a finger or other tool. The value is normalized to a range from + * 0 (no pressure at all) to 1 (normal pressure), although values higher than 1 + * may be generated depending on the calibration of the input device. + * - For a trackball, the value is set to 1 if the trackball button is pressed + * or 0 otherwise. + * - For a mouse, the value is set to 1 if the primary mouse button is pressed + * or 0 otherwise. + */ + AMOTION_EVENT_AXIS_PRESSURE = 2, + /** + * Axis constant: Size axis of a motion event. + * + * - For a touch screen or touch pad, reports the approximate size of the contact area in + * relation to the maximum detectable size for the device. The value is normalized + * to a range from 0 (smallest detectable size) to 1 (largest detectable size), + * although it is not a linear scale. This value is of limited use. + * To obtain calibrated size information, see + * {@link AMOTION_EVENT_AXIS_TOUCH_MAJOR} or {@link AMOTION_EVENT_AXIS_TOOL_MAJOR}. + */ + AMOTION_EVENT_AXIS_SIZE = 3, + /** + * Axis constant: TouchMajor axis of a motion event. + * + * - For a touch screen, reports the length of the major axis of an ellipse that + * represents the touch area at the point of contact. + * The units are display pixels. + * - For a touch pad, reports the length of the major axis of an ellipse that + * represents the touch area at the point of contact. + * The units are device-dependent. + */ + AMOTION_EVENT_AXIS_TOUCH_MAJOR = 4, + /** + * Axis constant: TouchMinor axis of a motion event. + * + * - For a touch screen, reports the length of the minor axis of an ellipse that + * represents the touch area at the point of contact. + * The units are display pixels. + * - For a touch pad, reports the length of the minor axis of an ellipse that + * represents the touch area at the point of contact. + * The units are device-dependent. + * + * When the touch is circular, the major and minor axis lengths will be equal to one another. + */ + AMOTION_EVENT_AXIS_TOUCH_MINOR = 5, + /** + * Axis constant: ToolMajor axis of a motion event. + * + * - For a touch screen, reports the length of the major axis of an ellipse that + * represents the size of the approaching finger or tool used to make contact. + * - For a touch pad, reports the length of the major axis of an ellipse that + * represents the size of the approaching finger or tool used to make contact. + * The units are device-dependent. + * + * When the touch is circular, the major and minor axis lengths will be equal to one another. + * + * The tool size may be larger than the touch size since the tool may not be fully + * in contact with the touch sensor. + */ + AMOTION_EVENT_AXIS_TOOL_MAJOR = 6, + /** + * Axis constant: ToolMinor axis of a motion event. + * + * - For a touch screen, reports the length of the minor axis of an ellipse that + * represents the size of the approaching finger or tool used to make contact. + * - For a touch pad, reports the length of the minor axis of an ellipse that + * represents the size of the approaching finger or tool used to make contact. + * The units are device-dependent. + * + * When the touch is circular, the major and minor axis lengths will be equal to one another. + * + * The tool size may be larger than the touch size since the tool may not be fully + * in contact with the touch sensor. + */ + AMOTION_EVENT_AXIS_TOOL_MINOR = 7, + /** + * Axis constant: Orientation axis of a motion event. + * + * - For a touch screen or touch pad, reports the orientation of the finger + * or tool in radians relative to the vertical plane of the device. + * An angle of 0 radians indicates that the major axis of contact is oriented + * upwards, is perfectly circular or is of unknown orientation. A positive angle + * indicates that the major axis of contact is oriented to the right. A negative angle + * indicates that the major axis of contact is oriented to the left. + * The full range is from -PI/2 radians (finger pointing fully left) to PI/2 radians + * (finger pointing fully right). + * - For a stylus, the orientation indicates the direction in which the stylus + * is pointing in relation to the vertical axis of the current orientation of the screen. + * The range is from -PI radians to PI radians, where 0 is pointing up, + * -PI/2 radians is pointing left, -PI or PI radians is pointing down, and PI/2 radians + * is pointing right. See also {@link AMOTION_EVENT_AXIS_TILT}. + */ + AMOTION_EVENT_AXIS_ORIENTATION = 8, + /** + * Axis constant: Vertical Scroll axis of a motion event. + * + * - For a mouse, reports the relative movement of the vertical scroll wheel. + * The value is normalized to a range from -1.0 (down) to 1.0 (up). + * + * This axis should be used to scroll views vertically. + */ + AMOTION_EVENT_AXIS_VSCROLL = 9, + /** + * Axis constant: Horizontal Scroll axis of a motion event. + * + * - For a mouse, reports the relative movement of the horizontal scroll wheel. + * The value is normalized to a range from -1.0 (left) to 1.0 (right). + * + * This axis should be used to scroll views horizontally. + */ + AMOTION_EVENT_AXIS_HSCROLL = 10, + /** + * Axis constant: Z axis of a motion event. + * + * - For a joystick, reports the absolute Z position of the joystick. + * The value is normalized to a range from -1.0 (high) to 1.0 (low). + * On game pads with two analog joysticks, this axis is often reinterpreted + * to report the absolute X position of the second joystick instead. + */ + AMOTION_EVENT_AXIS_Z = 11, + /** + * Axis constant: X Rotation axis of a motion event. + * + * - For a joystick, reports the absolute rotation angle about the X axis. + * The value is normalized to a range from -1.0 (counter-clockwise) to 1.0 (clockwise). + */ + AMOTION_EVENT_AXIS_RX = 12, + /** + * Axis constant: Y Rotation axis of a motion event. + * + * - For a joystick, reports the absolute rotation angle about the Y axis. + * The value is normalized to a range from -1.0 (counter-clockwise) to 1.0 (clockwise). + */ + AMOTION_EVENT_AXIS_RY = 13, + /** + * Axis constant: Z Rotation axis of a motion event. + * + * - For a joystick, reports the absolute rotation angle about the Z axis. + * The value is normalized to a range from -1.0 (counter-clockwise) to 1.0 (clockwise). + * On game pads with two analog joysticks, this axis is often reinterpreted + * to report the absolute Y position of the second joystick instead. + */ + AMOTION_EVENT_AXIS_RZ = 14, + /** + * Axis constant: Hat X axis of a motion event. + * + * - For a joystick, reports the absolute X position of the directional hat control. + * The value is normalized to a range from -1.0 (left) to 1.0 (right). + */ + AMOTION_EVENT_AXIS_HAT_X = 15, + /** + * Axis constant: Hat Y axis of a motion event. + * + * - For a joystick, reports the absolute Y position of the directional hat control. + * The value is normalized to a range from -1.0 (up) to 1.0 (down). + */ + AMOTION_EVENT_AXIS_HAT_Y = 16, + /** + * Axis constant: Left Trigger axis of a motion event. + * + * - For a joystick, reports the absolute position of the left trigger control. + * The value is normalized to a range from 0.0 (released) to 1.0 (fully pressed). + */ + AMOTION_EVENT_AXIS_LTRIGGER = 17, + /** + * Axis constant: Right Trigger axis of a motion event. + * + * - For a joystick, reports the absolute position of the right trigger control. + * The value is normalized to a range from 0.0 (released) to 1.0 (fully pressed). + */ + AMOTION_EVENT_AXIS_RTRIGGER = 18, + /** + * Axis constant: Throttle axis of a motion event. + * + * - For a joystick, reports the absolute position of the throttle control. + * The value is normalized to a range from 0.0 (fully open) to 1.0 (fully closed). + */ + AMOTION_EVENT_AXIS_THROTTLE = 19, + /** + * Axis constant: Rudder axis of a motion event. + * + * - For a joystick, reports the absolute position of the rudder control. + * The value is normalized to a range from -1.0 (turn left) to 1.0 (turn right). + */ + AMOTION_EVENT_AXIS_RUDDER = 20, + /** + * Axis constant: Wheel axis of a motion event. + * + * - For a joystick, reports the absolute position of the steering wheel control. + * The value is normalized to a range from -1.0 (turn left) to 1.0 (turn right). + */ + AMOTION_EVENT_AXIS_WHEEL = 21, + /** + * Axis constant: Gas axis of a motion event. + * + * - For a joystick, reports the absolute position of the gas (accelerator) control. + * The value is normalized to a range from 0.0 (no acceleration) + * to 1.0 (maximum acceleration). + */ + AMOTION_EVENT_AXIS_GAS = 22, + /** + * Axis constant: Brake axis of a motion event. + * + * - For a joystick, reports the absolute position of the brake control. + * The value is normalized to a range from 0.0 (no braking) to 1.0 (maximum braking). + */ + AMOTION_EVENT_AXIS_BRAKE = 23, + /** + * Axis constant: Distance axis of a motion event. + * + * - For a stylus, reports the distance of the stylus from the screen. + * A value of 0.0 indicates direct contact and larger values indicate increasing + * distance from the surface. + */ + AMOTION_EVENT_AXIS_DISTANCE = 24, + /** + * Axis constant: Tilt axis of a motion event. + * + * - For a stylus, reports the tilt angle of the stylus in radians where + * 0 radians indicates that the stylus is being held perpendicular to the + * surface, and PI/2 radians indicates that the stylus is being held flat + * against the surface. + */ + AMOTION_EVENT_AXIS_TILT = 25, + /** + * Axis constant: Generic 1 axis of a motion event. + * The interpretation of a generic axis is device-specific. + */ + AMOTION_EVENT_AXIS_GENERIC_1 = 32, + /** + * Axis constant: Generic 2 axis of a motion event. + * The interpretation of a generic axis is device-specific. + */ + AMOTION_EVENT_AXIS_GENERIC_2 = 33, + /** + * Axis constant: Generic 3 axis of a motion event. + * The interpretation of a generic axis is device-specific. + */ + AMOTION_EVENT_AXIS_GENERIC_3 = 34, + /** + * Axis constant: Generic 4 axis of a motion event. + * The interpretation of a generic axis is device-specific. + */ + AMOTION_EVENT_AXIS_GENERIC_4 = 35, + /** + * Axis constant: Generic 5 axis of a motion event. + * The interpretation of a generic axis is device-specific. + */ + AMOTION_EVENT_AXIS_GENERIC_5 = 36, + /** + * Axis constant: Generic 6 axis of a motion event. + * The interpretation of a generic axis is device-specific. + */ + AMOTION_EVENT_AXIS_GENERIC_6 = 37, + /** + * Axis constant: Generic 7 axis of a motion event. + * The interpretation of a generic axis is device-specific. + */ + AMOTION_EVENT_AXIS_GENERIC_7 = 38, + /** + * Axis constant: Generic 8 axis of a motion event. + * The interpretation of a generic axis is device-specific. + */ + AMOTION_EVENT_AXIS_GENERIC_8 = 39, + /** + * Axis constant: Generic 9 axis of a motion event. + * The interpretation of a generic axis is device-specific. + */ + AMOTION_EVENT_AXIS_GENERIC_9 = 40, + /** + * Axis constant: Generic 10 axis of a motion event. + * The interpretation of a generic axis is device-specific. + */ + AMOTION_EVENT_AXIS_GENERIC_10 = 41, + /** + * Axis constant: Generic 11 axis of a motion event. + * The interpretation of a generic axis is device-specific. + */ + AMOTION_EVENT_AXIS_GENERIC_11 = 42, + /** + * Axis constant: Generic 12 axis of a motion event. + * The interpretation of a generic axis is device-specific. + */ + AMOTION_EVENT_AXIS_GENERIC_12 = 43, + /** + * Axis constant: Generic 13 axis of a motion event. + * The interpretation of a generic axis is device-specific. + */ + AMOTION_EVENT_AXIS_GENERIC_13 = 44, + /** + * Axis constant: Generic 14 axis of a motion event. + * The interpretation of a generic axis is device-specific. + */ + AMOTION_EVENT_AXIS_GENERIC_14 = 45, + /** + * Axis constant: Generic 15 axis of a motion event. + * The interpretation of a generic axis is device-specific. + */ + AMOTION_EVENT_AXIS_GENERIC_15 = 46, + /** + * Axis constant: Generic 16 axis of a motion event. + * The interpretation of a generic axis is device-specific. + */ + AMOTION_EVENT_AXIS_GENERIC_16 = 47, + + // NOTE: If you add a new axis here you must also add it to several other files. + // Refer to frameworks/base/core/java/android/view/MotionEvent.java for the full list. +}; + +/** + * Constants that identify buttons that are associated with motion events. + * Refer to the documentation on the MotionEvent class for descriptions of each button. + */ +enum { + /** primary */ + AMOTION_EVENT_BUTTON_PRIMARY = 1 << 0, + /** secondary */ + AMOTION_EVENT_BUTTON_SECONDARY = 1 << 1, + /** tertiary */ + AMOTION_EVENT_BUTTON_TERTIARY = 1 << 2, + /** back */ + AMOTION_EVENT_BUTTON_BACK = 1 << 3, + /** forward */ + AMOTION_EVENT_BUTTON_FORWARD = 1 << 4, + AMOTION_EVENT_BUTTON_STYLUS_PRIMARY = 1 << 5, + AMOTION_EVENT_BUTTON_STYLUS_SECONDARY = 1 << 6, +}; + +/** + * Constants that identify tool types. + * Refer to the documentation on the MotionEvent class for descriptions of each tool type. + */ +enum { + /** unknown */ + AMOTION_EVENT_TOOL_TYPE_UNKNOWN = 0, + /** finger */ + AMOTION_EVENT_TOOL_TYPE_FINGER = 1, + /** stylus */ + AMOTION_EVENT_TOOL_TYPE_STYLUS = 2, + /** mouse */ + AMOTION_EVENT_TOOL_TYPE_MOUSE = 3, + /** eraser */ + AMOTION_EVENT_TOOL_TYPE_ERASER = 4, +}; + +/** + * Input source masks. + * + * Refer to the documentation on android.view.InputDevice for more details about input sources + * and their correct interpretation. + */ +enum { + /** mask */ + AINPUT_SOURCE_CLASS_MASK = 0x000000ff, + + /** none */ + AINPUT_SOURCE_CLASS_NONE = 0x00000000, + /** button */ + AINPUT_SOURCE_CLASS_BUTTON = 0x00000001, + /** pointer */ + AINPUT_SOURCE_CLASS_POINTER = 0x00000002, + /** navigation */ + AINPUT_SOURCE_CLASS_NAVIGATION = 0x00000004, + /** position */ + AINPUT_SOURCE_CLASS_POSITION = 0x00000008, + /** joystick */ + AINPUT_SOURCE_CLASS_JOYSTICK = 0x00000010, +}; + +/** + * Input sources. + */ +enum { + /** unknown */ + AINPUT_SOURCE_UNKNOWN = 0x00000000, + + /** keyboard */ + AINPUT_SOURCE_KEYBOARD = 0x00000100 | AINPUT_SOURCE_CLASS_BUTTON, + /** dpad */ + AINPUT_SOURCE_DPAD = 0x00000200 | AINPUT_SOURCE_CLASS_BUTTON, + /** gamepad */ + AINPUT_SOURCE_GAMEPAD = 0x00000400 | AINPUT_SOURCE_CLASS_BUTTON, + /** touchscreen */ + AINPUT_SOURCE_TOUCHSCREEN = 0x00001000 | AINPUT_SOURCE_CLASS_POINTER, + /** mouse */ + AINPUT_SOURCE_MOUSE = 0x00002000 | AINPUT_SOURCE_CLASS_POINTER, + /** stylus */ + AINPUT_SOURCE_STYLUS = 0x00004000 | AINPUT_SOURCE_CLASS_POINTER, + /** bluetooth stylus */ + AINPUT_SOURCE_BLUETOOTH_STYLUS = 0x00008000 | AINPUT_SOURCE_STYLUS, + /** trackball */ + AINPUT_SOURCE_TRACKBALL = 0x00010000 | AINPUT_SOURCE_CLASS_NAVIGATION, + /** touchpad */ + AINPUT_SOURCE_TOUCHPAD = 0x00100000 | AINPUT_SOURCE_CLASS_POSITION, + /** navigation */ + AINPUT_SOURCE_TOUCH_NAVIGATION = 0x00200000 | AINPUT_SOURCE_CLASS_NONE, + /** gesture sensor (?) */ + AINPUT_SOURCE_GESTURE_SENSOR = 0x00400000 | AINPUT_SOURCE_CLASS_NONE, + /** joystick */ + AINPUT_SOURCE_JOYSTICK = 0x01000000 | AINPUT_SOURCE_CLASS_JOYSTICK, + + /** any */ + AINPUT_SOURCE_ANY = 0xffffff00, +}; + +/** + * Keyboard types. + * + * Refer to the documentation on android.view.InputDevice for more details. + */ +enum { + /** none */ + AINPUT_KEYBOARD_TYPE_NONE = 0, + /** non alphabetic */ + AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC = 1, + /** alphabetic */ + AINPUT_KEYBOARD_TYPE_ALPHABETIC = 2, +}; + +/** + * Constants used to retrieve information about the range of motion for a particular + * coordinate of a motion event. + * + * Refer to the documentation on android.view.InputDevice for more details about input sources + * and their correct interpretation. + * + * @deprecated These constants are deprecated. Use {@link AMOTION_EVENT_AXIS AMOTION_EVENT_AXIS_*} constants instead. + */ +enum { + /** x */ + AINPUT_MOTION_RANGE_X = AMOTION_EVENT_AXIS_X, + /** y */ + AINPUT_MOTION_RANGE_Y = AMOTION_EVENT_AXIS_Y, + /** pressure */ + AINPUT_MOTION_RANGE_PRESSURE = AMOTION_EVENT_AXIS_PRESSURE, + /** size */ + AINPUT_MOTION_RANGE_SIZE = AMOTION_EVENT_AXIS_SIZE, + /** touch major */ + AINPUT_MOTION_RANGE_TOUCH_MAJOR = AMOTION_EVENT_AXIS_TOUCH_MAJOR, + /** touch minor */ + AINPUT_MOTION_RANGE_TOUCH_MINOR = AMOTION_EVENT_AXIS_TOUCH_MINOR, + /** tool major */ + AINPUT_MOTION_RANGE_TOOL_MAJOR = AMOTION_EVENT_AXIS_TOOL_MAJOR, + /** tool minor */ + AINPUT_MOTION_RANGE_TOOL_MINOR = AMOTION_EVENT_AXIS_TOOL_MINOR, + /** orientation */ + AINPUT_MOTION_RANGE_ORIENTATION = AMOTION_EVENT_AXIS_ORIENTATION, +}; + + +/** + * Input event accessors. + * + * Note that most functions can only be used on input events that are of a given type. + * Calling these functions on input events of other types will yield undefined behavior. + */ + +/*** Accessors for all input events. ***/ + +/** Get the input event type. */ +int32_t AInputEvent_getType(const AInputEvent* event); + +/** Get the id for the device that an input event came from. + * + * Input events can be generated by multiple different input devices. + * Use the input device id to obtain information about the input + * device that was responsible for generating a particular event. + * + * An input device id of 0 indicates that the event didn't come from a physical device; + * other numbers are arbitrary and you shouldn't depend on the values. + * Use the provided input device query API to obtain information about input devices. + */ +int32_t AInputEvent_getDeviceId(const AInputEvent* event); + +/** Get the input event source. */ +int32_t AInputEvent_getSource(const AInputEvent* event); + +/*** Accessors for key events only. ***/ + +/** Get the key event action. */ +int32_t AKeyEvent_getAction(const AInputEvent* key_event); + +/** Get the key event flags. */ +int32_t AKeyEvent_getFlags(const AInputEvent* key_event); + +/** + * Get the key code of the key event. + * This is the physical key that was pressed, not the Unicode character. + */ +int32_t AKeyEvent_getKeyCode(const AInputEvent* key_event); + +/** + * Get the hardware key id of this key event. + * These values are not reliable and vary from device to device. + */ +int32_t AKeyEvent_getScanCode(const AInputEvent* key_event); + +/** Get the meta key state. */ +int32_t AKeyEvent_getMetaState(const AInputEvent* key_event); + +/** + * Get the repeat count of the event. + * For both key up an key down events, this is the number of times the key has + * repeated with the first down starting at 0 and counting up from there. For + * multiple key events, this is the number of down/up pairs that have occurred. + */ +int32_t AKeyEvent_getRepeatCount(const AInputEvent* key_event); + +/** + * Get the time of the most recent key down event, in the + * java.lang.System.nanoTime() time base. If this is a down event, + * this will be the same as eventTime. + * Note that when chording keys, this value is the down time of the most recently + * pressed key, which may not be the same physical key of this event. + */ +int64_t AKeyEvent_getDownTime(const AInputEvent* key_event); + +/** + * Get the time this event occurred, in the + * java.lang.System.nanoTime() time base. + */ +int64_t AKeyEvent_getEventTime(const AInputEvent* key_event); + +/*** Accessors for motion events only. ***/ + +/** Get the combined motion event action code and pointer index. */ +int32_t AMotionEvent_getAction(const AInputEvent* motion_event); + +/** Get the motion event flags. */ +int32_t AMotionEvent_getFlags(const AInputEvent* motion_event); + +/** + * Get the state of any meta / modifier keys that were in effect when the + * event was generated. + */ +int32_t AMotionEvent_getMetaState(const AInputEvent* motion_event); + +/** Get the button state of all buttons that are pressed. */ +int32_t AMotionEvent_getButtonState(const AInputEvent* motion_event); + +/** + * Get a bitfield indicating which edges, if any, were touched by this motion event. + * For touch events, clients can use this to determine if the user's finger was + * touching the edge of the display. + */ +int32_t AMotionEvent_getEdgeFlags(const AInputEvent* motion_event); + +/** + * Get the time when the user originally pressed down to start a stream of + * position events, in the java.lang.System.nanoTime() time base. + */ +int64_t AMotionEvent_getDownTime(const AInputEvent* motion_event); + +/** + * Get the time when this specific event was generated, + * in the java.lang.System.nanoTime() time base. + */ +int64_t AMotionEvent_getEventTime(const AInputEvent* motion_event); + +/** + * Get the X coordinate offset. + * For touch events on the screen, this is the delta that was added to the raw + * screen coordinates to adjust for the absolute position of the containing windows + * and views. + */ +float AMotionEvent_getXOffset(const AInputEvent* motion_event); + +/** + * Get the Y coordinate offset. + * For touch events on the screen, this is the delta that was added to the raw + * screen coordinates to adjust for the absolute position of the containing windows + * and views. + */ +float AMotionEvent_getYOffset(const AInputEvent* motion_event); + +/** + * Get the precision of the X coordinates being reported. + * You can multiply this number with an X coordinate sample to find the + * actual hardware value of the X coordinate. + */ +float AMotionEvent_getXPrecision(const AInputEvent* motion_event); + +/** + * Get the precision of the Y coordinates being reported. + * You can multiply this number with a Y coordinate sample to find the + * actual hardware value of the Y coordinate. + */ +float AMotionEvent_getYPrecision(const AInputEvent* motion_event); + +/** + * Get the number of pointers of data contained in this event. + * Always >= 1. + */ +size_t AMotionEvent_getPointerCount(const AInputEvent* motion_event); + +/** + * Get the pointer identifier associated with a particular pointer + * data index in this event. The identifier tells you the actual pointer + * number associated with the data, accounting for individual pointers + * going up and down since the start of the current gesture. + */ +int32_t AMotionEvent_getPointerId(const AInputEvent* motion_event, size_t pointer_index); + +/** + * Get the tool type of a pointer for the given pointer index. + * The tool type indicates the type of tool used to make contact such as a + * finger or stylus, if known. + */ +int32_t AMotionEvent_getToolType(const AInputEvent* motion_event, size_t pointer_index); + +/** + * Get the original raw X coordinate of this event. + * For touch events on the screen, this is the original location of the event + * on the screen, before it had been adjusted for the containing window + * and views. + */ +float AMotionEvent_getRawX(const AInputEvent* motion_event, size_t pointer_index); + +/** + * Get the original raw X coordinate of this event. + * For touch events on the screen, this is the original location of the event + * on the screen, before it had been adjusted for the containing window + * and views. + */ +float AMotionEvent_getRawY(const AInputEvent* motion_event, size_t pointer_index); + +/** + * Get the current X coordinate of this event for the given pointer index. + * Whole numbers are pixels; the value may have a fraction for input devices + * that are sub-pixel precise. + */ +float AMotionEvent_getX(const AInputEvent* motion_event, size_t pointer_index); + +/** + * Get the current Y coordinate of this event for the given pointer index. + * Whole numbers are pixels; the value may have a fraction for input devices + * that are sub-pixel precise. + */ +float AMotionEvent_getY(const AInputEvent* motion_event, size_t pointer_index); + +/** + * Get the current pressure of this event for the given pointer index. + * The pressure generally ranges from 0 (no pressure at all) to 1 (normal pressure), + * although values higher than 1 may be generated depending on the calibration of + * the input device. + */ +float AMotionEvent_getPressure(const AInputEvent* motion_event, size_t pointer_index); + +/** + * Get the current scaled value of the approximate size for the given pointer index. + * This represents some approximation of the area of the screen being + * pressed; the actual value in pixels corresponding to the + * touch is normalized with the device specific range of values + * and scaled to a value between 0 and 1. The value of size can be used to + * determine fat touch events. + */ +float AMotionEvent_getSize(const AInputEvent* motion_event, size_t pointer_index); + +/** + * Get the current length of the major axis of an ellipse that describes the touch area + * at the point of contact for the given pointer index. + */ +float AMotionEvent_getTouchMajor(const AInputEvent* motion_event, size_t pointer_index); + +/** + * Get the current length of the minor axis of an ellipse that describes the touch area + * at the point of contact for the given pointer index. + */ +float AMotionEvent_getTouchMinor(const AInputEvent* motion_event, size_t pointer_index); + +/** + * Get the current length of the major axis of an ellipse that describes the size + * of the approaching tool for the given pointer index. + * The tool area represents the estimated size of the finger or pen that is + * touching the device independent of its actual touch area at the point of contact. + */ +float AMotionEvent_getToolMajor(const AInputEvent* motion_event, size_t pointer_index); + +/** + * Get the current length of the minor axis of an ellipse that describes the size + * of the approaching tool for the given pointer index. + * The tool area represents the estimated size of the finger or pen that is + * touching the device independent of its actual touch area at the point of contact. + */ +float AMotionEvent_getToolMinor(const AInputEvent* motion_event, size_t pointer_index); + +/** + * Get the current orientation of the touch area and tool area in radians clockwise from + * vertical for the given pointer index. + * An angle of 0 degrees indicates that the major axis of contact is oriented + * upwards, is perfectly circular or is of unknown orientation. A positive angle + * indicates that the major axis of contact is oriented to the right. A negative angle + * indicates that the major axis of contact is oriented to the left. + * The full range is from -PI/2 radians (finger pointing fully left) to PI/2 radians + * (finger pointing fully right). + */ +float AMotionEvent_getOrientation(const AInputEvent* motion_event, size_t pointer_index); + +/** Get the value of the request axis for the given pointer index. */ +float AMotionEvent_getAxisValue(const AInputEvent* motion_event, + int32_t axis, size_t pointer_index); + +/** + * Get the number of historical points in this event. These are movements that + * have occurred between this event and the previous event. This only applies + * to AMOTION_EVENT_ACTION_MOVE events -- all other actions will have a size of 0. + * Historical samples are indexed from oldest to newest. + */ +size_t AMotionEvent_getHistorySize(const AInputEvent* motion_event); + +/** + * Get the time that a historical movement occurred between this event and + * the previous event, in the java.lang.System.nanoTime() time base. + */ +int64_t AMotionEvent_getHistoricalEventTime(const AInputEvent* motion_event, + size_t history_index); + +/** + * Get the historical raw X coordinate of this event for the given pointer index that + * occurred between this event and the previous motion event. + * For touch events on the screen, this is the original location of the event + * on the screen, before it had been adjusted for the containing window + * and views. + * Whole numbers are pixels; the value may have a fraction for input devices + * that are sub-pixel precise. + */ +float AMotionEvent_getHistoricalRawX(const AInputEvent* motion_event, size_t pointer_index, + size_t history_index); + +/** + * Get the historical raw Y coordinate of this event for the given pointer index that + * occurred between this event and the previous motion event. + * For touch events on the screen, this is the original location of the event + * on the screen, before it had been adjusted for the containing window + * and views. + * Whole numbers are pixels; the value may have a fraction for input devices + * that are sub-pixel precise. + */ +float AMotionEvent_getHistoricalRawY(const AInputEvent* motion_event, size_t pointer_index, + size_t history_index); + +/** + * Get the historical X coordinate of this event for the given pointer index that + * occurred between this event and the previous motion event. + * Whole numbers are pixels; the value may have a fraction for input devices + * that are sub-pixel precise. + */ +float AMotionEvent_getHistoricalX(const AInputEvent* motion_event, size_t pointer_index, + size_t history_index); + +/** + * Get the historical Y coordinate of this event for the given pointer index that + * occurred between this event and the previous motion event. + * Whole numbers are pixels; the value may have a fraction for input devices + * that are sub-pixel precise. + */ +float AMotionEvent_getHistoricalY(const AInputEvent* motion_event, size_t pointer_index, + size_t history_index); + +/** + * Get the historical pressure of this event for the given pointer index that + * occurred between this event and the previous motion event. + * The pressure generally ranges from 0 (no pressure at all) to 1 (normal pressure), + * although values higher than 1 may be generated depending on the calibration of + * the input device. + */ +float AMotionEvent_getHistoricalPressure(const AInputEvent* motion_event, size_t pointer_index, + size_t history_index); + +/** + * Get the current scaled value of the approximate size for the given pointer index that + * occurred between this event and the previous motion event. + * This represents some approximation of the area of the screen being + * pressed; the actual value in pixels corresponding to the + * touch is normalized with the device specific range of values + * and scaled to a value between 0 and 1. The value of size can be used to + * determine fat touch events. + */ +float AMotionEvent_getHistoricalSize(const AInputEvent* motion_event, size_t pointer_index, + size_t history_index); + +/** + * Get the historical length of the major axis of an ellipse that describes the touch area + * at the point of contact for the given pointer index that + * occurred between this event and the previous motion event. + */ +float AMotionEvent_getHistoricalTouchMajor(const AInputEvent* motion_event, size_t pointer_index, + size_t history_index); + +/** + * Get the historical length of the minor axis of an ellipse that describes the touch area + * at the point of contact for the given pointer index that + * occurred between this event and the previous motion event. + */ +float AMotionEvent_getHistoricalTouchMinor(const AInputEvent* motion_event, size_t pointer_index, + size_t history_index); + +/** + * Get the historical length of the major axis of an ellipse that describes the size + * of the approaching tool for the given pointer index that + * occurred between this event and the previous motion event. + * The tool area represents the estimated size of the finger or pen that is + * touching the device independent of its actual touch area at the point of contact. + */ +float AMotionEvent_getHistoricalToolMajor(const AInputEvent* motion_event, size_t pointer_index, + size_t history_index); + +/** + * Get the historical length of the minor axis of an ellipse that describes the size + * of the approaching tool for the given pointer index that + * occurred between this event and the previous motion event. + * The tool area represents the estimated size of the finger or pen that is + * touching the device independent of its actual touch area at the point of contact. + */ +float AMotionEvent_getHistoricalToolMinor(const AInputEvent* motion_event, size_t pointer_index, + size_t history_index); + +/** + * Get the historical orientation of the touch area and tool area in radians clockwise from + * vertical for the given pointer index that + * occurred between this event and the previous motion event. + * An angle of 0 degrees indicates that the major axis of contact is oriented + * upwards, is perfectly circular or is of unknown orientation. A positive angle + * indicates that the major axis of contact is oriented to the right. A negative angle + * indicates that the major axis of contact is oriented to the left. + * The full range is from -PI/2 radians (finger pointing fully left) to PI/2 radians + * (finger pointing fully right). + */ +float AMotionEvent_getHistoricalOrientation(const AInputEvent* motion_event, size_t pointer_index, + size_t history_index); + +/** + * Get the historical value of the request axis for the given pointer index + * that occurred between this event and the previous motion event. + */ +float AMotionEvent_getHistoricalAxisValue(const AInputEvent* motion_event, + int32_t axis, size_t pointer_index, size_t history_index); + + +struct AInputQueue; +/** + * Input queue + * + * An input queue is the facility through which you retrieve input + * events. + */ +typedef struct AInputQueue AInputQueue; + +/** + * Add this input queue to a looper for processing. See + * ALooper_addFd() for information on the ident, callback, and data params. + */ +void AInputQueue_attachLooper(AInputQueue* queue, ALooper* looper, + int ident, ALooper_callbackFunc callback, void* data); + +/** + * Remove the input queue from the looper it is currently attached to. + */ +void AInputQueue_detachLooper(AInputQueue* queue); + +/** + * Returns true if there are one or more events available in the + * input queue. Returns 1 if the queue has events; 0 if + * it does not have events; and a negative value if there is an error. + */ +int32_t AInputQueue_hasEvents(AInputQueue* queue); + +/** + * Returns the next available event from the queue. Returns a negative + * value if no events are available or an error has occurred. + */ +int32_t AInputQueue_getEvent(AInputQueue* queue, AInputEvent** outEvent); + +/** + * Sends the key for standard pre-dispatching -- that is, possibly deliver + * it to the current IME to be consumed before the app. Returns 0 if it + * was not pre-dispatched, meaning you can process it right now. If non-zero + * is returned, you must abandon the current event processing and allow the + * event to appear again in the event queue (if it does not get consumed during + * pre-dispatching). + */ +int32_t AInputQueue_preDispatchEvent(AInputQueue* queue, AInputEvent* event); + +/** + * Report that dispatching has finished with the given event. + * This must be called after receiving an event with AInputQueue_get_event(). + */ +void AInputQueue_finishEvent(AInputQueue* queue, AInputEvent* event, int handled); + +#ifdef __cplusplus +} +#endif + +#endif // _ANDROID_INPUT_H + +/** @} */ diff --git a/phonelibs/android_frameworks_native/include/android/keycodes.h b/phonelibs/android_frameworks_native/include/android/keycodes.h new file mode 100644 index 0000000000..421abe5477 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/android/keycodes.h @@ -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 + +#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 + +/** @} */ diff --git a/phonelibs/android_frameworks_native/include/android/looper.h b/phonelibs/android_frameworks_native/include/android/looper.h new file mode 100644 index 0000000000..718f703048 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/android/looper.h @@ -0,0 +1,269 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @addtogroup Looper + * @{ + */ + +/** + * @file looper.h + */ + +#ifndef ANDROID_LOOPER_H +#define ANDROID_LOOPER_H + +#ifdef __cplusplus +extern "C" { +#endif + +struct ALooper; +/** + * ALooper + * + * A looper is the state tracking an event loop for a thread. + * Loopers do not define event structures or other such things; rather + * they are a lower-level facility to attach one or more discrete objects + * listening for an event. An "event" here is simply data available on + * a file descriptor: each attached object has an associated file descriptor, + * and waiting for "events" means (internally) polling on all of these file + * descriptors until one or more of them have data available. + * + * A thread can have only one ALooper associated with it. + */ +typedef struct ALooper ALooper; + +/** + * Returns the looper associated with the calling thread, or NULL if + * there is not one. + */ +ALooper* ALooper_forThread(); + +/** Option for for ALooper_prepare(). */ +enum { + /** + * This looper will accept calls to ALooper_addFd() that do not + * have a callback (that is provide NULL for the callback). In + * this case the caller of ALooper_pollOnce() or ALooper_pollAll() + * MUST check the return from these functions to discover when + * data is available on such fds and process it. + */ + ALOOPER_PREPARE_ALLOW_NON_CALLBACKS = 1<<0 +}; + +/** + * Prepares a looper associated with the calling thread, and returns it. + * If the thread already has a looper, it is returned. Otherwise, a new + * one is created, associated with the thread, and returned. + * + * The opts may be ALOOPER_PREPARE_ALLOW_NON_CALLBACKS or 0. + */ +ALooper* ALooper_prepare(int opts); + +/** Result from ALooper_pollOnce() and ALooper_pollAll(). */ +enum { + /** + * The poll was awoken using wake() before the timeout expired + * and no callbacks were executed and no other file descriptors were ready. + */ + ALOOPER_POLL_WAKE = -1, + + /** + * Result from ALooper_pollOnce() and ALooper_pollAll(): + * One or more callbacks were executed. + */ + ALOOPER_POLL_CALLBACK = -2, + + /** + * Result from ALooper_pollOnce() and ALooper_pollAll(): + * The timeout expired. + */ + ALOOPER_POLL_TIMEOUT = -3, + + /** + * Result from ALooper_pollOnce() and ALooper_pollAll(): + * An error occurred. + */ + ALOOPER_POLL_ERROR = -4, +}; + +/** + * Acquire a reference on the given ALooper object. This prevents the object + * from being deleted until the reference is removed. This is only needed + * to safely hand an ALooper from one thread to another. + */ +void ALooper_acquire(ALooper* looper); + +/** + * Remove a reference that was previously acquired with ALooper_acquire(). + */ +void ALooper_release(ALooper* looper); + +/** + * Flags for file descriptor events that a looper can monitor. + * + * These flag bits can be combined to monitor multiple events at once. + */ +enum { + /** + * The file descriptor is available for read operations. + */ + ALOOPER_EVENT_INPUT = 1 << 0, + + /** + * The file descriptor is available for write operations. + */ + ALOOPER_EVENT_OUTPUT = 1 << 1, + + /** + * The file descriptor has encountered an error condition. + * + * The looper always sends notifications about errors; it is not necessary + * to specify this event flag in the requested event set. + */ + ALOOPER_EVENT_ERROR = 1 << 2, + + /** + * The file descriptor was hung up. + * For example, indicates that the remote end of a pipe or socket was closed. + * + * The looper always sends notifications about hangups; it is not necessary + * to specify this event flag in the requested event set. + */ + ALOOPER_EVENT_HANGUP = 1 << 3, + + /** + * The file descriptor is invalid. + * For example, the file descriptor was closed prematurely. + * + * The looper always sends notifications about invalid file descriptors; it is not necessary + * to specify this event flag in the requested event set. + */ + ALOOPER_EVENT_INVALID = 1 << 4, +}; + +/** + * For callback-based event loops, this is the prototype of the function + * that is called when a file descriptor event occurs. + * It is given the file descriptor it is associated with, + * a bitmask of the poll events that were triggered (typically ALOOPER_EVENT_INPUT), + * and the data pointer that was originally supplied. + * + * Implementations should return 1 to continue receiving callbacks, or 0 + * to have this file descriptor and callback unregistered from the looper. + */ +typedef int (*ALooper_callbackFunc)(int fd, int events, void* data); + +/** + * Waits for events to be available, with optional timeout in milliseconds. + * Invokes callbacks for all file descriptors on which an event occurred. + * + * If the timeout is zero, returns immediately without blocking. + * If the timeout is negative, waits indefinitely until an event appears. + * + * Returns ALOOPER_POLL_WAKE if the poll was awoken using wake() before + * the timeout expired and no callbacks were invoked and no other file + * descriptors were ready. + * + * Returns ALOOPER_POLL_CALLBACK if one or more callbacks were invoked. + * + * Returns ALOOPER_POLL_TIMEOUT if there was no data before the given + * timeout expired. + * + * Returns ALOOPER_POLL_ERROR if an error occurred. + * + * Returns a value >= 0 containing an identifier (the same identifier + * `ident` passed to ALooper_addFd()) if its file descriptor has data + * and it has no callback function (requiring the caller here to + * handle it). In this (and only this) case outFd, outEvents and + * outData will contain the poll events and data associated with the + * fd, otherwise they will be set to NULL. + * + * This method does not return until it has finished invoking the appropriate callbacks + * for all file descriptors that were signalled. + */ +int ALooper_pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData); + +/** + * Like ALooper_pollOnce(), but performs all pending callbacks until all + * data has been consumed or a file descriptor is available with no callback. + * This function will never return ALOOPER_POLL_CALLBACK. + */ +int ALooper_pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData); + +/** + * Wakes the poll asynchronously. + * + * This method can be called on any thread. + * This method returns immediately. + */ +void ALooper_wake(ALooper* looper); + +/** + * Adds a new file descriptor to be polled by the looper. + * If the same file descriptor was previously added, it is replaced. + * + * "fd" is the file descriptor to be added. + * "ident" is an identifier for this event, which is returned from ALooper_pollOnce(). + * The identifier must be >= 0, or ALOOPER_POLL_CALLBACK if providing a non-NULL callback. + * "events" are the poll events to wake up on. Typically this is ALOOPER_EVENT_INPUT. + * "callback" is the function to call when there is an event on the file descriptor. + * "data" is a private data pointer to supply to the callback. + * + * There are two main uses of this function: + * + * (1) If "callback" is non-NULL, then this function will be called when there is + * data on the file descriptor. It should execute any events it has pending, + * appropriately reading from the file descriptor. The 'ident' is ignored in this case. + * + * (2) If "callback" is NULL, the 'ident' will be returned by ALooper_pollOnce + * when its file descriptor has data available, requiring the caller to take + * care of processing it. + * + * Returns 1 if the file descriptor was added or -1 if an error occurred. + * + * This method can be called on any thread. + * This method may block briefly if it needs to wake the poll. + */ +int ALooper_addFd(ALooper* looper, int fd, int ident, int events, + ALooper_callbackFunc callback, void* data); + +/** + * Removes a previously added file descriptor from the looper. + * + * When this method returns, it is safe to close the file descriptor since the looper + * will no longer have a reference to it. However, it is possible for the callback to + * already be running or for it to run one last time if the file descriptor was already + * signalled. Calling code is responsible for ensuring that this case is safely handled. + * For example, if the callback takes care of removing itself during its own execution either + * by returning 0 or by calling this method, then it can be guaranteed to not be invoked + * again at any later time unless registered anew. + * + * Returns 1 if the file descriptor was removed, 0 if none was previously registered + * or -1 if an error occurred. + * + * This method can be called on any thread. + * This method may block briefly if it needs to wake the poll. + */ +int ALooper_removeFd(ALooper* looper, int fd); + +#ifdef __cplusplus +}; +#endif + +#endif // ANDROID_LOOPER_H + +/** @} */ diff --git a/phonelibs/android_frameworks_native/include/android/multinetwork.h b/phonelibs/android_frameworks_native/include/android/multinetwork.h new file mode 100644 index 0000000000..6c718c9037 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/android/multinetwork.h @@ -0,0 +1,109 @@ +/* + * Copyright (C) 2015 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_MULTINETWORK_H +#define ANDROID_MULTINETWORK_H + +#include +#include +#include + +__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(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 diff --git a/phonelibs/android_frameworks_native/include/android/native_activity.h b/phonelibs/android_frameworks_native/include/android/native_activity.h new file mode 100644 index 0000000000..d3d99cf7a9 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/android/native_activity.h @@ -0,0 +1,340 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @addtogroup NativeActivity Native Activity + * @{ + */ + +/** + * @file native_activity.h + */ + +#ifndef ANDROID_NATIVE_ACTIVITY_H +#define ANDROID_NATIVE_ACTIVITY_H + +#include +#include + +#include + +#include +#include +#include + +#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 + +/** @} */ diff --git a/phonelibs/android_frameworks_native/include/android/native_window.h b/phonelibs/android_frameworks_native/include/android/native_window.h new file mode 100644 index 0000000000..cf07f1afad --- /dev/null +++ b/phonelibs/android_frameworks_native/include/android/native_window.h @@ -0,0 +1,150 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @addtogroup NativeActivity Native Activity + * @{ + */ + +/** + * @file native_window.h + */ + +#ifndef ANDROID_NATIVE_WINDOW_H +#define ANDROID_NATIVE_WINDOW_H + +#include + +#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 + +/** @} */ diff --git a/phonelibs/android_frameworks_native/include/android/native_window_jni.h b/phonelibs/android_frameworks_native/include/android/native_window_jni.h new file mode 100644 index 0000000000..60a36c3f27 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/android/native_window_jni.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @addtogroup NativeActivity Native Activity + * @{ + */ + +/** + * @file native_window_jni.h + */ + +#ifndef ANDROID_NATIVE_WINDOW_JNI_H +#define ANDROID_NATIVE_WINDOW_JNI_H + +#include + +#include + +#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 + +/** @} */ diff --git a/phonelibs/android_frameworks_native/include/android/obb.h b/phonelibs/android_frameworks_native/include/android/obb.h new file mode 100644 index 0000000000..4c6d9d7bad --- /dev/null +++ b/phonelibs/android_frameworks_native/include/android/obb.h @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @addtogroup Storage + * @{ + */ + +/** + * @file obb.h + */ + +#ifndef ANDROID_OBB_H +#define ANDROID_OBB_H + +#include + +#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 + +/** @} */ diff --git a/phonelibs/android_frameworks_native/include/android/rect.h b/phonelibs/android_frameworks_native/include/android/rect.h new file mode 100644 index 0000000000..80741c0442 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/android/rect.h @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @addtogroup NativeActivity Native Activity + * @{ + */ + +/** + * @file rect.h + */ + +#ifndef ANDROID_RECT_H +#define ANDROID_RECT_H + +#include + +#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 + +/** @} */ diff --git a/phonelibs/android_frameworks_native/include/android/sensor.h b/phonelibs/android_frameworks_native/include/android/sensor.h new file mode 100644 index 0000000000..73928ea76f --- /dev/null +++ b/phonelibs/android_frameworks_native/include/android/sensor.h @@ -0,0 +1,475 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @addtogroup Sensor + * @{ + */ + +/** + * @file sensor.h + */ + +#ifndef ANDROID_SENSOR_H +#define ANDROID_SENSOR_H + +/****************************************************************** + * + * IMPORTANT NOTICE: + * + * This file is part of Android's set of stable system headers + * exposed by the Android NDK (Native Development Kit). + * + * Third-party source AND binary code relies on the definitions + * here to be FROZEN ON ALL UPCOMING PLATFORM RELEASES. + * + * - DO NOT MODIFY ENUMS (EXCEPT IF YOU ADD NEW 32-BIT VALUES) + * - DO NOT MODIFY CONSTANTS OR FUNCTIONAL MACROS + * - DO NOT CHANGE THE SIGNATURE OF FUNCTIONS IN ANY WAY + * - DO NOT CHANGE THE LAYOUT OR SIZE OF STRUCTURES + */ + +/** + * Structures and functions to receive and process sensor events in + * native code. + * + */ + +#include + +#include + +#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 + +/** @} */ diff --git a/phonelibs/android_frameworks_native/include/android/storage_manager.h b/phonelibs/android_frameworks_native/include/android/storage_manager.h new file mode 100644 index 0000000000..7f2ee08d62 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/android/storage_manager.h @@ -0,0 +1,154 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @addtogroup Storage + * @{ + */ + +/** + * @file storage_manager.h + */ + +#ifndef ANDROID_STORAGE_MANAGER_H +#define ANDROID_STORAGE_MANAGER_H + +#include + +#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 + +/** @} */ diff --git a/phonelibs/android_frameworks_native/include/android/trace.h b/phonelibs/android_frameworks_native/include/android/trace.h new file mode 100644 index 0000000000..e42e334102 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/android/trace.h @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2015 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef ANDROID_NATIVE_TRACE_H +#define ANDROID_NATIVE_TRACE_H + +#include + +#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 diff --git a/phonelibs/android_frameworks_native/include/android/window.h b/phonelibs/android_frameworks_native/include/android/window.h new file mode 100644 index 0000000000..436bf3a830 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/android/window.h @@ -0,0 +1,224 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @addtogroup NativeActivity Native Activity + * @{ + */ + +/** + * @file window.h + */ + +#ifndef ANDROID_WINDOW_H +#define ANDROID_WINDOW_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Window flags, as per the Java API at android.view.WindowManager.LayoutParams. + */ +enum { + /** + * As long as this window is visible to the user, allow the lock + * screen to activate while the screen is on. This can be used + * independently, or in combination with {@link + * AWINDOW_FLAG_KEEP_SCREEN_ON} and/or {@link + * AWINDOW_FLAG_SHOW_WHEN_LOCKED} + */ + AWINDOW_FLAG_ALLOW_LOCK_WHILE_SCREEN_ON = 0x00000001, + /** Everything behind this window will be dimmed. */ + AWINDOW_FLAG_DIM_BEHIND = 0x00000002, + /** + * Blur everything behind this window. + * @deprecated Blurring is no longer supported. + */ + AWINDOW_FLAG_BLUR_BEHIND = 0x00000004, + /** + * This window won't ever get key input focus, so the + * user can not send key or other button events to it. Those will + * instead go to whatever focusable window is behind it. This flag + * will also enable {@link AWINDOW_FLAG_NOT_TOUCH_MODAL} whether or not that + * is explicitly set. + * + * Setting this flag also implies that the window will not need to + * interact with + * a soft input method, so it will be Z-ordered and positioned + * independently of any active input method (typically this means it + * gets Z-ordered on top of the input method, so it can use the full + * screen for its content and cover the input method if needed. You + * can use {@link AWINDOW_FLAG_ALT_FOCUSABLE_IM} to modify this behavior. + */ + AWINDOW_FLAG_NOT_FOCUSABLE = 0x00000008, + /** this window can never receive touch events. */ + AWINDOW_FLAG_NOT_TOUCHABLE = 0x00000010, + /** + * Even when this window is focusable (its + * {@link AWINDOW_FLAG_NOT_FOCUSABLE} is not set), allow any pointer events + * outside of the window to be sent to the windows behind it. Otherwise + * it will consume all pointer events itself, regardless of whether they + * are inside of the window. + */ + AWINDOW_FLAG_NOT_TOUCH_MODAL = 0x00000020, + /** + * When set, if the device is asleep when the touch + * screen is pressed, you will receive this first touch event. Usually + * the first touch event is consumed by the system since the user can + * not see what they are pressing on. + * + * @deprecated This flag has no effect. + */ + AWINDOW_FLAG_TOUCHABLE_WHEN_WAKING = 0x00000040, + /** + * As long as this window is visible to the user, keep + * the device's screen turned on and bright. + */ + AWINDOW_FLAG_KEEP_SCREEN_ON = 0x00000080, + /** + * Place the window within the entire screen, ignoring + * decorations around the border (such as the status bar). The + * window must correctly position its contents to take the screen + * decoration into account. + */ + AWINDOW_FLAG_LAYOUT_IN_SCREEN = 0x00000100, + /** allow window to extend outside of the screen. */ + AWINDOW_FLAG_LAYOUT_NO_LIMITS = 0x00000200, + /** + * Hide all screen decorations (such as the status + * bar) while this window is displayed. This allows the window to + * use the entire display space for itself -- the status bar will + * be hidden when an app window with this flag set is on the top + * layer. A fullscreen window will ignore a value of {@link + * AWINDOW_SOFT_INPUT_ADJUST_RESIZE}; the window will stay + * fullscreen and will not resize. + */ + AWINDOW_FLAG_FULLSCREEN = 0x00000400, + /** + * Override {@link AWINDOW_FLAG_FULLSCREEN} and force the + * screen decorations (such as the status bar) to be shown. + */ + AWINDOW_FLAG_FORCE_NOT_FULLSCREEN = 0x00000800, + /** + * Turn on dithering when compositing this window to + * the screen. + * @deprecated This flag is no longer used. + */ + AWINDOW_FLAG_DITHER = 0x00001000, + /** + * Treat the content of the window as secure, preventing + * it from appearing in screenshots or from being viewed on non-secure + * displays. + */ + AWINDOW_FLAG_SECURE = 0x00002000, + /** + * A special mode where the layout parameters are used + * to perform scaling of the surface when it is composited to the + * screen. + */ + AWINDOW_FLAG_SCALED = 0x00004000, + /** + * Intended for windows that will often be used when the user is + * holding the screen against their face, it will aggressively + * filter the event stream to prevent unintended presses in this + * situation that may not be desired for a particular window, when + * such an event stream is detected, the application will receive + * a {@link AMOTION_EVENT_ACTION_CANCEL} to indicate this so + * applications can handle this accordingly by taking no action on + * the event until the finger is released. + */ + AWINDOW_FLAG_IGNORE_CHEEK_PRESSES = 0x00008000, + /** + * A special option only for use in combination with + * {@link AWINDOW_FLAG_LAYOUT_IN_SCREEN}. When requesting layout in the + * screen your window may appear on top of or behind screen decorations + * such as the status bar. By also including this flag, the window + * manager will report the inset rectangle needed to ensure your + * content is not covered by screen decorations. + */ + AWINDOW_FLAG_LAYOUT_INSET_DECOR = 0x00010000, + /** + * Invert the state of {@link AWINDOW_FLAG_NOT_FOCUSABLE} with + * respect to how this window interacts with the current method. + * That is, if FLAG_NOT_FOCUSABLE is set and this flag is set, + * then the window will behave as if it needs to interact with the + * input method and thus be placed behind/away from it; if {@link + * AWINDOW_FLAG_NOT_FOCUSABLE} is not set and this flag is set, + * then the window will behave as if it doesn't need to interact + * with the input method and can be placed to use more space and + * cover the input method. + */ + AWINDOW_FLAG_ALT_FOCUSABLE_IM = 0x00020000, + /** + * If you have set {@link AWINDOW_FLAG_NOT_TOUCH_MODAL}, you + * can set this flag to receive a single special MotionEvent with + * the action + * {@link AMOTION_EVENT_ACTION_OUTSIDE} for + * touches that occur outside of your window. Note that you will not + * receive the full down/move/up gesture, only the location of the + * first down as an {@link AMOTION_EVENT_ACTION_OUTSIDE}. + */ + AWINDOW_FLAG_WATCH_OUTSIDE_TOUCH = 0x00040000, + /** + * Special flag to let windows be shown when the screen + * is locked. This will let application windows take precedence over + * key guard or any other lock screens. Can be used with + * {@link AWINDOW_FLAG_KEEP_SCREEN_ON} to turn screen on and display windows + * directly before showing the key guard window. Can be used with + * {@link AWINDOW_FLAG_DISMISS_KEYGUARD} to automatically fully dismisss + * non-secure keyguards. This flag only applies to the top-most + * full-screen window. + */ + AWINDOW_FLAG_SHOW_WHEN_LOCKED = 0x00080000, + /** + * Ask that the system wallpaper be shown behind + * your window. The window surface must be translucent to be able + * to actually see the wallpaper behind it; this flag just ensures + * that the wallpaper surface will be there if this window actually + * has translucent regions. + */ + AWINDOW_FLAG_SHOW_WALLPAPER = 0x00100000, + /** + * When set as a window is being added or made + * visible, once the window has been shown then the system will + * poke the power manager's user activity (as if the user had woken + * up the device) to turn the screen on. + */ + AWINDOW_FLAG_TURN_SCREEN_ON = 0x00200000, + /** + * When set the window will cause the keyguard to + * be dismissed, only if it is not a secure lock keyguard. Because such + * a keyguard is not needed for security, it will never re-appear if + * the user navigates to another window (in contrast to + * {@link AWINDOW_FLAG_SHOW_WHEN_LOCKED}, which will only temporarily + * hide both secure and non-secure keyguards but ensure they reappear + * when the user moves to another UI that doesn't hide them). + * If the keyguard is currently active and is secure (requires an + * unlock pattern) than the user will still need to confirm it before + * seeing this window, unless {@link AWINDOW_FLAG_SHOW_WHEN_LOCKED} has + * also been set. + */ + AWINDOW_FLAG_DISMISS_KEYGUARD = 0x00400000, +}; + +#ifdef __cplusplus +}; +#endif + +#endif // ANDROID_WINDOW_H + +/** @} */ diff --git a/phonelibs/android_frameworks_native/include/batteryservice/BatteryService.h b/phonelibs/android_frameworks_native/include/batteryservice/BatteryService.h new file mode 100644 index 0000000000..3e6bfb8204 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/batteryservice/BatteryService.h @@ -0,0 +1,93 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * Copyright (C) 2015 The CyanogenMod Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_BATTERYSERVICE_H +#define ANDROID_BATTERYSERVICE_H + +#include +#include +#include +#include + +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 diff --git a/phonelibs/android_frameworks_native/include/batteryservice/IBatteryPropertiesListener.h b/phonelibs/android_frameworks_native/include/batteryservice/IBatteryPropertiesListener.h new file mode 100644 index 0000000000..b02d8e9073 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/batteryservice/IBatteryPropertiesListener.h @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_IBATTERYPROPERTIESLISTENER_H +#define ANDROID_IBATTERYPROPERTIESLISTENER_H + +#include +#include + +#include + +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 diff --git a/phonelibs/android_frameworks_native/include/batteryservice/IBatteryPropertiesRegistrar.h b/phonelibs/android_frameworks_native/include/batteryservice/IBatteryPropertiesRegistrar.h new file mode 100644 index 0000000000..f6a7981d54 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/batteryservice/IBatteryPropertiesRegistrar.h @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * Copyright (C) 2015 The CyanogenMod Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_IBATTERYPROPERTIESREGISTRAR_H +#define ANDROID_IBATTERYPROPERTIESREGISTRAR_H + +#include +#include + +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& listener) = 0; + virtual void unregisterListener(const sp& 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 { +public: + virtual status_t onTransact(uint32_t code, const Parcel& data, + Parcel* reply, uint32_t flags = 0); +}; + +}; // namespace android + +#endif // ANDROID_IBATTERYPROPERTIESREGISTRAR_H diff --git a/phonelibs/android_frameworks_native/include/binder/AppOpsManager.h b/phonelibs/android_frameworks_native/include/binder/AppOpsManager.h new file mode 100644 index 0000000000..1d0e968c4a --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/AppOpsManager.h @@ -0,0 +1,130 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_APP_OPS_MANAGER_H +#define ANDROID_APP_OPS_MANAGER_H + +#include + +#include + +// --------------------------------------------------------------------------- +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& callback); + void stopWatchingMode(const sp& callback); + int32_t permissionToOpCode(const String16& permission); + +private: + Mutex mLock; + sp mService; + + sp getService(); +}; + + +}; // namespace android +// --------------------------------------------------------------------------- +#endif // ANDROID_APP_OPS_MANAGER_H diff --git a/phonelibs/android_frameworks_native/include/binder/Binder.h b/phonelibs/android_frameworks_native/include/binder/Binder.h new file mode 100644 index 0000000000..86628a03d3 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/Binder.h @@ -0,0 +1,105 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_BINDER_H +#define ANDROID_BINDER_H + +#include +#include +#include + +// --------------------------------------------------------------------------- +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& args); + + virtual status_t transact( uint32_t code, + const Parcel& data, + Parcel* reply, + uint32_t flags = 0); + + virtual status_t linkToDeath(const sp& recipient, + void* cookie = NULL, + uint32_t flags = 0); + + virtual status_t unlinkToDeath( const wp& recipient, + void* cookie = NULL, + uint32_t flags = 0, + wp* 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 + void* mReserved0; +}; + +// --------------------------------------------------------------------------- + +class BpRefBase : public virtual RefBase +{ +protected: + BpRefBase(const sp& 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 diff --git a/phonelibs/android_frameworks_native/include/binder/BinderService.h b/phonelibs/android_frameworks_native/include/binder/BinderService.h new file mode 100644 index 0000000000..ef703bda90 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/BinderService.h @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_BINDER_SERVICE_H +#define ANDROID_BINDER_SERVICE_H + +#include + +#include +#include + +#include +#include +#include +#include + +// --------------------------------------------------------------------------- +namespace android { + +template +class BinderService +{ +public: + static status_t publish(bool allowIsolated = false) { + sp 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 ps(ProcessState::self()); + ps->startThreadPool(); + ps->giveThreadPoolName(); + IPCThreadState::self()->joinThreadPool(); + } +}; + + +}; // namespace android +// --------------------------------------------------------------------------- +#endif // ANDROID_BINDER_SERVICE_H diff --git a/phonelibs/android_frameworks_native/include/binder/BpBinder.h b/phonelibs/android_frameworks_native/include/binder/BpBinder.h new file mode 100644 index 0000000000..7ef93aa390 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/BpBinder.h @@ -0,0 +1,124 @@ +/* + * Copyright (C) 2005 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_BPBINDER_H +#define ANDROID_BPBINDER_H + +#include +#include +#include + +// --------------------------------------------------------------------------- +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& args); + + virtual status_t transact( uint32_t code, + const Parcel& data, + Parcel* reply, + uint32_t flags = 0); + + virtual status_t linkToDeath(const sp& recipient, + void* cookie = NULL, + uint32_t flags = 0); + virtual status_t unlinkToDeath( const wp& recipient, + void* cookie = NULL, + uint32_t flags = 0, + wp* 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 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 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* mObituaries; + ObjectManager mObjects; + Parcel* mConstantData; + mutable String16 mDescriptorCache; +}; + +}; // namespace android + +// --------------------------------------------------------------------------- + +#endif // ANDROID_BPBINDER_H diff --git a/phonelibs/android_frameworks_native/include/binder/BufferedTextOutput.h b/phonelibs/android_frameworks_native/include/binder/BufferedTextOutput.h new file mode 100644 index 0000000000..9a7c43bb13 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/BufferedTextOutput.h @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2006 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_BUFFEREDTEXTOUTPUT_H +#define ANDROID_BUFFEREDTEXTOUTPUT_H + +#include +#include +#include + +// --------------------------------------------------------------------------- +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 diff --git a/phonelibs/android_frameworks_native/include/binder/Debug.h b/phonelibs/android_frameworks_native/include/binder/Debug.h new file mode 100644 index 0000000000..f6a335502f --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/Debug.h @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2005 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_BINDER_DEBUG_H +#define ANDROID_BINDER_DEBUG_H + +#include +#include + +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 diff --git a/phonelibs/android_frameworks_native/include/binder/IAppOpsCallback.h b/phonelibs/android_frameworks_native/include/binder/IAppOpsCallback.h new file mode 100644 index 0000000000..7f8eb0168b --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/IAppOpsCallback.h @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +#ifndef ANDROID_IAPP_OPS_CALLBACK_H +#define ANDROID_IAPP_OPS_CALLBACK_H + +#include + +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 +{ +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 + diff --git a/phonelibs/android_frameworks_native/include/binder/IAppOpsService.h b/phonelibs/android_frameworks_native/include/binder/IAppOpsService.h new file mode 100644 index 0000000000..cd81efa363 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/IAppOpsService.h @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +#ifndef ANDROID_IAPP_OPS_SERVICE_H +#define ANDROID_IAPP_OPS_SERVICE_H + +#include +#include + +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& token, int32_t code, int32_t uid, + const String16& packageName) = 0; + virtual void finishOperation(const sp& token, int32_t code, int32_t uid, + const String16& packageName) = 0; + virtual void startWatchingMode(int32_t op, const String16& packageName, + const sp& callback) = 0; + virtual void stopWatchingMode(const sp& callback) = 0; + virtual sp getToken(const sp& 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 +{ +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 diff --git a/phonelibs/android_frameworks_native/include/binder/IBatteryStats.h b/phonelibs/android_frameworks_native/include/binder/IBatteryStats.h new file mode 100644 index 0000000000..5f3818652b --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/IBatteryStats.h @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_IBATTERYSTATS_H +#define ANDROID_IBATTERYSTATS_H + +#include + +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 +{ +public: + virtual status_t onTransact( uint32_t code, + const Parcel& data, + Parcel* reply, + uint32_t flags = 0); +}; + +// ---------------------------------------------------------------------- + +}; // namespace android + +#endif // ANDROID_IBATTERYSTATS_H diff --git a/phonelibs/android_frameworks_native/include/binder/IBinder.h b/phonelibs/android_frameworks_native/include/binder/IBinder.h new file mode 100644 index 0000000000..43b654334b --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/IBinder.h @@ -0,0 +1,152 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_IBINDER_H +#define ANDROID_IBINDER_H + +#include +#include +#include +#include + + +#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 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& 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& 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& 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& recipient, + void* cookie = NULL, + uint32_t flags = 0, + wp* 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 diff --git a/phonelibs/android_frameworks_native/include/binder/IInterface.h b/phonelibs/android_frameworks_native/include/binder/IInterface.h new file mode 100644 index 0000000000..4ce361380d --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/IInterface.h @@ -0,0 +1,150 @@ +/* + * Copyright (C) 2005 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +#ifndef ANDROID_IINTERFACE_H +#define ANDROID_IINTERFACE_H + +#include + +namespace android { + +// ---------------------------------------------------------------------- + +class IInterface : public virtual RefBase +{ +public: + IInterface(); + static sp asBinder(const IInterface*); + static sp asBinder(const sp&); + +protected: + virtual ~IInterface(); + virtual IBinder* onAsBinder() = 0; +}; + +// ---------------------------------------------------------------------- + +template +inline sp interface_cast(const sp& obj) +{ + return INTERFACE::asInterface(obj); +} + +// ---------------------------------------------------------------------- + +template +class BnInterface : public INTERFACE, public BBinder +{ +public: + virtual sp queryLocalInterface(const String16& _descriptor); + virtual const String16& getInterfaceDescriptor() const; + +protected: + virtual IBinder* onAsBinder(); +}; + +// ---------------------------------------------------------------------- + +template +class BpInterface : public INTERFACE, public BpRefBase +{ +public: + BpInterface(const sp& remote); + +protected: + virtual IBinder* onAsBinder(); +}; + +// ---------------------------------------------------------------------- + +#define DECLARE_META_INTERFACE(INTERFACE) \ + static const android::String16 descriptor; \ + static android::sp asInterface( \ + const android::sp& 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::asInterface( \ + const android::sp& obj) \ + { \ + android::sp intr; \ + if (obj != NULL) { \ + intr = static_cast( \ + 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 +inline sp BnInterface::queryLocalInterface( + const String16& _descriptor) +{ + if (_descriptor == INTERFACE::descriptor) return this; + return NULL; +} + +template +inline const String16& BnInterface::getInterfaceDescriptor() const +{ + return INTERFACE::getInterfaceDescriptor(); +} + +template +IBinder* BnInterface::onAsBinder() +{ + return this; +} + +template +inline BpInterface::BpInterface(const sp& remote) + : BpRefBase(remote) +{ +} + +template +inline IBinder* BpInterface::onAsBinder() +{ + return remote(); +} + +// ---------------------------------------------------------------------- + +}; // namespace android + +#endif // ANDROID_IINTERFACE_H diff --git a/phonelibs/android_frameworks_native/include/binder/IMemory.h b/phonelibs/android_frameworks_native/include/binder/IMemory.h new file mode 100644 index 0000000000..178ef85937 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/IMemory.h @@ -0,0 +1,107 @@ +/* + * Copyright (C) 2007 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_IMEMORY_H +#define ANDROID_IMEMORY_H + +#include +#include +#include + +#include +#include +#include + +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 +{ +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 getMemory(ssize_t* offset=0, size_t* size=0) const = 0; + + // helpers + void* fastPointer(const sp& heap, ssize_t offset) const; + void* pointer() const; + size_t size() const; + ssize_t offset() const; +}; + +class BnMemory : public BnInterface +{ +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 diff --git a/phonelibs/android_frameworks_native/include/binder/IPCThreadState.h b/phonelibs/android_frameworks_native/include/binder/IPCThreadState.h new file mode 100644 index 0000000000..1853cff235 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/IPCThreadState.h @@ -0,0 +1,135 @@ +/* + * Copyright (C) 2005 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_IPC_THREAD_STATE_H +#define ANDROID_IPC_THREAD_STATE_H + +#include +#include +#include +#include + +#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 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 mProcess; + const pid_t mMyThreadId; + Vector mPendingStrongDerefs; + Vector 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 diff --git a/phonelibs/android_frameworks_native/include/binder/IPermissionController.h b/phonelibs/android_frameworks_native/include/binder/IPermissionController.h new file mode 100644 index 0000000000..4e5fb34838 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/IPermissionController.h @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2005 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +#ifndef ANDROID_IPERMISSION_CONTROLLER_H +#define ANDROID_IPERMISSION_CONTROLLER_H + +#include +#include + +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 &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 +{ +public: + virtual status_t onTransact( uint32_t code, + const Parcel& data, + Parcel* reply, + uint32_t flags = 0); +}; + +// ---------------------------------------------------------------------- + +}; // namespace android + +#endif // ANDROID_IPERMISSION_CONTROLLER_H + diff --git a/phonelibs/android_frameworks_native/include/binder/IProcessInfoService.h b/phonelibs/android_frameworks_native/include/binder/IProcessInfoService.h new file mode 100644 index 0000000000..dc62f457c7 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/IProcessInfoService.h @@ -0,0 +1,53 @@ +/* + * Copyright 2015 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_I_PROCESS_INFO_SERVICE_H +#define ANDROID_I_PROCESS_INFO_SERVICE_H + +#include + +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 { +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 diff --git a/phonelibs/android_frameworks_native/include/binder/IServiceManager.h b/phonelibs/android_frameworks_native/include/binder/IServiceManager.h new file mode 100644 index 0000000000..2c297d64fb --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/IServiceManager.h @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2005 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +#ifndef ANDROID_ISERVICE_MANAGER_H +#define ANDROID_ISERVICE_MANAGER_H + +#include +#include +#include +#include + +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 getService( const String16& name) const = 0; + + /** + * Retrieve an existing service, non-blocking. + */ + virtual sp checkService( const String16& name) const = 0; + + /** + * Register a service. + */ + virtual status_t addService( const String16& name, + const sp& service, + bool allowIsolated = false) = 0; + + /** + * Return list of all existing services. + */ + virtual Vector listServices() = 0; + + enum { + GET_SERVICE_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION, + CHECK_SERVICE_TRANSACTION, + ADD_SERVICE_TRANSACTION, + LIST_SERVICES_TRANSACTION, + }; +}; + +sp defaultServiceManager(); + +template +status_t getService(const String16& name, sp* outService) +{ + const sp sm = defaultServiceManager(); + if (sm != NULL) { + *outService = interface_cast(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 +{ +public: + virtual status_t onTransact( uint32_t code, + const Parcel& data, + Parcel* reply, + uint32_t flags = 0); +}; + +// ---------------------------------------------------------------------- + +}; // namespace android + +#endif // ANDROID_ISERVICE_MANAGER_H + diff --git a/phonelibs/android_frameworks_native/include/binder/MemoryBase.h b/phonelibs/android_frameworks_native/include/binder/MemoryBase.h new file mode 100644 index 0000000000..463e26d977 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/MemoryBase.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_MEMORY_BASE_H +#define ANDROID_MEMORY_BASE_H + +#include +#include + +#include + + +namespace android { + +// --------------------------------------------------------------------------- + +class MemoryBase : public BnMemory +{ +public: + MemoryBase(const sp& heap, ssize_t offset, size_t size); + virtual ~MemoryBase(); + virtual sp getMemory(ssize_t* offset, size_t* size) const; + +protected: + size_t getSize() const { return mSize; } + ssize_t getOffset() const { return mOffset; } + const sp& getHeap() const { return mHeap; } + +private: + size_t mSize; + ssize_t mOffset; + sp mHeap; +}; + +// --------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_MEMORY_BASE_H diff --git a/phonelibs/android_frameworks_native/include/binder/MemoryDealer.h b/phonelibs/android_frameworks_native/include/binder/MemoryDealer.h new file mode 100644 index 0000000000..aa415d5ac8 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/MemoryDealer.h @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2007 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_MEMORY_DEALER_H +#define ANDROID_MEMORY_DEALER_H + + +#include +#include + +#include +#include + +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 allocate(size_t size); + virtual void deallocate(size_t offset); + virtual void dump(const char* what) const; + + sp getMemoryHeap() const { return heap(); } + +protected: + virtual ~MemoryDealer(); + +private: + const sp& heap() const; + SimpleBestFitAllocator* allocator() const; + + sp mHeap; + SimpleBestFitAllocator* mAllocator; +}; + + +// ---------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_MEMORY_DEALER_H diff --git a/phonelibs/android_frameworks_native/include/binder/MemoryHeapBase.h b/phonelibs/android_frameworks_native/include/binder/MemoryHeapBase.h new file mode 100644 index 0000000000..ea9b66c497 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/MemoryHeapBase.h @@ -0,0 +1,103 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_MEMORY_HEAP_BASE_H +#define ANDROID_MEMORY_HEAP_BASE_H + +#include +#include + +#include + + +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 diff --git a/phonelibs/android_frameworks_native/include/binder/MemoryHeapIon.h b/phonelibs/android_frameworks_native/include/binder/MemoryHeapIon.h new file mode 100644 index 0000000000..7e059f4eac --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/MemoryHeapIon.h @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * Copyright 2011, Samsung Electronics Co. LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/*! + * \file MemoryHeapIon.h + * \brief header file for MemoryHeapIon + * \author MinGu, Jeon(mingu85.jeon) + * \date 2011/11/20 + * + * Revision History: + * - 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 +#include +#include + +#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 diff --git a/phonelibs/android_frameworks_native/include/binder/Parcel.h b/phonelibs/android_frameworks_native/include/binder/Parcel.h new file mode 100644 index 0000000000..91ffae0ba3 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/Parcel.h @@ -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 +#include +#include +#include +#include +#include +#include + +// --------------------------------------------------------------------------- +namespace android { + +template class Flattenable; +template 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& val); + status_t writeWeakBinder(const wp& val); + status_t writeInt32Array(size_t len, const int32_t *val); + status_t writeByteArray(size_t len, const uint8_t *val); + + template + status_t write(const Flattenable& val); + + template + status_t write(const LightFlattenable& 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 readStrongBinder() const; + wp readWeakBinder() const; + + template + status_t read(Flattenable& val) const; + + template + status_t read(LightFlattenable& 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 + status_t readAligned(T *pArg) const; + + template T readAligned() const; + + template + 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 + class FlattenableHelper : public FlattenableHelperInterface { + friend class Parcel; + const Flattenable& val; + explicit FlattenableHelper(const Flattenable& 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&>(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 +status_t Parcel::write(const Flattenable& val) { + const FlattenableHelper helper(val); + return write(helper); +} + +template +status_t Parcel::write(const LightFlattenable& 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 +status_t Parcel::read(Flattenable& val) const { + FlattenableHelper helper(val); + return read(helper); +} + +template +status_t Parcel::read(LightFlattenable& 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& proc, + const flat_binder_object& obj, const void* who); +void release_object(const sp& proc, + const flat_binder_object& obj, const void* who); + +void flatten_binder(const sp& proc, + const sp& binder, flat_binder_object* out); +void flatten_binder(const sp& proc, + const wp& binder, flat_binder_object* out); +status_t unflatten_binder(const sp& proc, + const flat_binder_object& flat, sp* out); +status_t unflatten_binder(const sp& proc, + const flat_binder_object& flat, wp* out); + +}; // namespace android + +// --------------------------------------------------------------------------- + +#endif // ANDROID_PARCEL_H diff --git a/phonelibs/android_frameworks_native/include/binder/PermissionCache.h b/phonelibs/android_frameworks_native/include/binder/PermissionCache.h new file mode 100644 index 0000000000..bcdf0c2914 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/PermissionCache.h @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BINDER_PERMISSION_H +#define BINDER_PERMISSION_H + +#include +#include + +#include +#include +#include + +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 { + 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 */ diff --git a/phonelibs/android_frameworks_native/include/binder/ProcessInfoService.h b/phonelibs/android_frameworks_native/include/binder/ProcessInfoService.h new file mode 100644 index 0000000000..c5ead20676 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/ProcessInfoService.h @@ -0,0 +1,65 @@ +/* + * Copyright 2015 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_PROCESS_INFO_SERVICE_H +#define ANDROID_PROCESS_INFO_SERVICE_H + +#include +#include +#include +#include + +namespace android { + +// ---------------------------------------------------------------------- + +class ProcessInfoService : public Singleton { + + friend class Singleton; + sp 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 + diff --git a/phonelibs/android_frameworks_native/include/binder/ProcessState.h b/phonelibs/android_frameworks_native/include/binder/ProcessState.h new file mode 100644 index 0000000000..f9edc2a691 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/ProcessState.h @@ -0,0 +1,116 @@ +/* + * Copyright (C) 2005 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_PROCESS_STATE_H +#define ANDROID_PROCESS_STATE_H + +#include +#include +#include +#include + +#include + +#include + +// --------------------------------------------------------------------------- +namespace android { + +class IPCThreadState; + +class ProcessState : public virtual RefBase +{ +public: + static sp self(); + + void setContextObject(const sp& object); + sp getContextObject(const sp& caller); + + void setContextObject(const sp& object, + const String16& name); + sp getContextObject(const String16& name, + const sp& caller); + + void startThreadPool(); + + typedef bool (*context_check_func)(const String16& name, + const sp& caller, + void* userData); + + bool isContextManager(void) const; + bool becomeContextManager( + context_check_func checkFunc, + void* userData); + + sp getStrongProxyForHandle(int32_t handle); + wp 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. + + VectormHandleToObject; + + bool mManagesContexts; + context_check_func mBinderContextCheckFunc; + void* mBinderContextUserData; + + KeyedVector > + mContexts; + + + String8 mRootDir; + bool mThreadPoolStarted; + volatile int32_t mThreadPoolSeq; +}; + +}; // namespace android + +// --------------------------------------------------------------------------- + +#endif // ANDROID_PROCESS_STATE_H diff --git a/phonelibs/android_frameworks_native/include/binder/TextOutput.h b/phonelibs/android_frameworks_native/include/binder/TextOutput.h new file mode 100644 index 0000000000..974a194d8c --- /dev/null +++ b/phonelibs/android_frameworks_native/include/binder/TextOutput.h @@ -0,0 +1,195 @@ +/* + * Copyright (C) 2006 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_TEXTOUTPUT_H +#define ANDROID_TEXTOUTPUT_H + +#include + +#include +#include + +// --------------------------------------------------------------------------- +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 diff --git a/phonelibs/android_frameworks_native/include/diskusage/dirsize.h b/phonelibs/android_frameworks_native/include/diskusage/dirsize.h new file mode 100644 index 0000000000..34236c0e6f --- /dev/null +++ b/phonelibs/android_frameworks_native/include/diskusage/dirsize.h @@ -0,0 +1,30 @@ +/* + * + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __LIBDISKUSAGE_DIRSIZE_H +#define __LIBDISKUSAGE_DIRSIZE_H + +#include + +__BEGIN_DECLS + +int64_t stat_size(struct stat *s); +int64_t calculate_dir_size(int dfd); + +__END_DECLS + +#endif /* __LIBDISKUSAGE_DIRSIZE_H */ diff --git a/phonelibs/android_frameworks_native/include/gui/BitTube.h b/phonelibs/android_frameworks_native/include/gui/BitTube.h new file mode 100644 index 0000000000..3ecac52ad7 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/BitTube.h @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_SENSOR_CHANNEL_H +#define ANDROID_GUI_SENSOR_CHANNEL_H + +#include +#include + +#include +#include +#include + + +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 + static ssize_t sendObjects(const sp& 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 + static ssize_t recvObjects(const sp& 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& tube, + void const* events, size_t count, size_t objSize); + + static ssize_t recvObjects(const sp& tube, + void* events, size_t count, size_t objSize); +}; + +// ---------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_GUI_SENSOR_CHANNEL_H diff --git a/phonelibs/android_frameworks_native/include/gui/BufferItem.h b/phonelibs/android_frameworks_native/include/gui/BufferItem.h new file mode 100644 index 0000000000..145efe6f60 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/BufferItem.h @@ -0,0 +1,130 @@ +/* + * Copyright 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_BUFFERITEM_H +#define ANDROID_GUI_BUFFERITEM_H + +#include +#include + +#include +#include + +#include + +#include +#include + +namespace android { + +class Fence; +class GraphicBuffer; + +class BufferItem : public Flattenable { + friend class Flattenable; + 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 mGraphicBuffer; + + // mFence is a fence that will signal when the buffer is idle. + sp 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 + uint32_t mTransform; + + // mScalingMode is the current scaling mode for this buffer slot. + // refer to NATIVE_WINDOW_SCALING_* in + 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 diff --git a/phonelibs/android_frameworks_native/include/gui/BufferItemConsumer.h b/phonelibs/android_frameworks_native/include/gui/BufferItemConsumer.h new file mode 100644 index 0000000000..56c7a3f463 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/BufferItemConsumer.h @@ -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 + +#include + +#include +#include +#include + +#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& 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& releaseFence = Fence::NO_FENCE); + +}; + +} // namespace android + +#endif // ANDROID_GUI_CPUCONSUMER_H diff --git a/phonelibs/android_frameworks_native/include/gui/BufferQueue.h b/phonelibs/android_frameworks_native/include/gui/BufferQueue.h new file mode 100644 index 0000000000..09300a20c9 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/BufferQueue.h @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_BUFFERQUEUE_H +#define ANDROID_GUI_BUFFERQUEUE_H + +#include +#include +#include +#include +#include + +// These are only required to keep other parts of the framework with incomplete +// dependencies building successfully +#include + +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 -- 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); + 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 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* outProducer, + sp* outConsumer, + const sp& allocator = NULL); + +private: + BufferQueue(); // Create through createBufferQueue +}; + +// ---------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_GUI_BUFFERQUEUE_H diff --git a/phonelibs/android_frameworks_native/include/gui/BufferQueueConsumer.h b/phonelibs/android_frameworks_native/include/gui/BufferQueueConsumer.h new file mode 100644 index 0000000000..cde302f8a6 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/BufferQueueConsumer.h @@ -0,0 +1,187 @@ +/* + * Copyright 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_BUFFERQUEUECONSUMER_H +#define ANDROID_GUI_BUFFERQUEUECONSUMER_H + +#include +#include + +#include +#include + +namespace android { + +class BufferQueueCore; + +class BufferQueueConsumer : public BnGraphicBufferConsumer { + +public: + BufferQueueConsumer(const sp& 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& 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& 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& 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 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& releaseFence) { + return releaseBuffer(buf, frameNumber, releaseFence, display, fence); + } + + virtual status_t consumerConnect(const sp& consumer, + bool controlledByApp) { + return connect(consumer, controlledByApp); + } + + virtual status_t consumerDisconnect() { return disconnect(); } + + // End functions required for backwards compatibility + +private: + sp 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 diff --git a/phonelibs/android_frameworks_native/include/gui/BufferQueueCore.h b/phonelibs/android_frameworks_native/include/gui/BufferQueueCore.h new file mode 100644 index 0000000000..99134ea501 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/BufferQueueCore.h @@ -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 +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#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 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& 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 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 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 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 mFreeSlots; + + // mFreeBuffers contains all of the slots which are FREE and currently have + // a buffer attached + std::list 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 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 diff --git a/phonelibs/android_frameworks_native/include/gui/BufferQueueDefs.h b/phonelibs/android_frameworks_native/include/gui/BufferQueueDefs.h new file mode 100644 index 0000000000..83e9580037 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/BufferQueueDefs.h @@ -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 + +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 diff --git a/phonelibs/android_frameworks_native/include/gui/BufferQueueProducer.h b/phonelibs/android_frameworks_native/include/gui/BufferQueueProducer.h new file mode 100644 index 0000000000..9754a89eac --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/BufferQueueProducer.h @@ -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 +#include + +namespace android { + +class BufferSlot; + +class BufferQueueProducer : public BnGraphicBufferProducer, + private IBinder::DeathRecipient { +public: + friend class BufferQueue; // Needed to access binderDied + + BufferQueueProducer(const sp& 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* 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* 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* outBuffer, + sp* outFence); + + // See IGraphicBufferProducer::attachBuffer + virtual status_t attachBuffer(int* outSlot, const sp& 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); + + // 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& 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& 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& 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 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 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 diff --git a/phonelibs/android_frameworks_native/include/gui/BufferSlot.h b/phonelibs/android_frameworks_native/include/gui/BufferSlot.h new file mode 100644 index 0000000000..6085e116a3 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/BufferSlot.h @@ -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 +#include + +#include +#include + +#include + +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 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 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 diff --git a/phonelibs/android_frameworks_native/include/gui/ConsumerBase.h b/phonelibs/android_frameworks_native/include/gui/ConsumerBase.h new file mode 100644 index 0000000000..9307a26fb3 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/ConsumerBase.h @@ -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 + +#include + +#include +#include +#include +#include + +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& 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& 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, + EGLDisplay display, EGLSyncKHR eglFence); + + // returns true iff the slot still has the graphicBuffer in it. + bool stillTracking(int slot, const sp 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, const sp& fence); + status_t addReleaseFenceLocked(int slot, + const sp graphicBuffer, const sp& 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 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 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 mFrameAvailableListener; + + // The ConsumerBase has-a BufferQueue and is responsible for creating this object + // if none is supplied + sp 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 diff --git a/phonelibs/android_frameworks_native/include/gui/CpuConsumer.h b/phonelibs/android_frameworks_native/include/gui/CpuConsumer.h new file mode 100644 index 0000000000..3b07a31750 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/CpuConsumer.h @@ -0,0 +1,131 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_CPUCONSUMER_H +#define ANDROID_GUI_CPUCONSUMER_H + +#include + +#include + +#include +#include +#include + + +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& 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 mGraphicBuffer; + void *mBufferPointer; + + AcquiredBuffer() : + mSlot(BufferQueue::INVALID_BUFFER_SLOT), + mBufferPointer(NULL) { + } + }; + Vector mAcquiredBuffers; + + // Count of currently locked buffers + size_t mCurrentLockedBuffers; + +}; + +} // namespace android + +#endif // ANDROID_GUI_CPUCONSUMER_H diff --git a/phonelibs/android_frameworks_native/include/gui/DisplayEventReceiver.h b/phonelibs/android_frameworks_native/include/gui/DisplayEventReceiver.h new file mode 100644 index 0000000000..a4718b91c6 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/DisplayEventReceiver.h @@ -0,0 +1,137 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_DISPLAY_EVENT_H +#define ANDROID_GUI_DISPLAY_EVENT_H + +#include +#include + +#include +#include +#include + +#include + +// ---------------------------------------------------------------------------- + +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& 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& 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 mEventConnection; + sp mDataChannel; +}; + +// ---------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_GUI_DISPLAY_EVENT_H diff --git a/phonelibs/android_frameworks_native/include/gui/GLConsumer.h b/phonelibs/android_frameworks_native/include/gui/GLConsumer.h new file mode 100644 index 0000000000..c35c7be064 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/GLConsumer.h @@ -0,0 +1,488 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_CONSUMER_H +#define ANDROID_GUI_CONSUMER_H + +#include +#include + +#include +#include +#include + +#include + +#include +#include +#include + +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& bq, + uint32_t tex, uint32_t texureTarget, bool useFenceSync, + bool isControlledByApp); + + GLConsumer(const sp& 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); + + // 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 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 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, + EGLDisplay display, EGLSyncKHR eglFence); + + status_t releaseBufferLocked(int slot, + const sp 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 { + public: + EglImage(sp 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() { return mGraphicBuffer; } + const native_handle* graphicBufferHandle() { + return mGraphicBuffer == NULL ? NULL : mGraphicBuffer->handle; + } + + private: + // Only allow instantiation using ref counting. + friend class LightRefBase; + virtual ~EglImage(); + + // createImage creates a new EGLImage from a GraphicBuffer. + EGLImageKHR createImage(EGLDisplay dpy, + const sp& 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 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 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 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 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 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 sReleasedTexImageBuffer; + sp mReleasedTexImage; +}; + +// ---------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_GUI_CONSUMER_H diff --git a/phonelibs/android_frameworks_native/include/gui/GraphicBufferAlloc.h b/phonelibs/android_frameworks_native/include/gui/GraphicBufferAlloc.h new file mode 100644 index 0000000000..69fe51ef93 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/GraphicBufferAlloc.h @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_SF_GRAPHIC_BUFFER_ALLOC_H +#define ANDROID_SF_GRAPHIC_BUFFER_ALLOC_H + +#include +#include + +#include +#include +#include + +namespace android { +// --------------------------------------------------------------------------- + +class GraphicBuffer; + +class GraphicBufferAlloc : public BnGraphicBufferAlloc { +public: + GraphicBufferAlloc(); + virtual ~GraphicBufferAlloc(); + virtual sp createGraphicBuffer(uint32_t width, + uint32_t height, PixelFormat format, uint32_t usage, + status_t* error); +}; + + +// --------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_SF_GRAPHIC_BUFFER_ALLOC_H diff --git a/phonelibs/android_frameworks_native/include/gui/GuiConfig.h b/phonelibs/android_frameworks_native/include/gui/GuiConfig.h new file mode 100644 index 0000000000..b020ed9b6a --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/GuiConfig.h @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_CONFIG_H +#define ANDROID_GUI_CONFIG_H + +#include + +namespace android { + +// Append the libgui configuration details to configStr. +void appendGuiConfigString(String8& configStr); + +}; // namespace android + +#endif /*ANDROID_GUI_CONFIG_H*/ diff --git a/phonelibs/android_frameworks_native/include/gui/IConsumerListener.h b/phonelibs/android_frameworks_native/include/gui/IConsumerListener.h new file mode 100644 index 0000000000..3f39799564 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/IConsumerListener.h @@ -0,0 +1,104 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_ICONSUMERLISTENER_H +#define ANDROID_GUI_ICONSUMERLISTENER_H + +#include +#include + +#include +#include + +#include + +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 +{ +public: + virtual status_t onTransact( uint32_t code, + const Parcel& data, + Parcel* reply, + uint32_t flags = 0); +}; + +// ---------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_GUI_ICONSUMERLISTENER_H diff --git a/phonelibs/android_frameworks_native/include/gui/IDisplayEventConnection.h b/phonelibs/android_frameworks_native/include/gui/IDisplayEventConnection.h new file mode 100644 index 0000000000..86247de62b --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/IDisplayEventConnection.h @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_IDISPLAY_EVENT_CONNECTION_H +#define ANDROID_GUI_IDISPLAY_EVENT_CONNECTION_H + +#include +#include + +#include +#include + +#include + +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 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 +{ +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 diff --git a/phonelibs/android_frameworks_native/include/gui/IGraphicBufferAlloc.h b/phonelibs/android_frameworks_native/include/gui/IGraphicBufferAlloc.h new file mode 100644 index 0000000000..f3c46ec2ed --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/IGraphicBufferAlloc.h @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_IGRAPHIC_BUFFER_ALLOC_H +#define ANDROID_GUI_IGRAPHIC_BUFFER_ALLOC_H + +#include +#include + +#include +#include +#include + +namespace android { +// ---------------------------------------------------------------------------- + +class GraphicBuffer; + +class IGraphicBufferAlloc : public IInterface +{ +public: + DECLARE_META_INTERFACE(GraphicBufferAlloc); + + /* Create a new GraphicBuffer for the client to use. + */ + virtual sp createGraphicBuffer(uint32_t w, uint32_t h, + PixelFormat format, uint32_t usage, status_t* error) = 0; +}; + +// ---------------------------------------------------------------------------- + +class BnGraphicBufferAlloc : public BnInterface +{ +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 diff --git a/phonelibs/android_frameworks_native/include/gui/IGraphicBufferConsumer.h b/phonelibs/android_frameworks_native/include/gui/IGraphicBufferConsumer.h new file mode 100644 index 0000000000..60ec9cc0e9 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/IGraphicBufferConsumer.h @@ -0,0 +1,280 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_IGRAPHICBUFFERCONSUMER_H +#define ANDROID_GUI_IGRAPHICBUFFERCONSUMER_H + +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include +#include + +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& 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& 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& 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 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 +{ +public: + virtual status_t onTransact( uint32_t code, + const Parcel& data, + Parcel* reply, + uint32_t flags = 0); +}; + +// ---------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_GUI_IGRAPHICBUFFERCONSUMER_H diff --git a/phonelibs/android_frameworks_native/include/gui/IGraphicBufferProducer.h b/phonelibs/android_frameworks_native/include/gui/IGraphicBufferProducer.h new file mode 100644 index 0000000000..9530de1aa8 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/IGraphicBufferProducer.h @@ -0,0 +1,502 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_IGRAPHICBUFFERPRODUCER_H +#define ANDROID_GUI_IGRAPHICBUFFERPRODUCER_H + +#include +#include + +#include +#include + +#include + +#include +#include +#include +#include + +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* 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 , 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, 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 (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* outBuffer, + sp* 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& 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 { + friend class Flattenable; + 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 + // transform - a set of flags from NATIVE_WINDOW_TRANSFORM_* in + // 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, + 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* 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; + 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) = 0; + + // query retrieves some information for this surface + // 'what' tokens allowed are that of NATIVE_WINDOW_* in + // + // 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 + // + // 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& 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 + // + // 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& 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 +{ +public: + virtual status_t onTransact( uint32_t code, + const Parcel& data, + Parcel* reply, + uint32_t flags = 0); +}; + +// ---------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_GUI_IGRAPHICBUFFERPRODUCER_H diff --git a/phonelibs/android_frameworks_native/include/gui/IProducerListener.h b/phonelibs/android_frameworks_native/include/gui/IProducerListener.h new file mode 100644 index 0000000000..3848a6c850 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/IProducerListener.h @@ -0,0 +1,67 @@ +/* + * Copyright 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_IPRODUCERLISTENER_H +#define ANDROID_GUI_IPRODUCERLISTENER_H + +#include + +#include + +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 +{ +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 diff --git a/phonelibs/android_frameworks_native/include/gui/ISensorEventConnection.h b/phonelibs/android_frameworks_native/include/gui/ISensorEventConnection.h new file mode 100644 index 0000000000..f64c6b8604 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/ISensorEventConnection.h @@ -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 +#include + +#include +#include + +#include + +namespace android { +// ---------------------------------------------------------------------------- + +class BitTube; + +class ISensorEventConnection : public IInterface +{ +public: + DECLARE_META_INTERFACE(SensorEventConnection); + + virtual sp 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 +{ +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 diff --git a/phonelibs/android_frameworks_native/include/gui/ISensorServer.h b/phonelibs/android_frameworks_native/include/gui/ISensorServer.h new file mode 100644 index 0000000000..3dca2a3739 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/ISensorServer.h @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_ISENSORSERVER_H +#define ANDROID_GUI_ISENSORSERVER_H + +#include +#include + +#include +#include + +#include + +namespace android { +// ---------------------------------------------------------------------------- + +class Sensor; +class ISensorEventConnection; +class String8; + +class ISensorServer : public IInterface +{ +public: + DECLARE_META_INTERFACE(SensorServer); + + virtual Vector getSensorList(const String16& opPackageName) = 0; + virtual sp createSensorEventConnection(const String8& packageName, + int mode, const String16& opPackageName) = 0; + virtual int32_t isDataInjectionEnabled() = 0; +}; + +// ---------------------------------------------------------------------------- + +class BnSensorServer : public BnInterface +{ +public: + virtual status_t onTransact( uint32_t code, + const Parcel& data, + Parcel* reply, + uint32_t flags = 0); +}; + +// ---------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_GUI_ISENSORSERVER_H diff --git a/phonelibs/android_frameworks_native/include/gui/ISurfaceComposer.h b/phonelibs/android_frameworks_native/include/gui/ISurfaceComposer.h new file mode 100644 index 0000000000..6e3fc5a6de --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/ISurfaceComposer.h @@ -0,0 +1,201 @@ +/* + * Copyright (C) 2006 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_ISURFACE_COMPOSER_H +#define ANDROID_GUI_ISURFACE_COMPOSER_H + +#include +#include + +#include +#include +#include +#include + +#include + +#include + +#include +#include + +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 createConnection() = 0; + + /* create a graphic buffer allocator + */ + virtual sp createGraphicBufferAlloc() = 0; + + /* return an IDisplayEventConnection */ + virtual sp createDisplayEventConnection() = 0; + + /* create a virtual display + * requires ACCESS_SURFACE_FLINGER permission. + */ + virtual sp createDisplay(const String8& displayName, + bool secure) = 0; + + /* destroy a virtual display + * requires ACCESS_SURFACE_FLINGER permission. + */ + virtual void destroyDisplay(const sp& display) = 0; + + /* get the token for the existing default displays. possible values + * for id are eDisplayIdMain and eDisplayIdHdmi. + */ + virtual sp getBuiltInDisplay(int32_t id) = 0; + + /* open/close transactions. requires ACCESS_SURFACE_FLINGER permission */ + virtual void setTransactionState(const Vector& state, + const Vector& 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& 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& 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& display, + Vector* 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& display, + DisplayStatInfo* stats) = 0; + + /* indicates which of the configurations returned by getDisplayInfo is + * currently active */ + virtual int getActiveConfig(const sp& display) = 0; + + /* specifies which configuration (of those returned by getDisplayInfo) + * should be used */ + virtual status_t setActiveConfig(const sp& 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& display, + const sp& 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 { +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 diff --git a/phonelibs/android_frameworks_native/include/gui/ISurfaceComposerClient.h b/phonelibs/android_frameworks_native/include/gui/ISurfaceComposerClient.h new file mode 100644 index 0000000000..d3e8b8ba13 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/ISurfaceComposerClient.h @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2007 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_ISURFACE_COMPOSER_CLIENT_H +#define ANDROID_GUI_ISURFACE_COMPOSER_CLIENT_H + +#include +#include + +#include +#include + +#include + +#include +#include + +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* handle, + sp* gbp) = 0; + + /* + * Requires ACCESS_SURFACE_FLINGER permission + */ + virtual status_t destroySurface(const sp& handle) = 0; + + /* + * Requires ACCESS_SURFACE_FLINGER permission + */ + virtual status_t clearLayerFrameStats(const sp& handle) const = 0; + + /* + * Requires ACCESS_SURFACE_FLINGER permission + */ + virtual status_t getLayerFrameStats(const sp& handle, FrameStats* outStats) const = 0; +}; + +// ---------------------------------------------------------------------------- + +class BnSurfaceComposerClient: public BnInterface { +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 diff --git a/phonelibs/android_frameworks_native/include/gui/Sensor.h b/phonelibs/android_frameworks_native/include/gui/Sensor.h new file mode 100644 index 0000000000..8142be6352 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/Sensor.h @@ -0,0 +1,113 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_SENSOR_H +#define ANDROID_GUI_SENSOR_H + +#include +#include + +#include +#include +#include +#include + +#include + +#include + +// ---------------------------------------------------------------------------- +// Concrete types for the NDK +struct ASensor { }; + +// ---------------------------------------------------------------------------- +namespace android { +// ---------------------------------------------------------------------------- + +class Parcel; + +// ---------------------------------------------------------------------------- + +class Sensor : public ASensor, public LightFlattenable +{ +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 diff --git a/phonelibs/android_frameworks_native/include/gui/SensorEventQueue.h b/phonelibs/android_frameworks_native/include/gui/SensorEventQueue.h new file mode 100644 index 0000000000..e5b9fc5984 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/SensorEventQueue.h @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_SENSOR_EVENT_QUEUE_H +#define ANDROID_SENSOR_EVENT_QUEUE_H + +#include +#include + +#include +#include +#include +#include + +#include + +// ---------------------------------------------------------------------------- +#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& connection); + virtual ~SensorEventQueue(); + virtual void onFirstRef(); + + int getFd() const; + + static ssize_t write(const sp& 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 getLooper() const; + sp mSensorEventConnection; + sp mSensorChannel; + mutable Mutex mLock; + mutable sp mLooper; + ASensorEvent* mRecBuffer; + size_t mAvailable; + size_t mConsumed; + uint32_t mNumAcksToSend; +}; + +// ---------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_SENSOR_EVENT_QUEUE_H diff --git a/phonelibs/android_frameworks_native/include/gui/SensorManager.h b/phonelibs/android_frameworks_native/include/gui/SensorManager.h new file mode 100644 index 0000000000..0cff46c076 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/SensorManager.h @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_SENSOR_MANAGER_H +#define ANDROID_GUI_SENSOR_MANAGER_H + +#include + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +// ---------------------------------------------------------------------------- +// 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 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 sPackageInstances; + + mutable Mutex mLock; + mutable sp mSensorServer; + mutable Sensor const** mSensorList; + mutable Vector mSensors; + mutable sp mDeathObserver; + const String16 mOpPackageName; +}; + +// ---------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_GUI_SENSOR_MANAGER_H diff --git a/phonelibs/android_frameworks_native/include/gui/StreamSplitter.h b/phonelibs/android_frameworks_native/include/gui/StreamSplitter.h new file mode 100644 index 0000000000..8f47eb47ac --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/StreamSplitter.h @@ -0,0 +1,184 @@ +/* + * Copyright 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_STREAMSPLITTER_H +#define ANDROID_GUI_STREAMSPLITTER_H + +#include +#include + +#include +#include +#include +#include + +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& inputQueue, + sp* 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& 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& 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& splitter, + const sp& output); + virtual ~OutputListener(); + + // From IProducerListener + virtual void onBufferReleased(); + + // From IBinder::DeathRecipient + virtual void binderDied(const wp& who); + + private: + sp mSplitter; + sp mOutput; + }; + + class BufferTracker : public LightRefBase { + public: + BufferTracker(const sp& buffer); + + const sp& getBuffer() const { return mBuffer; } + const sp& getMergedFence() const { return mMergedFence; } + + void mergeFence(const sp& with); + + // Returns the new value + // Only called while mMutex is held + size_t incrementReleaseCountLocked() { return ++mReleaseCount; } + + private: + // Only destroy through LightRefBase + friend LightRefBase; + ~BufferTracker(); + + // Disallow copying + BufferTracker(const BufferTracker& other); + BufferTracker& operator=(const BufferTracker& other); + + sp mBuffer; // One instance that holds this native handle + sp mMergedFence; + size_t mReleaseCount; + }; + + // Only called from createSplitter + StreamSplitter(const sp& 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 mInput; + Vector > 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 > mBuffers; +}; + +} // namespace android + +#endif diff --git a/phonelibs/android_frameworks_native/include/gui/Surface.h b/phonelibs/android_frameworks_native/include/gui/Surface.h new file mode 100644 index 0000000000..72f1067076 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/Surface.h @@ -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 +#include + +#include +#include + +#include +#include +#include + +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 +{ +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& 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 getIGraphicBufferProducer() const; + + /* convenience function to check that the given surface is non NULL as + * well as its IGraphicBufferProducer */ + static bool isValid(const sp& 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& 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& listener); + virtual int detachNextBuffer(sp* outBuffer, + sp* 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 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 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 mLockedBuffer; + sp 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 diff --git a/phonelibs/android_frameworks_native/include/gui/SurfaceComposerClient.h b/phonelibs/android_frameworks_native/include/gui/SurfaceComposerClient.h new file mode 100644 index 0000000000..9ec3f23491 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/SurfaceComposerClient.h @@ -0,0 +1,242 @@ +/* + * Copyright (C) 2007 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_SURFACE_COMPOSER_CLIENT_H +#define ANDROID_GUI_SURFACE_COMPOSER_CLIENT_H + +#include +#include + +#include +#include + +#include +#include +#include +#include + +#include +#include + +#include +#include + +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 connection() const; + + // Forcibly remove connection before all references have gone away. + void dispose(); + + // callback when the composer is dies + status_t linkToComposerDeath(const sp& recipient, + void* cookie = NULL, uint32_t flags = 0); + + // Get a list of supported configurations for a given display + static status_t getDisplayConfigs(const sp& display, + Vector* configs); + + // Get the DisplayInfo for the currently-active configuration + static status_t getDisplayInfo(const sp& display, + DisplayInfo* info); + + // Get the index of the current active configuration (relative to the list + // returned by getDisplayInfo) + static int getActiveConfig(const sp& display); + + // Set a new active configuration using an index relative to the list + // returned by getDisplayInfo + static status_t setActiveConfig(const sp& display, int id); + + /* Triggers screen on/off or low power mode and waits for it to complete */ + static void setDisplayPowerMode(const sp& display, int mode); + + // ------------------------------------------------------------------------ + // surface creation / destruction + + //! Create a surface + sp 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 createDisplay(const String8& displayName, bool secure); + + //! Destroy a virtual display + static void destroyDisplay(const sp& display); + + //! Get the token for the existing default displays. + //! Possible values for id are eDisplayIdMain and eDisplayIdHdmi. + static sp 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& id); + status_t show(const sp& id); + status_t setFlags(const sp& id, uint32_t flags, uint32_t mask); + status_t setTransparentRegionHint(const sp& id, const Region& transparent); + status_t setLayer(const sp& id, uint32_t layer); + status_t setAlpha(const sp& id, float alpha=1.0f); + status_t setMatrix(const sp& id, float dsdx, float dtdx, float dsdy, float dtdy); + status_t setPosition(const sp& id, float x, float y); + status_t setSize(const sp& id, uint32_t w, uint32_t h); + status_t setCrop(const sp& id, const Rect& crop); + status_t setLayerStack(const sp& id, uint32_t layerStack); + status_t destroySurface(const sp& id); + + status_t clearLayerFrameStats(const sp& token) const; + status_t getLayerFrameStats(const sp& token, FrameStats* outStats) const; + + static status_t clearAnimationFrameStats(); + static status_t getAnimationFrameStats(FrameStats* outStats); + + static void setDisplaySurface(const sp& token, + const sp& bufferProducer); + static void setDisplayLayerStack(const sp& token, + uint32_t layerStack); + static void setDisplaySize(const sp& 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& token, + uint32_t orientation, + const Rect& layerStackRect, + const Rect& displayRect); + + status_t setBlur(const sp& id, float blur); + status_t setBlurMaskSurface(const sp& id, const sp& maskSurfaceId); + status_t setBlurMaskSampling(const sp& id, uint32_t blurMaskSampling); + status_t setBlurMaskAlphaThreshold(const sp& id, float alpha); + +private: + virtual void onFirstRef(); + Composer& getComposer(); + + mutable Mutex mLock; + status_t mStatus; + sp 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& display, + const sp& producer, + Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight, + uint32_t minLayerZ, uint32_t maxLayerZ, + bool useIdentityTransform); + +private: + mutable sp mCpuConsumer; + mutable sp 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& display, + Rect sourceCrop, bool useIdentityTransform); + status_t update(const sp& display, + Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight, + bool useIdentityTransform); + status_t update(const sp& display, + Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight, + uint32_t minLayerZ, uint32_t maxLayerZ, + bool useIdentityTransform); + status_t update(const sp& display, + Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight, + uint32_t minLayerZ, uint32_t maxLayerZ, + bool useIdentityTransform, uint32_t rotation); + + sp 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 diff --git a/phonelibs/android_frameworks_native/include/gui/SurfaceControl.h b/phonelibs/android_frameworks_native/include/gui/SurfaceControl.h new file mode 100644 index 0000000000..5fa45d1668 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/gui/SurfaceControl.h @@ -0,0 +1,112 @@ +/* + * Copyright (C) 2007 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_SURFACE_CONTROL_H +#define ANDROID_GUI_SURFACE_CONTROL_H + +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include + +namespace android { + +// --------------------------------------------------------------------------- + +class IGraphicBufferProducer; +class Surface; +class SurfaceComposerClient; + +// --------------------------------------------------------------------------- + +class SurfaceControl : public RefBase +{ +public: + static bool isValid(const sp& surface) { + return (surface != 0) && surface->isValid(); + } + + bool isValid() { + return mHandle!=0 && mClient!=0; + } + + static bool isSameSurface( + const sp& lhs, const sp& 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& control, Parcel* parcel); + + sp getSurface() const; + + status_t clearLayerFrameStats() const; + status_t getLayerFrameStats(FrameStats* outStats) const; + + status_t setBlur(float blur = 0); + status_t setBlurMaskSurface(const sp& 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& client, + const sp& handle, + const sp& gbp); + + ~SurfaceControl(); + + status_t validate() const; + void destroy(); + + sp mClient; + sp mHandle; + sp mGraphicBufferProducer; + mutable Mutex mLock; + mutable sp mSurfaceData; +}; + +}; // namespace android + +#endif // ANDROID_GUI_SURFACE_CONTROL_H diff --git a/phonelibs/android_frameworks_native/include/input/IInputFlinger.h b/phonelibs/android_frameworks_native/include/input/IInputFlinger.h new file mode 100644 index 0000000000..629310ff2f --- /dev/null +++ b/phonelibs/android_frameworks_native/include/input/IInputFlinger.h @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _LIBINPUT_IINPUT_FLINGER_H +#define _LIBINPUT_IINPUT_FLINGER_H + +#include +#include + +#include + +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 { +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 diff --git a/phonelibs/android_frameworks_native/include/input/Input.h b/phonelibs/android_frameworks_native/include/input/Input.h new file mode 100644 index 0000000000..82fc6599a7 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/input/Input.h @@ -0,0 +1,681 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _LIBINPUT_INPUT_H +#define _LIBINPUT_INPUT_H + +/** + * Native input event structures. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Additional private constants not defined in ndk/ui/input.h. + */ +enum { + /* Signifies that the key is being predispatched */ + AKEY_EVENT_FLAG_PREDISPATCH = 0x20000000, + + /* Private control to determine when an app is tracking a key sequence. */ + AKEY_EVENT_FLAG_START_TRACKING = 0x40000000, + + /* Key event is inconsistent with previously sent key events. */ + AKEY_EVENT_FLAG_TAINTED = 0x80000000, +}; + +enum { + + /** + * This flag indicates that the window that received this motion event is partly + * or wholly obscured by another visible window above it. This flag is set to true + * even if the event did not directly pass through the obscured area. + * A security sensitive application can check this flag to identify situations in which + * a malicious application may have covered up part of its content for the purpose + * of misleading the user or hijacking touches. An appropriate response might be + * to drop the suspect touches or to take additional precautions to confirm the user's + * actual intent. + */ + AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED = 0x2, + + /* Motion event is inconsistent with previously sent motion events. */ + AMOTION_EVENT_FLAG_TAINTED = 0x80000000, +}; + +enum { + /* Used when a motion event is not associated with any display. + * Typically used for non-pointer events. */ + ADISPLAY_ID_NONE = -1, + + /* The default display id. */ + ADISPLAY_ID_DEFAULT = 0, +}; + +enum { + /* + * Indicates that an input device has switches. + * This input source flag is hidden from the API because switches are only used by the system + * and applications have no way to interact with them. + */ + AINPUT_SOURCE_SWITCH = 0x80000000, +}; + +enum { + /** + * Constants for LEDs. Hidden from the API since we don't actually expose a way to interact + * with LEDs to developers + * + * NOTE: If you add LEDs here, you must also add them to InputEventLabels.h + */ + + ALED_NUM_LOCK = 0x00, + ALED_CAPS_LOCK = 0x01, + ALED_SCROLL_LOCK = 0x02, + ALED_COMPOSE = 0x03, + ALED_KANA = 0x04, + ALED_SLEEP = 0x05, + ALED_SUSPEND = 0x06, + ALED_MUTE = 0x07, + ALED_MISC = 0x08, + ALED_MAIL = 0x09, + ALED_CHARGING = 0x0a, + ALED_CONTROLLER_1 = 0x10, + ALED_CONTROLLER_2 = 0x11, + ALED_CONTROLLER_3 = 0x12, + ALED_CONTROLLER_4 = 0x13, +}; + +/* Maximum number of controller LEDs we support */ +#define MAX_CONTROLLER_LEDS 4 + +/* + * SystemUiVisibility constants from View. + */ +enum { + ASYSTEM_UI_VISIBILITY_STATUS_BAR_VISIBLE = 0, + ASYSTEM_UI_VISIBILITY_STATUS_BAR_HIDDEN = 0x00000001, +}; + +/* + * Maximum number of pointers supported per motion event. + * Smallest number of pointers is 1. + * (We want at least 10 but some touch controllers obstensibly configured for 10 pointers + * will occasionally emit 11. There is not much harm making this constant bigger.) + */ +#define MAX_POINTERS 16 + +/* + * Maximum number of samples supported per motion event. + */ +#define MAX_SAMPLES UINT16_MAX + +/* + * Maximum pointer id value supported in a motion event. + * Smallest pointer id is 0. + * (This is limited by our use of BitSet32 to track pointer assignments.) + */ +#define MAX_POINTER_ID 31 + +/* + * Declare a concrete type for the NDK's input event forward declaration. + */ +struct AInputEvent { + virtual ~AInputEvent() { } +}; + +/* + * Declare a concrete type for the NDK's input device forward declaration. + */ +struct AInputDevice { + virtual ~AInputDevice() { } +}; + + +namespace android { + +#ifdef HAVE_ANDROID_OS +class Parcel; +#endif + +/* + * Flags that flow alongside events in the input dispatch system to help with certain + * policy decisions such as waking from device sleep. + * + * These flags are also defined in frameworks/base/core/java/android/view/WindowManagerPolicy.java. + */ +enum { + /* These flags originate in RawEvents and are generally set in the key map. + * NOTE: If you want a flag to be able to set in a keylayout file, then you must add it to + * InputEventLabels.h as well. */ + + // Indicates that the event should wake the device. + POLICY_FLAG_WAKE = 0x00000001, + + // Indicates that the key is virtual, such as a capacitive button, and should + // generate haptic feedback. Virtual keys may be suppressed for some time + // after a recent touch to prevent accidental activation of virtual keys adjacent + // to the touch screen during an edge swipe. + POLICY_FLAG_VIRTUAL = 0x00000002, + + // Indicates that the key is the special function modifier. + POLICY_FLAG_FUNCTION = 0x00000004, + + // Indicates that the key represents a special gesture that has been detected by + // the touch firmware or driver. Causes touch events from the same device to be canceled. + POLICY_FLAG_GESTURE = 0x00000008, + + POLICY_FLAG_RAW_MASK = 0x0000ffff, + + /* These flags are set by the input dispatcher. */ + + // Indicates that the input event was injected. + POLICY_FLAG_INJECTED = 0x01000000, + + // Indicates that the input event is from a trusted source such as a directly attached + // input device or an application with system-wide event injection permission. + POLICY_FLAG_TRUSTED = 0x02000000, + + // Indicates that the input event has passed through an input filter. + POLICY_FLAG_FILTERED = 0x04000000, + + // Disables automatic key repeating behavior. + POLICY_FLAG_DISABLE_KEY_REPEAT = 0x08000000, + + /* These flags are set by the input reader policy as it intercepts each event. */ + + // Indicates that the device was in an interactive state when the + // event was intercepted. + POLICY_FLAG_INTERACTIVE = 0x20000000, + + // Indicates that the event should be dispatched to applications. + // The input event should still be sent to the InputDispatcher so that it can see all + // input events received include those that it will not deliver. + POLICY_FLAG_PASS_TO_USER = 0x40000000, +}; + +/* + * Pointer coordinate data. + */ +struct PointerCoords { + enum { MAX_AXES = 30 }; // 30 so that sizeof(PointerCoords) == 128 + + // Bitfield of axes that are present in this structure. + uint64_t bits __attribute__((aligned(8))); + + // Values of axes that are stored in this structure packed in order by axis id + // for each axis that is present in the structure according to 'bits'. + float values[MAX_AXES]; + + inline void clear() { + BitSet64::clear(bits); + } + + bool isEmpty() const { + return BitSet64::isEmpty(bits); + } + + float getAxisValue(int32_t axis) const; + status_t setAxisValue(int32_t axis, float value); + + void scale(float scale); + void applyOffset(float xOffset, float yOffset); + + inline float getX() const { + return getAxisValue(AMOTION_EVENT_AXIS_X); + } + + inline float getY() const { + return getAxisValue(AMOTION_EVENT_AXIS_Y); + } + +#ifdef HAVE_ANDROID_OS + status_t readFromParcel(Parcel* parcel); + status_t writeToParcel(Parcel* parcel) const; +#endif + + bool operator==(const PointerCoords& other) const; + inline bool operator!=(const PointerCoords& other) const { + return !(*this == other); + } + + void copyFrom(const PointerCoords& other); + +private: + void tooManyAxes(int axis); +}; + +/* + * Pointer property data. + */ +struct PointerProperties { + // The id of the pointer. + int32_t id; + + // The pointer tool type. + int32_t toolType; + + inline void clear() { + id = -1; + toolType = 0; + } + + bool operator==(const PointerProperties& other) const; + inline bool operator!=(const PointerProperties& other) const { + return !(*this == other); + } + + void copyFrom(const PointerProperties& other); +}; + +/* + * Input events. + */ +class InputEvent : public AInputEvent { +public: + virtual ~InputEvent() { } + + virtual int32_t getType() const = 0; + + inline int32_t getDeviceId() const { return mDeviceId; } + + inline int32_t getSource() const { return mSource; } + + inline void setSource(int32_t source) { mSource = source; } + +protected: + void initialize(int32_t deviceId, int32_t source); + void initialize(const InputEvent& from); + + int32_t mDeviceId; + int32_t mSource; +}; + +/* + * Key events. + */ +class KeyEvent : public InputEvent { +public: + virtual ~KeyEvent() { } + + virtual int32_t getType() const { return AINPUT_EVENT_TYPE_KEY; } + + inline int32_t getAction() const { return mAction; } + + inline int32_t getFlags() const { return mFlags; } + + inline void setFlags(int32_t flags) { mFlags = flags; } + + inline int32_t getKeyCode() const { return mKeyCode; } + + inline int32_t getScanCode() const { return mScanCode; } + + inline int32_t getMetaState() const { return mMetaState; } + + inline int32_t getRepeatCount() const { return mRepeatCount; } + + inline nsecs_t getDownTime() const { return mDownTime; } + + inline nsecs_t getEventTime() const { return mEventTime; } + + static const char* getLabel(int32_t keyCode); + static int32_t getKeyCodeFromLabel(const char* label); + + void initialize( + int32_t deviceId, + int32_t source, + int32_t action, + int32_t flags, + int32_t keyCode, + int32_t scanCode, + int32_t metaState, + int32_t repeatCount, + nsecs_t downTime, + nsecs_t eventTime); + void initialize(const KeyEvent& from); + +protected: + int32_t mAction; + int32_t mFlags; + int32_t mKeyCode; + int32_t mScanCode; + int32_t mMetaState; + int32_t mRepeatCount; + nsecs_t mDownTime; + nsecs_t mEventTime; +}; + +/* + * Motion events. + */ +class MotionEvent : public InputEvent { +public: + virtual ~MotionEvent() { } + + virtual int32_t getType() const { return AINPUT_EVENT_TYPE_MOTION; } + + inline int32_t getAction() const { return mAction; } + + inline int32_t getActionMasked() const { return mAction & AMOTION_EVENT_ACTION_MASK; } + + inline int32_t getActionIndex() const { + return (mAction & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) + >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; + } + + inline void setAction(int32_t action) { mAction = action; } + + inline int32_t getFlags() const { return mFlags; } + + inline void setFlags(int32_t flags) { mFlags = flags; } + + inline int32_t getEdgeFlags() const { return mEdgeFlags; } + + inline void setEdgeFlags(int32_t edgeFlags) { mEdgeFlags = edgeFlags; } + + inline int32_t getMetaState() const { return mMetaState; } + + inline void setMetaState(int32_t metaState) { mMetaState = metaState; } + + inline int32_t getButtonState() const { return mButtonState; } + + inline int32_t setButtonState(int32_t buttonState) { mButtonState = buttonState; } + + inline int32_t getActionButton() const { return mActionButton; } + + inline void setActionButton(int32_t button) { mActionButton = button; } + + inline float getXOffset() const { return mXOffset; } + + inline float getYOffset() const { return mYOffset; } + + inline float getXPrecision() const { return mXPrecision; } + + inline float getYPrecision() const { return mYPrecision; } + + inline nsecs_t getDownTime() const { return mDownTime; } + + inline void setDownTime(nsecs_t downTime) { mDownTime = downTime; } + + inline size_t getPointerCount() const { return mPointerProperties.size(); } + + inline const PointerProperties* getPointerProperties(size_t pointerIndex) const { + return &mPointerProperties[pointerIndex]; + } + + inline int32_t getPointerId(size_t pointerIndex) const { + return mPointerProperties[pointerIndex].id; + } + + inline int32_t getToolType(size_t pointerIndex) const { + return mPointerProperties[pointerIndex].toolType; + } + + inline nsecs_t getEventTime() const { return mSampleEventTimes[getHistorySize()]; } + + const PointerCoords* getRawPointerCoords(size_t pointerIndex) const; + + float getRawAxisValue(int32_t axis, size_t pointerIndex) const; + + inline float getRawX(size_t pointerIndex) const { + return getRawAxisValue(AMOTION_EVENT_AXIS_X, pointerIndex); + } + + inline float getRawY(size_t pointerIndex) const { + return getRawAxisValue(AMOTION_EVENT_AXIS_Y, pointerIndex); + } + + float getAxisValue(int32_t axis, size_t pointerIndex) const; + + inline float getX(size_t pointerIndex) const { + return getAxisValue(AMOTION_EVENT_AXIS_X, pointerIndex); + } + + inline float getY(size_t pointerIndex) const { + return getAxisValue(AMOTION_EVENT_AXIS_Y, pointerIndex); + } + + inline float getPressure(size_t pointerIndex) const { + return getAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pointerIndex); + } + + inline float getSize(size_t pointerIndex) const { + return getAxisValue(AMOTION_EVENT_AXIS_SIZE, pointerIndex); + } + + inline float getTouchMajor(size_t pointerIndex) const { + return getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, pointerIndex); + } + + inline float getTouchMinor(size_t pointerIndex) const { + return getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, pointerIndex); + } + + inline float getToolMajor(size_t pointerIndex) const { + return getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, pointerIndex); + } + + inline float getToolMinor(size_t pointerIndex) const { + return getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, pointerIndex); + } + + inline float getOrientation(size_t pointerIndex) const { + return getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, pointerIndex); + } + + inline size_t getHistorySize() const { return mSampleEventTimes.size() - 1; } + + inline nsecs_t getHistoricalEventTime(size_t historicalIndex) const { + return mSampleEventTimes[historicalIndex]; + } + + const PointerCoords* getHistoricalRawPointerCoords( + size_t pointerIndex, size_t historicalIndex) const; + + float getHistoricalRawAxisValue(int32_t axis, size_t pointerIndex, + size_t historicalIndex) const; + + inline float getHistoricalRawX(size_t pointerIndex, size_t historicalIndex) const { + return getHistoricalRawAxisValue( + AMOTION_EVENT_AXIS_X, pointerIndex, historicalIndex); + } + + inline float getHistoricalRawY(size_t pointerIndex, size_t historicalIndex) const { + return getHistoricalRawAxisValue( + AMOTION_EVENT_AXIS_Y, pointerIndex, historicalIndex); + } + + float getHistoricalAxisValue(int32_t axis, size_t pointerIndex, size_t historicalIndex) const; + + inline float getHistoricalX(size_t pointerIndex, size_t historicalIndex) const { + return getHistoricalAxisValue( + AMOTION_EVENT_AXIS_X, pointerIndex, historicalIndex); + } + + inline float getHistoricalY(size_t pointerIndex, size_t historicalIndex) const { + return getHistoricalAxisValue( + AMOTION_EVENT_AXIS_Y, pointerIndex, historicalIndex); + } + + inline float getHistoricalPressure(size_t pointerIndex, size_t historicalIndex) const { + return getHistoricalAxisValue( + AMOTION_EVENT_AXIS_PRESSURE, pointerIndex, historicalIndex); + } + + inline float getHistoricalSize(size_t pointerIndex, size_t historicalIndex) const { + return getHistoricalAxisValue( + AMOTION_EVENT_AXIS_SIZE, pointerIndex, historicalIndex); + } + + inline float getHistoricalTouchMajor(size_t pointerIndex, size_t historicalIndex) const { + return getHistoricalAxisValue( + AMOTION_EVENT_AXIS_TOUCH_MAJOR, pointerIndex, historicalIndex); + } + + inline float getHistoricalTouchMinor(size_t pointerIndex, size_t historicalIndex) const { + return getHistoricalAxisValue( + AMOTION_EVENT_AXIS_TOUCH_MINOR, pointerIndex, historicalIndex); + } + + inline float getHistoricalToolMajor(size_t pointerIndex, size_t historicalIndex) const { + return getHistoricalAxisValue( + AMOTION_EVENT_AXIS_TOOL_MAJOR, pointerIndex, historicalIndex); + } + + inline float getHistoricalToolMinor(size_t pointerIndex, size_t historicalIndex) const { + return getHistoricalAxisValue( + AMOTION_EVENT_AXIS_TOOL_MINOR, pointerIndex, historicalIndex); + } + + inline float getHistoricalOrientation(size_t pointerIndex, size_t historicalIndex) const { + return getHistoricalAxisValue( + AMOTION_EVENT_AXIS_ORIENTATION, pointerIndex, historicalIndex); + } + + ssize_t findPointerIndex(int32_t pointerId) const; + + void initialize( + int32_t deviceId, + int32_t source, + int32_t action, + int32_t actionButton, + int32_t flags, + int32_t edgeFlags, + int32_t metaState, + int32_t buttonState, + float xOffset, + float yOffset, + float xPrecision, + float yPrecision, + nsecs_t downTime, + nsecs_t eventTime, + size_t pointerCount, + const PointerProperties* pointerProperties, + const PointerCoords* pointerCoords); + + void copyFrom(const MotionEvent* other, bool keepHistory); + + void addSample( + nsecs_t eventTime, + const PointerCoords* pointerCoords); + + void offsetLocation(float xOffset, float yOffset); + + void scale(float scaleFactor); + + // Apply 3x3 perspective matrix transformation. + // Matrix is in row-major form and compatible with SkMatrix. + void transform(const float matrix[9]); + +#ifdef HAVE_ANDROID_OS + status_t readFromParcel(Parcel* parcel); + status_t writeToParcel(Parcel* parcel) const; +#endif + + static bool isTouchEvent(int32_t source, int32_t action); + inline bool isTouchEvent() const { + return isTouchEvent(mSource, mAction); + } + + // Low-level accessors. + inline const PointerProperties* getPointerProperties() const { + return mPointerProperties.array(); + } + inline const nsecs_t* getSampleEventTimes() const { return mSampleEventTimes.array(); } + inline const PointerCoords* getSamplePointerCoords() const { + return mSamplePointerCoords.array(); + } + + static const char* getLabel(int32_t axis); + static int32_t getAxisFromLabel(const char* label); + +protected: + int32_t mAction; + int32_t mActionButton; + int32_t mFlags; + int32_t mEdgeFlags; + int32_t mMetaState; + int32_t mButtonState; + float mXOffset; + float mYOffset; + float mXPrecision; + float mYPrecision; + nsecs_t mDownTime; + Vector mPointerProperties; + Vector mSampleEventTimes; + Vector mSamplePointerCoords; +}; + +/* + * Input event factory. + */ +class InputEventFactoryInterface { +protected: + virtual ~InputEventFactoryInterface() { } + +public: + InputEventFactoryInterface() { } + + virtual KeyEvent* createKeyEvent() = 0; + virtual MotionEvent* createMotionEvent() = 0; +}; + +/* + * A simple input event factory implementation that uses a single preallocated instance + * of each type of input event that are reused for each request. + */ +class PreallocatedInputEventFactory : public InputEventFactoryInterface { +public: + PreallocatedInputEventFactory() { } + virtual ~PreallocatedInputEventFactory() { } + + virtual KeyEvent* createKeyEvent() { return & mKeyEvent; } + virtual MotionEvent* createMotionEvent() { return & mMotionEvent; } + +private: + KeyEvent mKeyEvent; + MotionEvent mMotionEvent; +}; + +/* + * An input event factory implementation that maintains a pool of input events. + */ +class PooledInputEventFactory : public InputEventFactoryInterface { +public: + PooledInputEventFactory(size_t maxPoolSize = 20); + virtual ~PooledInputEventFactory(); + + virtual KeyEvent* createKeyEvent(); + virtual MotionEvent* createMotionEvent(); + + void recycle(InputEvent* event); + +private: + const size_t mMaxPoolSize; + + Vector mKeyEventPool; + Vector mMotionEventPool; +}; + +} // namespace android + +#endif // _LIBINPUT_INPUT_H diff --git a/phonelibs/android_frameworks_native/include/input/InputDevice.h b/phonelibs/android_frameworks_native/include/input/InputDevice.h new file mode 100644 index 0000000000..1ea69d352d --- /dev/null +++ b/phonelibs/android_frameworks_native/include/input/InputDevice.h @@ -0,0 +1,170 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _LIBINPUT_INPUT_DEVICE_H +#define _LIBINPUT_INPUT_DEVICE_H + +#include +#include + +namespace android { + +/* + * Identifies a device. + */ +struct InputDeviceIdentifier { + inline InputDeviceIdentifier() : + bus(0), vendor(0), product(0), version(0) { + } + + // Information provided by the kernel. + String8 name; + String8 location; + String8 uniqueId; + uint16_t bus; + uint16_t vendor; + uint16_t product; + uint16_t version; + + // A composite input device descriptor string that uniquely identifies the device + // even across reboots or reconnections. The value of this field is used by + // upper layers of the input system to associate settings with individual devices. + // It is hashed from whatever kernel provided information is available. + // Ideally, the way this value is computed should not change between Android releases + // because that would invalidate persistent settings that rely on it. + String8 descriptor; + + // A value added to uniquely identify a device in the absence of a unique id. This + // is intended to be a minimum way to distinguish from other active devices and may + // reuse values that are not associated with an input anymore. + uint16_t nonce; +}; + +/* + * Describes the characteristics and capabilities of an input device. + */ +class InputDeviceInfo { +public: + InputDeviceInfo(); + InputDeviceInfo(const InputDeviceInfo& other); + ~InputDeviceInfo(); + + struct MotionRange { + int32_t axis; + uint32_t source; + float min; + float max; + float flat; + float fuzz; + float resolution; + }; + + void initialize(int32_t id, int32_t generation, int32_t controllerNumber, + const InputDeviceIdentifier& identifier, const String8& alias, bool isExternal, + bool hasMic); + + inline int32_t getId() const { return mId; } + inline int32_t getControllerNumber() const { return mControllerNumber; } + inline int32_t getGeneration() const { return mGeneration; } + inline const InputDeviceIdentifier& getIdentifier() const { return mIdentifier; } + inline const String8& getAlias() const { return mAlias; } + inline const String8& getDisplayName() const { + return mAlias.isEmpty() ? mIdentifier.name : mAlias; + } + inline bool isExternal() const { return mIsExternal; } + inline bool hasMic() const { return mHasMic; } + inline uint32_t getSources() const { return mSources; } + + const MotionRange* getMotionRange(int32_t axis, uint32_t source) const; + + void addSource(uint32_t source); + void addMotionRange(int32_t axis, uint32_t source, + float min, float max, float flat, float fuzz, float resolution); + void addMotionRange(const MotionRange& range); + + inline void setKeyboardType(int32_t keyboardType) { mKeyboardType = keyboardType; } + inline int32_t getKeyboardType() const { return mKeyboardType; } + + inline void setKeyCharacterMap(const sp& value) { + mKeyCharacterMap = value; + } + + inline sp getKeyCharacterMap() const { + return mKeyCharacterMap; + } + + inline void setVibrator(bool hasVibrator) { mHasVibrator = hasVibrator; } + inline bool hasVibrator() const { return mHasVibrator; } + + inline void setButtonUnderPad(bool hasButton) { mHasButtonUnderPad = hasButton; } + inline bool hasButtonUnderPad() const { return mHasButtonUnderPad; } + + inline const Vector& getMotionRanges() const { + return mMotionRanges; + } + +private: + int32_t mId; + int32_t mGeneration; + int32_t mControllerNumber; + InputDeviceIdentifier mIdentifier; + String8 mAlias; + bool mIsExternal; + bool mHasMic; + uint32_t mSources; + int32_t mKeyboardType; + sp mKeyCharacterMap; + bool mHasVibrator; + bool mHasButtonUnderPad; + + Vector mMotionRanges; +}; + +/* Types of input device configuration files. */ +enum InputDeviceConfigurationFileType { + INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION = 0, /* .idc file */ + INPUT_DEVICE_CONFIGURATION_FILE_TYPE_KEY_LAYOUT = 1, /* .kl file */ + INPUT_DEVICE_CONFIGURATION_FILE_TYPE_KEY_CHARACTER_MAP = 2, /* .kcm file */ +}; + +/* + * Gets the path of an input device configuration file, if one is available. + * Considers both system provided and user installed configuration files. + * + * The device identifier is used to construct several default configuration file + * names to try based on the device name, vendor, product, and version. + * + * Returns an empty string if not found. + */ +extern String8 getInputDeviceConfigurationFilePathByDeviceIdentifier( + const InputDeviceIdentifier& deviceIdentifier, + InputDeviceConfigurationFileType type); + +/* + * Gets the path of an input device configuration file, if one is available. + * Considers both system provided and user installed configuration files. + * + * The name is case-sensitive and is used to construct the filename to resolve. + * All characters except 'a'-'z', 'A'-'Z', '0'-'9', '-', and '_' are replaced by underscores. + * + * Returns an empty string if not found. + */ +extern String8 getInputDeviceConfigurationFilePathByName( + const String8& name, InputDeviceConfigurationFileType type); + +} // namespace android + +#endif // _LIBINPUT_INPUT_DEVICE_H diff --git a/phonelibs/android_frameworks_native/include/input/InputEventLabels.h b/phonelibs/android_frameworks_native/include/input/InputEventLabels.h new file mode 100644 index 0000000000..c03c0f2d58 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/input/InputEventLabels.h @@ -0,0 +1,447 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _LIBINPUT_INPUT_EVENT_LABELS_H +#define _LIBINPUT_INPUT_EVENT_LABELS_H + +#include +#include + +#define DEFINE_KEYCODE(key) { #key, AKEYCODE_##key } +#define DEFINE_AXIS(axis) { #axis, AMOTION_EVENT_AXIS_##axis } +#define DEFINE_LED(led) { #led, ALED_##led } +#define DEFINE_FLAG(flag) { #flag, POLICY_FLAG_##flag } + +namespace android { + +template +size_t size(T (&)[N]) { return N; } + +struct InputEventLabel { + const char *literal; + int value; +}; + + +static const InputEventLabel KEYCODES[] = { + // NOTE: If you add a new keycode here you must also add it to several other files. + // Refer to frameworks/base/core/java/android/view/KeyEvent.java for the full list. + DEFINE_KEYCODE(UNKNOWN), + DEFINE_KEYCODE(SOFT_LEFT), + DEFINE_KEYCODE(SOFT_RIGHT), + DEFINE_KEYCODE(HOME), + DEFINE_KEYCODE(BACK), + DEFINE_KEYCODE(CALL), + DEFINE_KEYCODE(ENDCALL), + DEFINE_KEYCODE(0), + DEFINE_KEYCODE(1), + DEFINE_KEYCODE(2), + DEFINE_KEYCODE(3), + DEFINE_KEYCODE(4), + DEFINE_KEYCODE(5), + DEFINE_KEYCODE(6), + DEFINE_KEYCODE(7), + DEFINE_KEYCODE(8), + DEFINE_KEYCODE(9), + DEFINE_KEYCODE(STAR), + DEFINE_KEYCODE(POUND), + DEFINE_KEYCODE(DPAD_UP), + DEFINE_KEYCODE(DPAD_DOWN), + DEFINE_KEYCODE(DPAD_LEFT), + DEFINE_KEYCODE(DPAD_RIGHT), + DEFINE_KEYCODE(DPAD_CENTER), + DEFINE_KEYCODE(VOLUME_UP), + DEFINE_KEYCODE(VOLUME_DOWN), + DEFINE_KEYCODE(POWER), + DEFINE_KEYCODE(CAMERA), + DEFINE_KEYCODE(CLEAR), + DEFINE_KEYCODE(A), + DEFINE_KEYCODE(B), + DEFINE_KEYCODE(C), + DEFINE_KEYCODE(D), + DEFINE_KEYCODE(E), + DEFINE_KEYCODE(F), + DEFINE_KEYCODE(G), + DEFINE_KEYCODE(H), + DEFINE_KEYCODE(I), + DEFINE_KEYCODE(J), + DEFINE_KEYCODE(K), + DEFINE_KEYCODE(L), + DEFINE_KEYCODE(M), + DEFINE_KEYCODE(N), + DEFINE_KEYCODE(O), + DEFINE_KEYCODE(P), + DEFINE_KEYCODE(Q), + DEFINE_KEYCODE(R), + DEFINE_KEYCODE(S), + DEFINE_KEYCODE(T), + DEFINE_KEYCODE(U), + DEFINE_KEYCODE(V), + DEFINE_KEYCODE(W), + DEFINE_KEYCODE(X), + DEFINE_KEYCODE(Y), + DEFINE_KEYCODE(Z), + DEFINE_KEYCODE(COMMA), + DEFINE_KEYCODE(PERIOD), + DEFINE_KEYCODE(ALT_LEFT), + DEFINE_KEYCODE(ALT_RIGHT), + DEFINE_KEYCODE(SHIFT_LEFT), + DEFINE_KEYCODE(SHIFT_RIGHT), + DEFINE_KEYCODE(TAB), + DEFINE_KEYCODE(SPACE), + DEFINE_KEYCODE(SYM), + DEFINE_KEYCODE(EXPLORER), + DEFINE_KEYCODE(ENVELOPE), + DEFINE_KEYCODE(ENTER), + DEFINE_KEYCODE(DEL), + DEFINE_KEYCODE(GRAVE), + DEFINE_KEYCODE(MINUS), + DEFINE_KEYCODE(EQUALS), + DEFINE_KEYCODE(LEFT_BRACKET), + DEFINE_KEYCODE(RIGHT_BRACKET), + DEFINE_KEYCODE(BACKSLASH), + DEFINE_KEYCODE(SEMICOLON), + DEFINE_KEYCODE(APOSTROPHE), + DEFINE_KEYCODE(SLASH), + DEFINE_KEYCODE(AT), + DEFINE_KEYCODE(NUM), + DEFINE_KEYCODE(HEADSETHOOK), + DEFINE_KEYCODE(FOCUS), // *Camera* focus + DEFINE_KEYCODE(PLUS), + DEFINE_KEYCODE(MENU), + DEFINE_KEYCODE(NOTIFICATION), + DEFINE_KEYCODE(SEARCH), + DEFINE_KEYCODE(MEDIA_PLAY_PAUSE), + DEFINE_KEYCODE(MEDIA_STOP), + DEFINE_KEYCODE(MEDIA_NEXT), + DEFINE_KEYCODE(MEDIA_PREVIOUS), + DEFINE_KEYCODE(MEDIA_REWIND), + DEFINE_KEYCODE(MEDIA_FAST_FORWARD), + DEFINE_KEYCODE(MUTE), + DEFINE_KEYCODE(PAGE_UP), + DEFINE_KEYCODE(PAGE_DOWN), + DEFINE_KEYCODE(PICTSYMBOLS), + DEFINE_KEYCODE(SWITCH_CHARSET), + DEFINE_KEYCODE(BUTTON_A), + DEFINE_KEYCODE(BUTTON_B), + DEFINE_KEYCODE(BUTTON_C), + DEFINE_KEYCODE(BUTTON_X), + DEFINE_KEYCODE(BUTTON_Y), + DEFINE_KEYCODE(BUTTON_Z), + DEFINE_KEYCODE(BUTTON_L1), + DEFINE_KEYCODE(BUTTON_R1), + DEFINE_KEYCODE(BUTTON_L2), + DEFINE_KEYCODE(BUTTON_R2), + DEFINE_KEYCODE(BUTTON_THUMBL), + DEFINE_KEYCODE(BUTTON_THUMBR), + DEFINE_KEYCODE(BUTTON_START), + DEFINE_KEYCODE(BUTTON_SELECT), + DEFINE_KEYCODE(BUTTON_MODE), + DEFINE_KEYCODE(ESCAPE), + DEFINE_KEYCODE(FORWARD_DEL), + DEFINE_KEYCODE(CTRL_LEFT), + DEFINE_KEYCODE(CTRL_RIGHT), + DEFINE_KEYCODE(CAPS_LOCK), + DEFINE_KEYCODE(SCROLL_LOCK), + DEFINE_KEYCODE(META_LEFT), + DEFINE_KEYCODE(META_RIGHT), + DEFINE_KEYCODE(FUNCTION), + DEFINE_KEYCODE(SYSRQ), + DEFINE_KEYCODE(BREAK), + DEFINE_KEYCODE(MOVE_HOME), + DEFINE_KEYCODE(MOVE_END), + DEFINE_KEYCODE(INSERT), + DEFINE_KEYCODE(FORWARD), + DEFINE_KEYCODE(MEDIA_PLAY), + DEFINE_KEYCODE(MEDIA_PAUSE), + DEFINE_KEYCODE(MEDIA_CLOSE), + DEFINE_KEYCODE(MEDIA_EJECT), + DEFINE_KEYCODE(MEDIA_RECORD), + DEFINE_KEYCODE(F1), + DEFINE_KEYCODE(F2), + DEFINE_KEYCODE(F3), + DEFINE_KEYCODE(F4), + DEFINE_KEYCODE(F5), + DEFINE_KEYCODE(F6), + DEFINE_KEYCODE(F7), + DEFINE_KEYCODE(F8), + DEFINE_KEYCODE(F9), + DEFINE_KEYCODE(F10), + DEFINE_KEYCODE(F11), + DEFINE_KEYCODE(F12), + DEFINE_KEYCODE(NUM_LOCK), + DEFINE_KEYCODE(NUMPAD_0), + DEFINE_KEYCODE(NUMPAD_1), + DEFINE_KEYCODE(NUMPAD_2), + DEFINE_KEYCODE(NUMPAD_3), + DEFINE_KEYCODE(NUMPAD_4), + DEFINE_KEYCODE(NUMPAD_5), + DEFINE_KEYCODE(NUMPAD_6), + DEFINE_KEYCODE(NUMPAD_7), + DEFINE_KEYCODE(NUMPAD_8), + DEFINE_KEYCODE(NUMPAD_9), + DEFINE_KEYCODE(NUMPAD_DIVIDE), + DEFINE_KEYCODE(NUMPAD_MULTIPLY), + DEFINE_KEYCODE(NUMPAD_SUBTRACT), + DEFINE_KEYCODE(NUMPAD_ADD), + DEFINE_KEYCODE(NUMPAD_DOT), + DEFINE_KEYCODE(NUMPAD_COMMA), + DEFINE_KEYCODE(NUMPAD_ENTER), + DEFINE_KEYCODE(NUMPAD_EQUALS), + DEFINE_KEYCODE(NUMPAD_LEFT_PAREN), + DEFINE_KEYCODE(NUMPAD_RIGHT_PAREN), + DEFINE_KEYCODE(VOLUME_MUTE), + DEFINE_KEYCODE(INFO), + DEFINE_KEYCODE(CHANNEL_UP), + DEFINE_KEYCODE(CHANNEL_DOWN), + DEFINE_KEYCODE(ZOOM_IN), + DEFINE_KEYCODE(ZOOM_OUT), + DEFINE_KEYCODE(TV), + DEFINE_KEYCODE(WINDOW), + DEFINE_KEYCODE(GUIDE), + DEFINE_KEYCODE(DVR), + DEFINE_KEYCODE(BOOKMARK), + DEFINE_KEYCODE(CAPTIONS), + DEFINE_KEYCODE(SETTINGS), + DEFINE_KEYCODE(TV_POWER), + DEFINE_KEYCODE(TV_INPUT), + DEFINE_KEYCODE(STB_POWER), + DEFINE_KEYCODE(STB_INPUT), + DEFINE_KEYCODE(AVR_POWER), + DEFINE_KEYCODE(AVR_INPUT), + DEFINE_KEYCODE(PROG_RED), + DEFINE_KEYCODE(PROG_GREEN), + DEFINE_KEYCODE(PROG_YELLOW), + DEFINE_KEYCODE(PROG_BLUE), + DEFINE_KEYCODE(APP_SWITCH), + DEFINE_KEYCODE(BUTTON_1), + DEFINE_KEYCODE(BUTTON_2), + DEFINE_KEYCODE(BUTTON_3), + DEFINE_KEYCODE(BUTTON_4), + DEFINE_KEYCODE(BUTTON_5), + DEFINE_KEYCODE(BUTTON_6), + DEFINE_KEYCODE(BUTTON_7), + DEFINE_KEYCODE(BUTTON_8), + DEFINE_KEYCODE(BUTTON_9), + DEFINE_KEYCODE(BUTTON_10), + DEFINE_KEYCODE(BUTTON_11), + DEFINE_KEYCODE(BUTTON_12), + DEFINE_KEYCODE(BUTTON_13), + DEFINE_KEYCODE(BUTTON_14), + DEFINE_KEYCODE(BUTTON_15), + DEFINE_KEYCODE(BUTTON_16), + DEFINE_KEYCODE(LANGUAGE_SWITCH), + DEFINE_KEYCODE(MANNER_MODE), + DEFINE_KEYCODE(3D_MODE), + DEFINE_KEYCODE(CONTACTS), + DEFINE_KEYCODE(CALENDAR), + DEFINE_KEYCODE(MUSIC), + DEFINE_KEYCODE(CALCULATOR), + DEFINE_KEYCODE(ZENKAKU_HANKAKU), + DEFINE_KEYCODE(EISU), + DEFINE_KEYCODE(MUHENKAN), + DEFINE_KEYCODE(HENKAN), + DEFINE_KEYCODE(KATAKANA_HIRAGANA), + DEFINE_KEYCODE(YEN), + DEFINE_KEYCODE(RO), + DEFINE_KEYCODE(KANA), + DEFINE_KEYCODE(ASSIST), + DEFINE_KEYCODE(BRIGHTNESS_DOWN), + DEFINE_KEYCODE(BRIGHTNESS_UP), + DEFINE_KEYCODE(MEDIA_AUDIO_TRACK), + DEFINE_KEYCODE(SLEEP), + DEFINE_KEYCODE(WAKEUP), + DEFINE_KEYCODE(PAIRING), + DEFINE_KEYCODE(MEDIA_TOP_MENU), + DEFINE_KEYCODE(11), + DEFINE_KEYCODE(12), + DEFINE_KEYCODE(LAST_CHANNEL), + DEFINE_KEYCODE(TV_DATA_SERVICE), + DEFINE_KEYCODE(VOICE_ASSIST), + DEFINE_KEYCODE(TV_RADIO_SERVICE), + DEFINE_KEYCODE(TV_TELETEXT), + DEFINE_KEYCODE(TV_NUMBER_ENTRY), + DEFINE_KEYCODE(TV_TERRESTRIAL_ANALOG), + DEFINE_KEYCODE(TV_TERRESTRIAL_DIGITAL), + DEFINE_KEYCODE(TV_SATELLITE), + DEFINE_KEYCODE(TV_SATELLITE_BS), + DEFINE_KEYCODE(TV_SATELLITE_CS), + DEFINE_KEYCODE(TV_SATELLITE_SERVICE), + DEFINE_KEYCODE(TV_NETWORK), + DEFINE_KEYCODE(TV_ANTENNA_CABLE), + DEFINE_KEYCODE(TV_INPUT_HDMI_1), + DEFINE_KEYCODE(TV_INPUT_HDMI_2), + DEFINE_KEYCODE(TV_INPUT_HDMI_3), + DEFINE_KEYCODE(TV_INPUT_HDMI_4), + DEFINE_KEYCODE(TV_INPUT_COMPOSITE_1), + DEFINE_KEYCODE(TV_INPUT_COMPOSITE_2), + DEFINE_KEYCODE(TV_INPUT_COMPONENT_1), + DEFINE_KEYCODE(TV_INPUT_COMPONENT_2), + DEFINE_KEYCODE(TV_INPUT_VGA_1), + DEFINE_KEYCODE(TV_AUDIO_DESCRIPTION), + DEFINE_KEYCODE(TV_AUDIO_DESCRIPTION_MIX_UP), + DEFINE_KEYCODE(TV_AUDIO_DESCRIPTION_MIX_DOWN), + DEFINE_KEYCODE(TV_ZOOM_MODE), + DEFINE_KEYCODE(TV_CONTENTS_MENU), + DEFINE_KEYCODE(TV_MEDIA_CONTEXT_MENU), + DEFINE_KEYCODE(TV_TIMER_PROGRAMMING), + DEFINE_KEYCODE(HELP), + DEFINE_KEYCODE(NAVIGATE_PREVIOUS), + DEFINE_KEYCODE(NAVIGATE_NEXT), + DEFINE_KEYCODE(NAVIGATE_IN), + DEFINE_KEYCODE(NAVIGATE_OUT), + DEFINE_KEYCODE(STEM_PRIMARY), + DEFINE_KEYCODE(STEM_1), + DEFINE_KEYCODE(STEM_2), + DEFINE_KEYCODE(STEM_3), + DEFINE_KEYCODE(MEDIA_SKIP_FORWARD), + DEFINE_KEYCODE(MEDIA_SKIP_BACKWARD), + DEFINE_KEYCODE(MEDIA_STEP_FORWARD), + DEFINE_KEYCODE(MEDIA_STEP_BACKWARD), + DEFINE_KEYCODE(SOFT_SLEEP), + + { NULL, 0 } +}; + +static const InputEventLabel AXES[] = { + DEFINE_AXIS(X), + DEFINE_AXIS(Y), + DEFINE_AXIS(PRESSURE), + DEFINE_AXIS(SIZE), + DEFINE_AXIS(TOUCH_MAJOR), + DEFINE_AXIS(TOUCH_MINOR), + DEFINE_AXIS(TOOL_MAJOR), + DEFINE_AXIS(TOOL_MINOR), + DEFINE_AXIS(ORIENTATION), + DEFINE_AXIS(VSCROLL), + DEFINE_AXIS(HSCROLL), + DEFINE_AXIS(Z), + DEFINE_AXIS(RX), + DEFINE_AXIS(RY), + DEFINE_AXIS(RZ), + DEFINE_AXIS(HAT_X), + DEFINE_AXIS(HAT_Y), + DEFINE_AXIS(LTRIGGER), + DEFINE_AXIS(RTRIGGER), + DEFINE_AXIS(THROTTLE), + DEFINE_AXIS(RUDDER), + DEFINE_AXIS(WHEEL), + DEFINE_AXIS(GAS), + DEFINE_AXIS(BRAKE), + DEFINE_AXIS(DISTANCE), + DEFINE_AXIS(TILT), + DEFINE_AXIS(GENERIC_1), + DEFINE_AXIS(GENERIC_2), + DEFINE_AXIS(GENERIC_3), + DEFINE_AXIS(GENERIC_4), + DEFINE_AXIS(GENERIC_5), + DEFINE_AXIS(GENERIC_6), + DEFINE_AXIS(GENERIC_7), + DEFINE_AXIS(GENERIC_8), + DEFINE_AXIS(GENERIC_9), + DEFINE_AXIS(GENERIC_10), + DEFINE_AXIS(GENERIC_11), + DEFINE_AXIS(GENERIC_12), + DEFINE_AXIS(GENERIC_13), + DEFINE_AXIS(GENERIC_14), + DEFINE_AXIS(GENERIC_15), + DEFINE_AXIS(GENERIC_16), + + // NOTE: If you add a new axis here you must also add it to several other files. + // Refer to frameworks/base/core/java/android/view/MotionEvent.java for the full list. + { NULL, 0 } +}; + +static const InputEventLabel LEDS[] = { + DEFINE_LED(NUM_LOCK), + DEFINE_LED(CAPS_LOCK), + DEFINE_LED(SCROLL_LOCK), + DEFINE_LED(COMPOSE), + DEFINE_LED(KANA), + DEFINE_LED(SLEEP), + DEFINE_LED(SUSPEND), + DEFINE_LED(MUTE), + DEFINE_LED(MISC), + DEFINE_LED(MAIL), + DEFINE_LED(CHARGING), + DEFINE_LED(CONTROLLER_1), + DEFINE_LED(CONTROLLER_2), + DEFINE_LED(CONTROLLER_3), + DEFINE_LED(CONTROLLER_4), + + // NOTE: If you add new LEDs here, you must also add them to Input.h + { NULL, 0 } +}; + +static const InputEventLabel FLAGS[] = { + DEFINE_FLAG(WAKE), + DEFINE_FLAG(VIRTUAL), + DEFINE_FLAG(FUNCTION), + DEFINE_FLAG(GESTURE), + + { NULL, 0 } +}; + +static int lookupValueByLabel(const char* literal, const InputEventLabel *list) { + while (list->literal) { + if (strcmp(literal, list->literal) == 0) { + return list->value; + } + list++; + } + return list->value; +} + +static const char* lookupLabelByValue(int value, const InputEventLabel* list) { + while (list->literal) { + if (list->value == value) { + return list->literal; + } + list++; + } + return NULL; +} + +static int32_t getKeyCodeByLabel(const char* label) { + return int32_t(lookupValueByLabel(label, KEYCODES)); +} + +static const char* getLabelByKeyCode(int32_t keyCode) { + if (keyCode >= 0 && keyCode < size(KEYCODES)) { + return KEYCODES[keyCode].literal; + } + return NULL; +} + +static uint32_t getKeyFlagByLabel(const char* label) { + return uint32_t(lookupValueByLabel(label, FLAGS)); +} + +static int32_t getAxisByLabel(const char* label) { + return int32_t(lookupValueByLabel(label, AXES)); +} + +static const char* getAxisLabel(int32_t axisId) { + return lookupLabelByValue(axisId, AXES); +} + +static int32_t getLedByLabel(const char* label) { + return int32_t(lookupValueByLabel(label, LEDS)); +} + + +} // namespace android +#endif // _LIBINPUT_INPUT_EVENT_LABELS_H diff --git a/phonelibs/android_frameworks_native/include/input/InputTransport.h b/phonelibs/android_frameworks_native/include/input/InputTransport.h new file mode 100644 index 0000000000..f31bceabd7 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/input/InputTransport.h @@ -0,0 +1,453 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _LIBINPUT_INPUT_TRANSPORT_H +#define _LIBINPUT_INPUT_TRANSPORT_H + +/** + * Native input transport. + * + * The InputChannel provides a mechanism for exchanging InputMessage structures across processes. + * + * The InputPublisher and InputConsumer each handle one end-point of an input channel. + * The InputPublisher is used by the input dispatcher to send events to the application. + * The InputConsumer is used by the application to receive events from the input dispatcher. + */ + +#include +#include +#include +#include +#include +#include +#include + +namespace android { + +/* + * Intermediate representation used to send input events and related signals. + * + * Note that this structure is used for IPCs so its layout must be identical + * on 64 and 32 bit processes. This is tested in StructLayout_test.cpp. + */ +struct InputMessage { + enum { + TYPE_KEY = 1, + TYPE_MOTION = 2, + TYPE_FINISHED = 3, + }; + + struct Header { + uint32_t type; + // We don't need this field in order to align the body below but we + // leave it here because InputMessage::size() and other functions + // compute the size of this structure as sizeof(Header) + sizeof(Body). + uint32_t padding; + } header; + + // Body *must* be 8 byte aligned. + union Body { + struct Key { + uint32_t seq; + nsecs_t eventTime __attribute__((aligned(8))); + int32_t deviceId; + int32_t source; + int32_t action; + int32_t flags; + int32_t keyCode; + int32_t scanCode; + int32_t metaState; + int32_t repeatCount; + nsecs_t downTime __attribute__((aligned(8))); + + inline size_t size() const { + return sizeof(Key); + } + } key; + + struct Motion { + uint32_t seq; + nsecs_t eventTime __attribute__((aligned(8))); + int32_t deviceId; + int32_t source; + int32_t action; + int32_t actionButton; + int32_t flags; + int32_t metaState; + int32_t buttonState; + int32_t edgeFlags; + nsecs_t downTime __attribute__((aligned(8))); + float xOffset; + float yOffset; + float xPrecision; + float yPrecision; + uint32_t pointerCount; + // Note that PointerCoords requires 8 byte alignment. + struct Pointer { + PointerProperties properties; + PointerCoords coords; + } pointers[MAX_POINTERS]; + + int32_t getActionId() const { + uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) + >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; + return pointers[index].properties.id; + } + + inline size_t size() const { + return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS + + sizeof(Pointer) * pointerCount; + } + } motion; + + struct Finished { + uint32_t seq; + bool handled; + + inline size_t size() const { + return sizeof(Finished); + } + } finished; + } __attribute__((aligned(8))) body; + + bool isValid(size_t actualSize) const; + size_t size() const; +}; + +/* + * An input channel consists of a local unix domain socket used to send and receive + * input messages across processes. Each channel has a descriptive name for debugging purposes. + * + * Each endpoint has its own InputChannel object that specifies its file descriptor. + * + * The input channel is closed when all references to it are released. + */ +class InputChannel : public RefBase { +protected: + virtual ~InputChannel(); + +public: + InputChannel(const String8& name, int fd); + + /* Creates a pair of input channels. + * + * Returns OK on success. + */ + static status_t openInputChannelPair(const String8& name, + sp& outServerChannel, sp& outClientChannel); + + inline String8 getName() const { return mName; } + inline int getFd() const { return mFd; } + + /* Sends a message to the other endpoint. + * + * If the channel is full then the message is guaranteed not to have been sent at all. + * Try again after the consumer has sent a finished signal indicating that it has + * consumed some of the pending messages from the channel. + * + * Returns OK on success. + * Returns WOULD_BLOCK if the channel is full. + * Returns DEAD_OBJECT if the channel's peer has been closed. + * Other errors probably indicate that the channel is broken. + */ + status_t sendMessage(const InputMessage* msg); + + /* Receives a message sent by the other endpoint. + * + * If there is no message present, try again after poll() indicates that the fd + * is readable. + * + * Returns OK on success. + * Returns WOULD_BLOCK if there is no message present. + * Returns DEAD_OBJECT if the channel's peer has been closed. + * Other errors probably indicate that the channel is broken. + */ + status_t receiveMessage(InputMessage* msg); + + /* Returns a new object that has a duplicate of this channel's fd. */ + sp dup() const; + +private: + String8 mName; + int mFd; +}; + +/* + * Publishes input events to an input channel. + */ +class InputPublisher { +public: + /* Creates a publisher associated with an input channel. */ + explicit InputPublisher(const sp& channel); + + /* Destroys the publisher and releases its input channel. */ + ~InputPublisher(); + + /* Gets the underlying input channel. */ + inline sp getChannel() { return mChannel; } + + /* Publishes a key event to the input channel. + * + * Returns OK on success. + * Returns WOULD_BLOCK if the channel is full. + * Returns DEAD_OBJECT if the channel's peer has been closed. + * Returns BAD_VALUE if seq is 0. + * Other errors probably indicate that the channel is broken. + */ + status_t publishKeyEvent( + uint32_t seq, + int32_t deviceId, + int32_t source, + int32_t action, + int32_t flags, + int32_t keyCode, + int32_t scanCode, + int32_t metaState, + int32_t repeatCount, + nsecs_t downTime, + nsecs_t eventTime); + + /* Publishes a motion event to the input channel. + * + * Returns OK on success. + * Returns WOULD_BLOCK if the channel is full. + * Returns DEAD_OBJECT if the channel's peer has been closed. + * Returns BAD_VALUE if seq is 0 or if pointerCount is less than 1 or greater than MAX_POINTERS. + * Other errors probably indicate that the channel is broken. + */ + status_t publishMotionEvent( + uint32_t seq, + int32_t deviceId, + int32_t source, + int32_t action, + int32_t actionButton, + int32_t flags, + int32_t edgeFlags, + int32_t metaState, + int32_t buttonState, + float xOffset, + float yOffset, + float xPrecision, + float yPrecision, + nsecs_t downTime, + nsecs_t eventTime, + uint32_t pointerCount, + const PointerProperties* pointerProperties, + const PointerCoords* pointerCoords); + + /* Receives the finished signal from the consumer in reply to the original dispatch signal. + * If a signal was received, returns the message sequence number, + * and whether the consumer handled the message. + * + * The returned sequence number is never 0 unless the operation failed. + * + * Returns OK on success. + * Returns WOULD_BLOCK if there is no signal present. + * Returns DEAD_OBJECT if the channel's peer has been closed. + * Other errors probably indicate that the channel is broken. + */ + status_t receiveFinishedSignal(uint32_t* outSeq, bool* outHandled); + +private: + sp mChannel; +}; + +/* + * Consumes input events from an input channel. + */ +class InputConsumer { +public: + /* Creates a consumer associated with an input channel. */ + explicit InputConsumer(const sp& channel); + + /* Destroys the consumer and releases its input channel. */ + ~InputConsumer(); + + /* Gets the underlying input channel. */ + inline sp getChannel() { return mChannel; } + + /* Consumes an input event from the input channel and copies its contents into + * an InputEvent object created using the specified factory. + * + * Tries to combine a series of move events into larger batches whenever possible. + * + * If consumeBatches is false, then defers consuming pending batched events if it + * is possible for additional samples to be added to them later. Call hasPendingBatch() + * to determine whether a pending batch is available to be consumed. + * + * If consumeBatches is true, then events are still batched but they are consumed + * immediately as soon as the input channel is exhausted. + * + * The frameTime parameter specifies the time when the current display frame started + * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown. + * + * The returned sequence number is never 0 unless the operation failed. + * + * Returns OK on success. + * Returns WOULD_BLOCK if there is no event present. + * Returns DEAD_OBJECT if the channel's peer has been closed. + * Returns NO_MEMORY if the event could not be created. + * Other errors probably indicate that the channel is broken. + */ + status_t consume(InputEventFactoryInterface* factory, bool consumeBatches, + nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent); + + /* Sends a finished signal to the publisher to inform it that the message + * with the specified sequence number has finished being process and whether + * the message was handled by the consumer. + * + * Returns OK on success. + * Returns BAD_VALUE if seq is 0. + * Other errors probably indicate that the channel is broken. + */ + status_t sendFinishedSignal(uint32_t seq, bool handled); + + /* Returns true if there is a deferred event waiting. + * + * Should be called after calling consume() to determine whether the consumer + * has a deferred event to be processed. Deferred events are somewhat special in + * that they have already been removed from the input channel. If the input channel + * becomes empty, the client may need to do extra work to ensure that it processes + * the deferred event despite the fact that the input channel's file descriptor + * is not readable. + * + * One option is simply to call consume() in a loop until it returns WOULD_BLOCK. + * This guarantees that all deferred events will be processed. + * + * Alternately, the caller can call hasDeferredEvent() to determine whether there is + * a deferred event waiting and then ensure that its event loop wakes up at least + * one more time to consume the deferred event. + */ + bool hasDeferredEvent() const; + + /* Returns true if there is a pending batch. + * + * Should be called after calling consume() with consumeBatches == false to determine + * whether consume() should be called again later on with consumeBatches == true. + */ + bool hasPendingBatch() const; + +private: + // True if touch resampling is enabled. + const bool mResampleTouch; + + // The input channel. + sp mChannel; + + // The current input message. + InputMessage mMsg; + + // True if mMsg contains a valid input message that was deferred from the previous + // call to consume and that still needs to be handled. + bool mMsgDeferred; + + // Batched motion events per device and source. + struct Batch { + Vector samples; + }; + Vector mBatches; + + // Touch state per device and source, only for sources of class pointer. + struct History { + nsecs_t eventTime; + BitSet32 idBits; + int32_t idToIndex[MAX_POINTER_ID + 1]; + PointerCoords pointers[MAX_POINTERS]; + + void initializeFrom(const InputMessage* msg) { + eventTime = msg->body.motion.eventTime; + idBits.clear(); + for (uint32_t i = 0; i < msg->body.motion.pointerCount; i++) { + uint32_t id = msg->body.motion.pointers[i].properties.id; + idBits.markBit(id); + idToIndex[id] = i; + pointers[i].copyFrom(msg->body.motion.pointers[i].coords); + } + } + + const PointerCoords& getPointerById(uint32_t id) const { + return pointers[idToIndex[id]]; + } + }; + struct TouchState { + int32_t deviceId; + int32_t source; + size_t historyCurrent; + size_t historySize; + History history[2]; + History lastResample; + + void initialize(int32_t deviceId, int32_t source) { + this->deviceId = deviceId; + this->source = source; + historyCurrent = 0; + historySize = 0; + lastResample.eventTime = 0; + lastResample.idBits.clear(); + } + + void addHistory(const InputMessage* msg) { + historyCurrent ^= 1; + if (historySize < 2) { + historySize += 1; + } + history[historyCurrent].initializeFrom(msg); + } + + const History* getHistory(size_t index) const { + return &history[(historyCurrent + index) & 1]; + } + }; + Vector mTouchStates; + + // Chain of batched sequence numbers. When multiple input messages are combined into + // a batch, we append a record here that associates the last sequence number in the + // batch with the previous one. When the finished signal is sent, we traverse the + // chain to individually finish all input messages that were part of the batch. + struct SeqChain { + uint32_t seq; // sequence number of batched input message + uint32_t chain; // sequence number of previous batched input message + }; + Vector mSeqChains; + + status_t consumeBatch(InputEventFactoryInterface* factory, + nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent); + status_t consumeSamples(InputEventFactoryInterface* factory, + Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent); + + void updateTouchState(InputMessage* msg); + void rewriteMessage(const TouchState& state, InputMessage* msg); + void resampleTouchState(nsecs_t frameTime, MotionEvent* event, + const InputMessage *next); + + ssize_t findBatch(int32_t deviceId, int32_t source) const; + ssize_t findTouchState(int32_t deviceId, int32_t source) const; + + status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled); + + static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg); + static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg); + static void addSample(MotionEvent* event, const InputMessage* msg); + static bool canAddSample(const Batch& batch, const InputMessage* msg); + static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time); + static bool shouldResampleTool(int32_t toolType); + + static bool isTouchResamplingEnabled(); +}; + +} // namespace android + +#endif // _LIBINPUT_INPUT_TRANSPORT_H diff --git a/phonelibs/android_frameworks_native/include/input/KeyCharacterMap.h b/phonelibs/android_frameworks_native/include/input/KeyCharacterMap.h new file mode 100644 index 0000000000..3f0914b67e --- /dev/null +++ b/phonelibs/android_frameworks_native/include/input/KeyCharacterMap.h @@ -0,0 +1,265 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _LIBINPUT_KEY_CHARACTER_MAP_H +#define _LIBINPUT_KEY_CHARACTER_MAP_H + +#include + +#if HAVE_ANDROID_OS +#include +#endif + +#include +#include +#include +#include +#include +#include +#include + +namespace android { + +/** + * Describes a mapping from Android key codes to characters. + * Also specifies other functions of the keyboard such as the keyboard type + * and key modifier semantics. + * + * This object is immutable after it has been loaded. + */ +class KeyCharacterMap : public RefBase { +public: + enum KeyboardType { + KEYBOARD_TYPE_UNKNOWN = 0, + KEYBOARD_TYPE_NUMERIC = 1, + KEYBOARD_TYPE_PREDICTIVE = 2, + KEYBOARD_TYPE_ALPHA = 3, + KEYBOARD_TYPE_FULL = 4, + KEYBOARD_TYPE_SPECIAL_FUNCTION = 5, + KEYBOARD_TYPE_OVERLAY = 6, + }; + + enum Format { + // Base keyboard layout, may contain device-specific options, such as "type" declaration. + FORMAT_BASE = 0, + // Overlay keyboard layout, more restrictive, may be published by applications, + // cannot override device-specific options. + FORMAT_OVERLAY = 1, + // Either base or overlay layout ok. + FORMAT_ANY = 2, + }; + + // Substitute key code and meta state for fallback action. + struct FallbackAction { + int32_t keyCode; + int32_t metaState; + }; + + /* Loads a key character map from a file. */ + static status_t load(const String8& filename, Format format, sp* outMap); + + /* Loads a key character map from its string contents. */ + static status_t loadContents(const String8& filename, + const char* contents, Format format, sp* outMap); + + /* Combines a base key character map and an overlay. */ + static sp combine(const sp& base, + const sp& overlay); + + /* Returns an empty key character map. */ + static sp empty(); + + /* Gets the keyboard type. */ + int32_t getKeyboardType() const; + + /* Gets the primary character for this key as in the label physically printed on it. + * Returns 0 if none (eg. for non-printing keys). */ + char16_t getDisplayLabel(int32_t keyCode) const; + + /* Gets the Unicode character for the number or symbol generated by the key + * when the keyboard is used as a dialing pad. + * Returns 0 if no number or symbol is generated. + */ + char16_t getNumber(int32_t keyCode) const; + + /* Gets the Unicode character generated by the key and meta key modifiers. + * Returns 0 if no character is generated. + */ + char16_t getCharacter(int32_t keyCode, int32_t metaState) const; + + /* Gets the fallback action to use by default if the application does not + * handle the specified key. + * Returns true if an action was available, false if none. + */ + bool getFallbackAction(int32_t keyCode, int32_t metaState, + FallbackAction* outFallbackAction) const; + + /* Gets the first matching Unicode character that can be generated by the key, + * preferring the one with the specified meta key modifiers. + * Returns 0 if no matching character is generated. + */ + char16_t getMatch(int32_t keyCode, const char16_t* chars, + size_t numChars, int32_t metaState) const; + + /* Gets a sequence of key events that could plausibly generate the specified + * character sequence. Returns false if some of the characters cannot be generated. + */ + bool getEvents(int32_t deviceId, const char16_t* chars, size_t numChars, + Vector& outEvents) const; + + /* Maps a scan code and usage code to a key code, in case this key map overrides + * the mapping in some way. */ + status_t mapKey(int32_t scanCode, int32_t usageCode, int32_t* outKeyCode) const; + + /* Tries to find a replacement key code for a given key code and meta state + * in character map. */ + void tryRemapKey(int32_t scanCode, int32_t metaState, + int32_t* outKeyCode, int32_t* outMetaState) const; + +#if HAVE_ANDROID_OS + /* Reads a key map from a parcel. */ + static sp readFromParcel(Parcel* parcel); + + /* Writes a key map to a parcel. */ + void writeToParcel(Parcel* parcel) const; +#endif + +protected: + virtual ~KeyCharacterMap(); + +private: + struct Behavior { + Behavior(); + Behavior(const Behavior& other); + + /* The next behavior in the list, or NULL if none. */ + Behavior* next; + + /* The meta key modifiers for this behavior. */ + int32_t metaState; + + /* The character to insert. */ + char16_t character; + + /* The fallback keycode if the key is not handled. */ + int32_t fallbackKeyCode; + + /* The replacement keycode if the key has to be replaced outright. */ + int32_t replacementKeyCode; + }; + + struct Key { + Key(); + Key(const Key& other); + ~Key(); + + /* The single character label printed on the key, or 0 if none. */ + char16_t label; + + /* The number or symbol character generated by the key, or 0 if none. */ + char16_t number; + + /* The list of key behaviors sorted from most specific to least specific + * meta key binding. */ + Behavior* firstBehavior; + }; + + class Parser { + enum State { + STATE_TOP = 0, + STATE_KEY = 1, + }; + + enum { + PROPERTY_LABEL = 1, + PROPERTY_NUMBER = 2, + PROPERTY_META = 3, + }; + + struct Property { + inline Property(int32_t property = 0, int32_t metaState = 0) : + property(property), metaState(metaState) { } + + int32_t property; + int32_t metaState; + }; + + KeyCharacterMap* mMap; + Tokenizer* mTokenizer; + Format mFormat; + State mState; + int32_t mKeyCode; + + public: + Parser(KeyCharacterMap* map, Tokenizer* tokenizer, Format format); + ~Parser(); + status_t parse(); + + private: + status_t parseType(); + status_t parseMap(); + status_t parseMapKey(); + status_t parseKey(); + status_t parseKeyProperty(); + status_t finishKey(Key* key); + status_t parseModifier(const String8& token, int32_t* outMetaState); + status_t parseCharacterLiteral(char16_t* outCharacter); + }; + + static sp sEmpty; + + KeyedVector mKeys; + int mType; + + KeyedVector mKeysByScanCode; + KeyedVector mKeysByUsageCode; + + KeyCharacterMap(); + KeyCharacterMap(const KeyCharacterMap& other); + + bool getKey(int32_t keyCode, const Key** outKey) const; + bool getKeyBehavior(int32_t keyCode, int32_t metaState, + const Key** outKey, const Behavior** outBehavior) const; + static bool matchesMetaState(int32_t eventMetaState, int32_t behaviorMetaState); + + bool findKey(char16_t ch, int32_t* outKeyCode, int32_t* outMetaState) const; + + static status_t load(Tokenizer* tokenizer, Format format, sp* outMap); + + static void addKey(Vector& outEvents, + int32_t deviceId, int32_t keyCode, int32_t metaState, bool down, nsecs_t time); + static void addMetaKeys(Vector& outEvents, + int32_t deviceId, int32_t metaState, bool down, nsecs_t time, + int32_t* currentMetaState); + static bool addSingleEphemeralMetaKey(Vector& outEvents, + int32_t deviceId, int32_t metaState, bool down, nsecs_t time, + int32_t keyCode, int32_t keyMetaState, + int32_t* currentMetaState); + static void addDoubleEphemeralMetaKey(Vector& outEvents, + int32_t deviceId, int32_t metaState, bool down, nsecs_t time, + int32_t leftKeyCode, int32_t leftKeyMetaState, + int32_t rightKeyCode, int32_t rightKeyMetaState, + int32_t eitherKeyMetaState, + int32_t* currentMetaState); + static void addLockedMetaKey(Vector& outEvents, + int32_t deviceId, int32_t metaState, nsecs_t time, + int32_t keyCode, int32_t keyMetaState, + int32_t* currentMetaState); +}; + +} // namespace android + +#endif // _LIBINPUT_KEY_CHARACTER_MAP_H diff --git a/phonelibs/android_frameworks_native/include/input/KeyLayoutMap.h b/phonelibs/android_frameworks_native/include/input/KeyLayoutMap.h new file mode 100644 index 0000000000..1e8de7173b --- /dev/null +++ b/phonelibs/android_frameworks_native/include/input/KeyLayoutMap.h @@ -0,0 +1,117 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _LIBINPUT_KEY_LAYOUT_MAP_H +#define _LIBINPUT_KEY_LAYOUT_MAP_H + +#include +#include +#include +#include +#include + +namespace android { + +struct AxisInfo { + enum Mode { + // Axis value is reported directly. + MODE_NORMAL = 0, + // Axis value should be inverted before reporting. + MODE_INVERT = 1, + // Axis value should be split into two axes + MODE_SPLIT = 2, + }; + + // Axis mode. + Mode mode; + + // Axis id. + // When split, this is the axis used for values smaller than the split position. + int32_t axis; + + // When split, this is the axis used for values after higher than the split position. + int32_t highAxis; + + // The split value, or 0 if not split. + int32_t splitValue; + + // The flat value, or -1 if none. + int32_t flatOverride; + + AxisInfo() : mode(MODE_NORMAL), axis(-1), highAxis(-1), splitValue(0), flatOverride(-1) { + } +}; + +/** + * Describes a mapping from keyboard scan codes and joystick axes to Android key codes and axes. + * + * This object is immutable after it has been loaded. + */ +class KeyLayoutMap : public RefBase { +public: + static status_t load(const String8& filename, sp* outMap); + + status_t mapKey(int32_t scanCode, int32_t usageCode, + int32_t* outKeyCode, uint32_t* outFlags) const; + status_t findScanCodesForKey(int32_t keyCode, Vector* outScanCodes) const; + status_t findScanCodeForLed(int32_t ledCode, int32_t* outScanCode) const; + status_t findUsageCodeForLed(int32_t ledCode, int32_t* outUsageCode) const; + + status_t mapAxis(int32_t scanCode, AxisInfo* outAxisInfo) const; + +protected: + virtual ~KeyLayoutMap(); + +private: + struct Key { + int32_t keyCode; + uint32_t flags; + }; + + struct Led { + int32_t ledCode; + }; + + + KeyedVector mKeysByScanCode; + KeyedVector mKeysByUsageCode; + KeyedVector mAxes; + KeyedVector mLedsByScanCode; + KeyedVector mLedsByUsageCode; + + KeyLayoutMap(); + + const Key* getKey(int32_t scanCode, int32_t usageCode) const; + + class Parser { + KeyLayoutMap* mMap; + Tokenizer* mTokenizer; + + public: + Parser(KeyLayoutMap* map, Tokenizer* tokenizer); + ~Parser(); + status_t parse(); + + private: + status_t parseKey(); + status_t parseAxis(); + status_t parseLed(); + }; +}; + +} // namespace android + +#endif // _LIBINPUT_KEY_LAYOUT_MAP_H diff --git a/phonelibs/android_frameworks_native/include/input/Keyboard.h b/phonelibs/android_frameworks_native/include/input/Keyboard.h new file mode 100644 index 0000000000..d4903e98df --- /dev/null +++ b/phonelibs/android_frameworks_native/include/input/Keyboard.h @@ -0,0 +1,104 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _LIBINPUT_KEYBOARD_H +#define _LIBINPUT_KEYBOARD_H + +#include +#include +#include +#include +#include +#include + +namespace android { + +enum { + /* Device id of the built in keyboard. */ + DEVICE_ID_BUILT_IN_KEYBOARD = 0, + + /* Device id of a generic virtual keyboard with a full layout that can be used + * to synthesize key events. */ + DEVICE_ID_VIRTUAL_KEYBOARD = -1, +}; + +class KeyLayoutMap; +class KeyCharacterMap; + +/** + * Loads the key layout map and key character map for a keyboard device. + */ +class KeyMap { +public: + String8 keyLayoutFile; + sp keyLayoutMap; + + String8 keyCharacterMapFile; + sp keyCharacterMap; + + KeyMap(); + ~KeyMap(); + + status_t load(const InputDeviceIdentifier& deviceIdenfier, + const PropertyMap* deviceConfiguration); + + inline bool haveKeyLayout() const { + return !keyLayoutFile.isEmpty(); + } + + inline bool haveKeyCharacterMap() const { + return !keyCharacterMapFile.isEmpty(); + } + + inline bool isComplete() const { + return haveKeyLayout() && haveKeyCharacterMap(); + } + +private: + bool probeKeyMap(const InputDeviceIdentifier& deviceIdentifier, const String8& name); + status_t loadKeyLayout(const InputDeviceIdentifier& deviceIdentifier, const String8& name); + status_t loadKeyCharacterMap(const InputDeviceIdentifier& deviceIdentifier, + const String8& name); + String8 getPath(const InputDeviceIdentifier& deviceIdentifier, + const String8& name, InputDeviceConfigurationFileType type); +}; + +/** + * Returns true if the keyboard is eligible for use as a built-in keyboard. + */ +extern bool isEligibleBuiltInKeyboard(const InputDeviceIdentifier& deviceIdentifier, + const PropertyMap* deviceConfiguration, const KeyMap* keyMap); + +/** + * Updates a meta state field when a key is pressed or released. + */ +extern int32_t updateMetaState(int32_t keyCode, bool down, int32_t oldMetaState); + +/** + * Normalizes the meta state such that if either the left or right modifier + * meta state bits are set then the result will also include the universal + * bit for that modifier. + */ +extern int32_t normalizeMetaState(int32_t oldMetaState); + +/** + * Returns true if a key is a meta key like ALT or CAPS_LOCK. + */ +extern bool isMetaKey(int32_t keyCode); + +} // namespace android + +#endif // _LIBINPUT_KEYBOARD_H diff --git a/phonelibs/android_frameworks_native/include/input/VelocityControl.h b/phonelibs/android_frameworks_native/include/input/VelocityControl.h new file mode 100644 index 0000000000..1acc2aef70 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/input/VelocityControl.h @@ -0,0 +1,107 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _LIBINPUT_VELOCITY_CONTROL_H +#define _LIBINPUT_VELOCITY_CONTROL_H + +#include +#include +#include + +namespace android { + +/* + * Specifies parameters that govern pointer or wheel acceleration. + */ +struct VelocityControlParameters { + // A scale factor that is multiplied with the raw velocity deltas + // prior to applying any other velocity control factors. The scale + // factor should be used to adapt the input device resolution + // (eg. counts per inch) to the output device resolution (eg. pixels per inch). + // + // Must be a positive value. + // Default is 1.0 (no scaling). + float scale; + + // The scaled speed at which acceleration begins to be applied. + // This value establishes the upper bound of a low speed regime for + // small precise motions that are performed without any acceleration. + // + // Must be a non-negative value. + // Default is 0.0 (no low threshold). + float lowThreshold; + + // The scaled speed at which maximum acceleration is applied. + // The difference between highThreshold and lowThreshold controls + // the range of speeds over which the acceleration factor is interpolated. + // The wider the range, the smoother the acceleration. + // + // Must be a non-negative value greater than or equal to lowThreshold. + // Default is 0.0 (no high threshold). + float highThreshold; + + // The acceleration factor. + // When the speed is above the low speed threshold, the velocity will scaled + // by an interpolated value between 1.0 and this amount. + // + // Must be a positive greater than or equal to 1.0. + // Default is 1.0 (no acceleration). + float acceleration; + + VelocityControlParameters() : + scale(1.0f), lowThreshold(0.0f), highThreshold(0.0f), acceleration(1.0f) { + } + + VelocityControlParameters(float scale, float lowThreshold, + float highThreshold, float acceleration) : + scale(scale), lowThreshold(lowThreshold), + highThreshold(highThreshold), acceleration(acceleration) { + } +}; + +/* + * Implements mouse pointer and wheel speed control and acceleration. + */ +class VelocityControl { +public: + VelocityControl(); + + /* Sets the various parameters. */ + void setParameters(const VelocityControlParameters& parameters); + + /* Resets the current movement counters to zero. + * This has the effect of nullifying any acceleration. */ + void reset(); + + /* Translates a raw movement delta into an appropriately + * scaled / accelerated delta based on the current velocity. */ + void move(nsecs_t eventTime, float* deltaX, float* deltaY); + +private: + // If no movements are received within this amount of time, + // we assume the movement has stopped and reset the movement counters. + static const nsecs_t STOP_TIME = 500 * 1000000; // 500 ms + + VelocityControlParameters mParameters; + + nsecs_t mLastMovementTime; + VelocityTracker::Position mRawPosition; + VelocityTracker mVelocityTracker; +}; + +} // namespace android + +#endif // _LIBINPUT_VELOCITY_CONTROL_H diff --git a/phonelibs/android_frameworks_native/include/input/VelocityTracker.h b/phonelibs/android_frameworks_native/include/input/VelocityTracker.h new file mode 100644 index 0000000000..795f575a2e --- /dev/null +++ b/phonelibs/android_frameworks_native/include/input/VelocityTracker.h @@ -0,0 +1,269 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _LIBINPUT_VELOCITY_TRACKER_H +#define _LIBINPUT_VELOCITY_TRACKER_H + +#include +#include +#include + +namespace android { + +class VelocityTrackerStrategy; + +/* + * Calculates the velocity of pointer movements over time. + */ +class VelocityTracker { +public: + struct Position { + float x, y; + }; + + struct Estimator { + static const size_t MAX_DEGREE = 4; + + // Estimator time base. + nsecs_t time; + + // Polynomial coefficients describing motion in X and Y. + float xCoeff[MAX_DEGREE + 1], yCoeff[MAX_DEGREE + 1]; + + // Polynomial degree (number of coefficients), or zero if no information is + // available. + uint32_t degree; + + // Confidence (coefficient of determination), between 0 (no fit) and 1 (perfect fit). + float confidence; + + inline void clear() { + time = 0; + degree = 0; + confidence = 0; + for (size_t i = 0; i <= MAX_DEGREE; i++) { + xCoeff[i] = 0; + yCoeff[i] = 0; + } + } + }; + + // Creates a velocity tracker using the specified strategy. + // If strategy is NULL, uses the default strategy for the platform. + VelocityTracker(const char* strategy = NULL); + + ~VelocityTracker(); + + // Resets the velocity tracker state. + void clear(); + + // Resets the velocity tracker state for specific pointers. + // Call this method when some pointers have changed and may be reusing + // an id that was assigned to a different pointer earlier. + void clearPointers(BitSet32 idBits); + + // Adds movement information for a set of pointers. + // The idBits bitfield specifies the pointer ids of the pointers whose positions + // are included in the movement. + // The positions array contains position information for each pointer in order by + // increasing id. Its size should be equal to the number of one bits in idBits. + void addMovement(nsecs_t eventTime, BitSet32 idBits, const Position* positions); + + // Adds movement information for all pointers in a MotionEvent, including historical samples. + void addMovement(const MotionEvent* event); + + // Gets the velocity of the specified pointer id in position units per second. + // Returns false and sets the velocity components to zero if there is + // insufficient movement information for the pointer. + bool getVelocity(uint32_t id, float* outVx, float* outVy) const; + + // Gets an estimator for the recent movements of the specified pointer id. + // Returns false and clears the estimator if there is no information available + // about the pointer. + bool getEstimator(uint32_t id, Estimator* outEstimator) const; + + // Gets the active pointer id, or -1 if none. + inline int32_t getActivePointerId() const { return mActivePointerId; } + + // Gets a bitset containing all pointer ids from the most recent movement. + inline BitSet32 getCurrentPointerIdBits() const { return mCurrentPointerIdBits; } + +private: + static const char* DEFAULT_STRATEGY; + + nsecs_t mLastEventTime; + BitSet32 mCurrentPointerIdBits; + int32_t mActivePointerId; + VelocityTrackerStrategy* mStrategy; + + bool configureStrategy(const char* strategy); + + static VelocityTrackerStrategy* createStrategy(const char* strategy); +}; + + +/* + * Implements a particular velocity tracker algorithm. + */ +class VelocityTrackerStrategy { +protected: + VelocityTrackerStrategy() { } + +public: + virtual ~VelocityTrackerStrategy() { } + + virtual void clear() = 0; + virtual void clearPointers(BitSet32 idBits) = 0; + virtual void addMovement(nsecs_t eventTime, BitSet32 idBits, + const VelocityTracker::Position* positions) = 0; + virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const = 0; +}; + + +/* + * Velocity tracker algorithm based on least-squares linear regression. + */ +class LeastSquaresVelocityTrackerStrategy : public VelocityTrackerStrategy { +public: + enum Weighting { + // No weights applied. All data points are equally reliable. + WEIGHTING_NONE, + + // Weight by time delta. Data points clustered together are weighted less. + WEIGHTING_DELTA, + + // Weight such that points within a certain horizon are weighed more than those + // outside of that horizon. + WEIGHTING_CENTRAL, + + // Weight such that points older than a certain amount are weighed less. + WEIGHTING_RECENT, + }; + + // Degree must be no greater than Estimator::MAX_DEGREE. + LeastSquaresVelocityTrackerStrategy(uint32_t degree, Weighting weighting = WEIGHTING_NONE); + virtual ~LeastSquaresVelocityTrackerStrategy(); + + virtual void clear(); + virtual void clearPointers(BitSet32 idBits); + virtual void addMovement(nsecs_t eventTime, BitSet32 idBits, + const VelocityTracker::Position* positions); + virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const; + +private: + // Sample horizon. + // We don't use too much history by default since we want to react to quick + // changes in direction. + static const nsecs_t HORIZON = 100 * 1000000; // 100 ms + + // Number of samples to keep. + static const uint32_t HISTORY_SIZE = 20; + + struct Movement { + nsecs_t eventTime; + BitSet32 idBits; + VelocityTracker::Position positions[MAX_POINTERS]; + + inline const VelocityTracker::Position& getPosition(uint32_t id) const { + return positions[idBits.getIndexOfBit(id)]; + } + }; + + float chooseWeight(uint32_t index) const; + + const uint32_t mDegree; + const Weighting mWeighting; + uint32_t mIndex; + Movement mMovements[HISTORY_SIZE]; +}; + + +/* + * Velocity tracker algorithm that uses an IIR filter. + */ +class IntegratingVelocityTrackerStrategy : public VelocityTrackerStrategy { +public: + // Degree must be 1 or 2. + IntegratingVelocityTrackerStrategy(uint32_t degree); + ~IntegratingVelocityTrackerStrategy(); + + virtual void clear(); + virtual void clearPointers(BitSet32 idBits); + virtual void addMovement(nsecs_t eventTime, BitSet32 idBits, + const VelocityTracker::Position* positions); + virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const; + +private: + // Current state estimate for a particular pointer. + struct State { + nsecs_t updateTime; + uint32_t degree; + + float xpos, xvel, xaccel; + float ypos, yvel, yaccel; + }; + + const uint32_t mDegree; + BitSet32 mPointerIdBits; + State mPointerState[MAX_POINTER_ID + 1]; + + void initState(State& state, nsecs_t eventTime, float xpos, float ypos) const; + void updateState(State& state, nsecs_t eventTime, float xpos, float ypos) const; + void populateEstimator(const State& state, VelocityTracker::Estimator* outEstimator) const; +}; + + +/* + * Velocity tracker strategy used prior to ICS. + */ +class LegacyVelocityTrackerStrategy : public VelocityTrackerStrategy { +public: + LegacyVelocityTrackerStrategy(); + virtual ~LegacyVelocityTrackerStrategy(); + + virtual void clear(); + virtual void clearPointers(BitSet32 idBits); + virtual void addMovement(nsecs_t eventTime, BitSet32 idBits, + const VelocityTracker::Position* positions); + virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const; + +private: + // Oldest sample to consider when calculating the velocity. + static const nsecs_t HORIZON = 200 * 1000000; // 100 ms + + // Number of samples to keep. + static const uint32_t HISTORY_SIZE = 20; + + // The minimum duration between samples when estimating velocity. + static const nsecs_t MIN_DURATION = 10 * 1000000; // 10 ms + + struct Movement { + nsecs_t eventTime; + BitSet32 idBits; + VelocityTracker::Position positions[MAX_POINTERS]; + + inline const VelocityTracker::Position& getPosition(uint32_t id) const { + return positions[idBits.getIndexOfBit(id)]; + } + }; + + uint32_t mIndex; + Movement mMovements[HISTORY_SIZE]; +}; + +} // namespace android + +#endif // _LIBINPUT_VELOCITY_TRACKER_H diff --git a/phonelibs/android_frameworks_native/include/input/VirtualKeyMap.h b/phonelibs/android_frameworks_native/include/input/VirtualKeyMap.h new file mode 100644 index 0000000000..e245ead682 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/input/VirtualKeyMap.h @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _LIBINPUT_VIRTUAL_KEY_MAP_H +#define _LIBINPUT_VIRTUAL_KEY_MAP_H + +#include + +#include +#include +#include +#include +#include +#include + +namespace android { + +/* Describes a virtual key. */ +struct VirtualKeyDefinition { + int32_t scanCode; + + // configured position data, specified in display coords + int32_t centerX; + int32_t centerY; + int32_t width; + int32_t height; +}; + + +/** + * Describes a collection of virtual keys on a touch screen in terms of + * virtual scan codes and hit rectangles. + * + * This object is immutable after it has been loaded. + */ +class VirtualKeyMap { +public: + ~VirtualKeyMap(); + + static status_t load(const String8& filename, VirtualKeyMap** outMap); + + inline const Vector& getVirtualKeys() const { + return mVirtualKeys; + } + +private: + class Parser { + VirtualKeyMap* mMap; + Tokenizer* mTokenizer; + + public: + Parser(VirtualKeyMap* map, Tokenizer* tokenizer); + ~Parser(); + status_t parse(); + + private: + bool consumeFieldDelimiterAndSkipWhitespace(); + bool parseNextIntField(int32_t* outValue); + }; + + Vector mVirtualKeys; + + VirtualKeyMap(); +}; + +} // namespace android + +#endif // _LIBINPUT_KEY_CHARACTER_MAP_H diff --git a/phonelibs/android_frameworks_native/include/media/drm/DrmAPI.h b/phonelibs/android_frameworks_native/include/media/drm/DrmAPI.h new file mode 100644 index 0000000000..272881b9f5 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/media/drm/DrmAPI.h @@ -0,0 +1,419 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DRM_API_H_ +#define DRM_API_H_ + +#include +#include +#include +#include +#include +#include +#include + +// Loadable DrmEngine shared libraries should define the entry points +// createDrmFactory and createCryptoFactory as shown below: +// +// extern "C" { +// extern android::DrmFactory *createDrmFactory(); +// extern android::CryptoFactory *createCryptoFactory(); +// } + +namespace android { + + class DrmPlugin; + class DrmPluginListener; + + // DRMs are implemented in DrmEngine plugins, which are dynamically + // loadable shared libraries that implement the entry points + // createDrmFactory and createCryptoFactory. createDrmFactory + // constructs and returns an instance of a DrmFactory object. Similarly, + // createCryptoFactory creates an instance of a CryptoFactory object. + // When a MediaCrypto or MediaDrm object needs to be constructed, all + // available DrmEngines present in the plugins directory on the device + // are scanned for a matching DrmEngine that can support the crypto + // scheme. When a match is found, the DrmEngine's createCryptoPlugin and + // createDrmPlugin methods are used to create CryptoPlugin or + // DrmPlugin instances to support that DRM scheme. + + class DrmFactory { + public: + DrmFactory() {} + virtual ~DrmFactory() {} + + // DrmFactory::isCryptoSchemeSupported can be called to determine + // if the plugin factory is able to construct plugins that support a + // given crypto scheme, which is specified by a UUID. + virtual bool isCryptoSchemeSupported(const uint8_t uuid[16]) = 0; + + // DrmFactory::isContentTypeSupported can be called to determine + // if the plugin factory is able to construct plugins that support a + // given media container format specified by mimeType + virtual bool isContentTypeSupported(const String8 &mimeType) = 0; + + // Construct a DrmPlugin for the crypto scheme specified by UUID. + virtual status_t createDrmPlugin( + const uint8_t uuid[16], DrmPlugin **plugin) = 0; + + private: + DrmFactory(const DrmFactory &); + DrmFactory &operator=(const DrmFactory &); + }; + + class DrmPlugin { + public: + enum EventType { + kDrmPluginEventProvisionRequired = 1, + kDrmPluginEventKeyNeeded, + kDrmPluginEventKeyExpired, + kDrmPluginEventVendorDefined, + kDrmPluginEventSessionReclaimed, + kDrmPluginEventExpirationUpdate, + kDrmPluginEventKeysChange, + }; + + // Drm keys can be for offline content or for online streaming. + // Offline keys are persisted on the device and may be used when the device + // is disconnected from the network. The Release type is used to request + // that offline keys be no longer restricted to offline use. + enum KeyType { + kKeyType_Offline, + kKeyType_Streaming, + kKeyType_Release + }; + + // Enumerate KeyRequestTypes to allow an app to determine the + // type of a key request returned from getKeyRequest. + enum KeyRequestType { + kKeyRequestType_Unknown, + kKeyRequestType_Initial, + kKeyRequestType_Renewal, + kKeyRequestType_Release + }; + + // Enumerate KeyStatusTypes which indicate the state of a key + enum KeyStatusType + { + kKeyStatusType_Usable, + kKeyStatusType_Expired, + kKeyStatusType_OutputNotAllowed, + kKeyStatusType_StatusPending, + kKeyStatusType_InternalError + }; + + // Used by sendKeysChange to report the usability status of each + // key to the app. + struct KeyStatus + { + Vector mKeyId; + KeyStatusType mType; + }; + + DrmPlugin() {} + virtual ~DrmPlugin() {} + + // Open a new session with the DrmPlugin object. A session ID is returned + // in the sessionId parameter. + virtual status_t openSession(Vector &sessionId) = 0; + + // Close a session on the DrmPlugin object. + virtual status_t closeSession(Vector const &sessionId) = 0; + + // A key request/response exchange occurs between the app and a License + // Server to obtain the keys required to decrypt the content. getKeyRequest() + // is used to obtain an opaque key request blob that is delivered to the + // license server. + // + // The scope parameter may be a sessionId or a keySetId, depending on the + // specified keyType. When the keyType is kKeyType_Offline or + // kKeyType_Streaming, scope should be set to the sessionId the keys will be + // provided to. When the keyType is kKeyType_Release, scope should be set to + // the keySetId of the keys being released. Releasing keys from a device + // invalidates them for all sessions. + // + // The init data passed to getKeyRequest is container-specific and its + // meaning is interpreted based on the mime type provided in the mimeType + // parameter to getKeyRequest. It could contain, for example, the content + // ID, key ID or other data obtained from the content metadata that is required + // in generating the key request. Init may be null when keyType is + // kKeyType_Release. + // + // mimeType identifies the mime type of the content + // + // keyType specifies if the keys are to be used for streaming or offline content + // + // optionalParameters are included in the key request message to allow a + // client application to provide additional message parameters to the server. + // + // If successful, the opaque key request blob is returned to the caller. + virtual status_t + getKeyRequest(Vector const &scope, + Vector const &initData, + String8 const &mimeType, KeyType keyType, + KeyedVector const &optionalParameters, + Vector &request, String8 &defaultUrl, + KeyRequestType *keyRequestType) = 0; + + // + // After a key response is received by the app, it is provided to the + // Drm plugin using provideKeyResponse. + // + // scope may be a sessionId or a keySetId depending on the type of the + // response. Scope should be set to the sessionId when the response is + // for either streaming or offline key requests. Scope should be set to the + // keySetId when the response is for a release request. + // + // When the response is for an offline key request, a keySetId is returned + // in the keySetId vector parameter that can be used to later restore the + // keys to a new session with the method restoreKeys. When the response is + // for a streaming or release request, no keySetId is returned. + // + virtual status_t provideKeyResponse(Vector const &scope, + Vector const &response, + Vector &keySetId) = 0; + + // Remove the current keys from a session + virtual status_t removeKeys(Vector const &sessionId) = 0; + + // Restore persisted offline keys into a new session. keySetId identifies + // the keys to load, obtained from a prior call to provideKeyResponse(). + virtual status_t restoreKeys(Vector const &sessionId, + Vector const &keySetId) = 0; + + // Request an informative description of the license for the session. The status + // is in the form of {name, value} pairs. Since DRM license policies vary by + // vendor, the specific status field names are determined by each DRM vendor. + // Refer to your DRM provider documentation for definitions of the field names + // for a particular DrmEngine. + virtual status_t + queryKeyStatus(Vector const &sessionId, + KeyedVector &infoMap) const = 0; + + // A provision request/response exchange occurs between the app and a + // provisioning server to retrieve a device certificate. getProvisionRequest + // is used to obtain an opaque key request blob that is delivered to the + // provisioning server. + // + // If successful, the opaque provision request blob is returned to the caller. + virtual status_t getProvisionRequest(String8 const &cert_type, + String8 const &cert_authority, + Vector &request, + String8 &defaultUrl) = 0; + + // After a provision response is received by the app, it is provided to the + // Drm plugin using provideProvisionResponse. + virtual status_t provideProvisionResponse(Vector const &response, + Vector &certificate, + Vector &wrapped_key) = 0; + + // Remove device provisioning. + virtual status_t unprovisionDevice() = 0; + + // A means of enforcing the contractual requirement for a concurrent stream + // limit per subscriber across devices is provided via SecureStop. SecureStop + // is a means of securely monitoring the lifetime of sessions. Since playback + // on a device can be interrupted due to reboot, power failure, etc. a means + // of persisting the lifetime information on the device is needed. + // + // A signed version of the sessionID is written to persistent storage on the + // device when each MediaCrypto object is created. The sessionID is signed by + // the device private key to prevent tampering. + // + // In the normal case, playback will be completed, the session destroyed and + // the Secure Stops will be queried. The App queries secure stops and forwards + // the secure stop message to the server which verifies the signature and + // notifies the server side database that the session destruction has been + // confirmed. The persisted record on the client is only removed after positive + // confirmation that the server received the message using releaseSecureStops(). + virtual status_t getSecureStops(List > &secureStops) = 0; + virtual status_t getSecureStop(Vector const &ssid, Vector &secureStop) = 0; + virtual status_t releaseSecureStops(Vector const &ssRelease) = 0; + virtual status_t releaseAllSecureStops() = 0; + + // Read a property value given the device property string. There are a few forms + // of property access methods, depending on the data type returned. + // Since DRM plugin properties may vary, additional field names may be defined + // by each DRM vendor. Refer to your DRM provider documentation for definitions + // of its additional field names. + // + // Standard values are: + // "vendor" [string] identifies the maker of the plugin + // "version" [string] identifies the version of the plugin + // "description" [string] describes the plugin + // 'deviceUniqueId' [byte array] The device unique identifier is established + // during device provisioning and provides a means of uniquely identifying + // each device. + virtual status_t getPropertyString(String8 const &name, String8 &value ) const = 0; + virtual status_t getPropertyByteArray(String8 const &name, + Vector &value ) const = 0; + + // Write a property value given the device property string. There are a few forms + // of property setting methods, depending on the data type. + // Since DRM plugin properties may vary, additional field names may be defined + // by each DRM vendor. Refer to your DRM provider documentation for definitions + // of its field names. + virtual status_t setPropertyString(String8 const &name, + String8 const &value ) = 0; + virtual status_t setPropertyByteArray(String8 const &name, + Vector const &value ) = 0; + + // The following methods implement operations on a CryptoSession to support + // encrypt, decrypt, sign verify operations on operator-provided + // session keys. + + // + // The algorithm string conforms to JCA Standard Names for Cipher + // Transforms and is case insensitive. For example "AES/CBC/PKCS5Padding". + // + // Return OK if the algorithm is supported, otherwise return BAD_VALUE + // + virtual status_t setCipherAlgorithm(Vector const &sessionId, + String8 const &algorithm) = 0; + + // + // The algorithm string conforms to JCA Standard Names for Mac + // Algorithms and is case insensitive. For example "HmacSHA256". + // + // Return OK if the algorithm is supported, otherwise return BAD_VALUE + // + virtual status_t setMacAlgorithm(Vector const &sessionId, + String8 const &algorithm) = 0; + + // Encrypt the provided input buffer with the cipher algorithm + // specified by setCipherAlgorithm and the key selected by keyId, + // and return the encrypted data. + virtual status_t encrypt(Vector const &sessionId, + Vector const &keyId, + Vector const &input, + Vector const &iv, + Vector &output) = 0; + + // Decrypt the provided input buffer with the cipher algorithm + // specified by setCipherAlgorithm and the key selected by keyId, + // and return the decrypted data. + virtual status_t decrypt(Vector const &sessionId, + Vector const &keyId, + Vector const &input, + Vector const &iv, + Vector &output) = 0; + + // Compute a signature on the provided message using the mac algorithm + // specified by setMacAlgorithm and the key selected by keyId, + // and return the signature. + virtual status_t sign(Vector const &sessionId, + Vector const &keyId, + Vector const &message, + Vector &signature) = 0; + + // Compute a signature on the provided message using the mac algorithm + // specified by setMacAlgorithm and the key selected by keyId, + // and compare with the expected result. Set result to true or + // false depending on the outcome. + virtual status_t verify(Vector const &sessionId, + Vector const &keyId, + Vector const &message, + Vector const &signature, + bool &match) = 0; + + + // Compute an RSA signature on the provided message using the algorithm + // specified by algorithm. + virtual status_t signRSA(Vector const &sessionId, + String8 const &algorithm, + Vector const &message, + Vector const &wrapped_key, + Vector &signature) = 0; + + + status_t setListener(const sp& listener) { + Mutex::Autolock lock(mEventLock); + mListener = listener; + return OK; + } + + protected: + // Plugins call these methods to deliver events to the java app + void sendEvent(EventType eventType, int extra, + Vector const *sessionId, + Vector const *data); + + void sendExpirationUpdate(Vector const *sessionId, + int64_t expiryTimeInMS); + + void sendKeysChange(Vector const *sessionId, + Vector const *keyStatusList, + bool hasNewUsableKey); + + private: + Mutex mEventLock; + sp mListener; + + DISALLOW_EVIL_CONSTRUCTORS(DrmPlugin); + }; + + class DrmPluginListener: virtual public RefBase + { + public: + virtual void sendEvent(DrmPlugin::EventType eventType, int extra, + Vector const *sessionId, + Vector const *data) = 0; + + virtual void sendExpirationUpdate(Vector const *sessionId, + int64_t expiryTimeInMS) = 0; + + virtual void sendKeysChange(Vector const *sessionId, + Vector const *keyStatusList, + bool hasNewUsableKey) = 0; + }; + + inline void DrmPlugin::sendEvent(EventType eventType, int extra, + Vector const *sessionId, + Vector const *data) { + mEventLock.lock(); + sp listener = mListener; + mEventLock.unlock(); + + if (listener != NULL) { + listener->sendEvent(eventType, extra, sessionId, data); + } + } + + inline void DrmPlugin::sendExpirationUpdate(Vector const *sessionId, + int64_t expiryTimeInMS) { + mEventLock.lock(); + sp listener = mListener; + mEventLock.unlock(); + + if (listener != NULL) { + listener->sendExpirationUpdate(sessionId, expiryTimeInMS); + } + } + + inline void DrmPlugin::sendKeysChange(Vector const *sessionId, + Vector const *keyStatusList, + bool hasNewUsableKey) { + mEventLock.lock(); + sp listener = mListener; + mEventLock.unlock(); + + if (listener != NULL) { + listener->sendKeysChange(sessionId, keyStatusList, hasNewUsableKey); + } + } +} // namespace android + +#endif // DRM_API_H_ diff --git a/phonelibs/android_frameworks_native/include/media/editor/II420ColorConverter.h b/phonelibs/android_frameworks_native/include/media/editor/II420ColorConverter.h new file mode 100644 index 0000000000..33af61ff9a --- /dev/null +++ b/phonelibs/android_frameworks_native/include/media/editor/II420ColorConverter.h @@ -0,0 +1,126 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef II420_COLOR_CONVERTER_H + +#define II420_COLOR_CONVERTER_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct II420ColorConverter { + + /* + * getDecoderOutputFormat + * Returns the color format (OMX_COLOR_FORMATTYPE) of the decoder output. + * If it is I420 (OMX_COLOR_FormatYUV420Planar), no conversion is needed, + * and convertDecoderOutputToI420() can be a no-op. + */ + int (*getDecoderOutputFormat)(); + + /* + * convertDecoderOutputToI420 + * @Desc Converts from the decoder output format to I420 format. + * @note Caller (e.g. VideoEditor) owns the buffers + * @param decoderBits (IN) Pointer to the buffer contains decoder output + * @param decoderWidth (IN) Buffer width, as reported by the decoder + * metadata (kKeyWidth) + * @param decoderHeight (IN) Buffer height, as reported by the decoder + * metadata (kKeyHeight) + * @param decoderRect (IN) The rectangle of the actual frame, as + * reported by decoder metadata (kKeyCropRect) + * @param dstBits (OUT) Pointer to the output I420 buffer + * @return -1 Any error + * @return 0 No Error + */ + int (*convertDecoderOutputToI420)( + void* decoderBits, int decoderWidth, int decoderHeight, + ARect decoderRect, void* dstBits); + + /* + * getEncoderIntputFormat + * Returns the color format (OMX_COLOR_FORMATTYPE) of the encoder input. + * If it is I420 (OMX_COLOR_FormatYUV420Planar), no conversion is needed, + * and convertI420ToEncoderInput() and getEncoderInputBufferInfo() can + * be no-ops. + */ + int (*getEncoderInputFormat)(); + + /* convertI420ToEncoderInput + * @Desc This function converts from I420 to the encoder input format + * @note Caller (e.g. VideoEditor) owns the buffers + * @param srcBits (IN) Pointer to the input I420 buffer + * @param srcWidth (IN) Width of the I420 frame + * @param srcHeight (IN) Height of the I420 frame + * @param encoderWidth (IN) Encoder buffer width, as calculated by + * getEncoderBufferInfo() + * @param encoderHeight (IN) Encoder buffer height, as calculated by + * getEncoderBufferInfo() + * @param encoderRect (IN) Rect coordinates of the actual frame inside + * the encoder buffer, as calculated by + * getEncoderBufferInfo(). + * @param encoderBits (OUT) Pointer to the output buffer. The size of + * this buffer is calculated by + * getEncoderBufferInfo() + * @return -1 Any error + * @return 0 No Error + */ + int (*convertI420ToEncoderInput)( + void* srcBits, int srcWidth, int srcHeight, + int encoderWidth, int encoderHeight, ARect encoderRect, + void* encoderBits); + + /* getEncoderInputBufferInfo + * @Desc This function returns metadata for the encoder input buffer + * based on the actual I420 frame width and height. + * @note This API should be be used to obtain the necessary information + * before calling convertI420ToEncoderInput(). + * VideoEditor knows only the width and height of the I420 buffer, + * but it also needs know the width, height, and size of the + * encoder input buffer. The encoder input buffer width and height + * are used to set the metadata for the encoder. + * @param srcWidth (IN) Width of the I420 frame + * @param srcHeight (IN) Height of the I420 frame + * @param encoderWidth (OUT) Encoder buffer width needed + * @param encoderHeight (OUT) Encoder buffer height needed + * @param encoderRect (OUT) Rect coordinates of the actual frame inside + * the encoder buffer + * @param encoderBufferSize (OUT) The size of the buffer that need to be + * allocated by the caller before invoking + * convertI420ToEncoderInput(). + * @return -1 Any error + * @return 0 No Error + */ + int (*getEncoderInputBufferInfo)( + int srcWidth, int srcHeight, + int* encoderWidth, int* encoderHeight, + ARect* encoderRect, int* encoderBufferSize); + +} II420ColorConverter; + +/* The only function that the shared library needs to expose: It fills the + function pointers in II420ColorConverter */ +void getI420ColorConverter(II420ColorConverter *converter); + +#if defined(__cplusplus) +} +#endif + +#endif // II420_COLOR_CONVERTER_H diff --git a/phonelibs/android_frameworks_native/include/media/hardware/CryptoAPI.h b/phonelibs/android_frameworks_native/include/media/hardware/CryptoAPI.h new file mode 100644 index 0000000000..3e3257f956 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/media/hardware/CryptoAPI.h @@ -0,0 +1,115 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#ifndef CRYPTO_API_H_ + +#define CRYPTO_API_H_ + +namespace android { + +struct AString; +struct CryptoPlugin; + +struct CryptoFactory { + CryptoFactory() {} + virtual ~CryptoFactory() {} + + virtual bool isCryptoSchemeSupported(const uint8_t uuid[16]) const = 0; + + virtual status_t createPlugin( + const uint8_t uuid[16], const void *data, size_t size, + CryptoPlugin **plugin) = 0; + +private: + CryptoFactory(const CryptoFactory &); + CryptoFactory &operator=(const CryptoFactory &); +}; + +struct CryptoPlugin { + enum Mode { + kMode_Unencrypted = 0, + kMode_AES_CTR = 1, + + // Neither key nor iv are being used in this mode. + // Each subsample is encrypted w/ an iv of all zeroes. + kMode_AES_WV = 2, // FIX constant + }; + + struct SubSample { + uint32_t mNumBytesOfClearData; + uint32_t mNumBytesOfEncryptedData; + }; + + CryptoPlugin() {} + virtual ~CryptoPlugin() {} + + // If this method returns false, a non-secure decoder will be used to + // decode the data after decryption. The decrypt API below will have + // to support insecure decryption of the data (secure = false) for + // media data of the given mime type. + virtual bool requiresSecureDecoderComponent(const char *mime) const = 0; + + // To implement resolution constraints, the crypto plugin needs to know + // the resolution of the video being decrypted. The media player should + // call this method when the resolution is determined and any time it + // is subsequently changed. + + virtual void notifyResolution(uint32_t /* width */, uint32_t /* height */) {} + + // A MediaDrm session may be associated with a MediaCrypto session. The + // associated MediaDrm session is used to load decryption keys + // into the crypto/drm plugin. The keys are then referenced by key-id + // in the 'key' parameter to the decrypt() method. + // Should return NO_ERROR on success, ERROR_DRM_SESSION_NOT_OPENED if + // the session is not opened and a code from MediaErrors.h otherwise. + virtual status_t setMediaDrmSession(const Vector & /*sessionId */) { + return ERROR_UNSUPPORTED; + } + + // If the error returned falls into the range + // ERROR_DRM_VENDOR_MIN..ERROR_DRM_VENDOR_MAX, errorDetailMsg should be + // filled in with an appropriate string. + // At the java level these special errors will then trigger a + // MediaCodec.CryptoException that gives clients access to both + // the error code and the errorDetailMsg. + // Returns a non-negative result to indicate the number of bytes written + // to the dstPtr, or a negative result to indicate an error. + virtual ssize_t decrypt( + bool secure, + const uint8_t key[16], + const uint8_t iv[16], + Mode mode, + const void *srcPtr, + const SubSample *subSamples, size_t numSubSamples, + void *dstPtr, + AString *errorDetailMsg) = 0; + +private: + CryptoPlugin(const CryptoPlugin &); + CryptoPlugin &operator=(const CryptoPlugin &); +}; + +} // namespace android + +extern "C" { + extern android::CryptoFactory *createCryptoFactory(); +} + +#endif // CRYPTO_API_H_ diff --git a/phonelibs/android_frameworks_native/include/media/hardware/HDCPAPI.h b/phonelibs/android_frameworks_native/include/media/hardware/HDCPAPI.h new file mode 100644 index 0000000000..3a53e9fc90 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/media/hardware/HDCPAPI.h @@ -0,0 +1,164 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HDCP_API_H_ + +#define HDCP_API_H_ + +#include +#include + +namespace android { + +// Two different kinds of modules are covered under the same HDCPModule +// structure below, a module either implements decryption or encryption. +struct HDCPModule { + typedef void (*ObserverFunc)(void *cookie, int msg, int ext1, int ext2); + + // The msg argument in calls to the observer notification function. + enum { + // Sent in response to a call to "HDCPModule::initAsync" once + // initialization has either been successfully completed, + // i.e. the HDCP session is now fully setup (AKE, Locality Check, + // SKE and any authentication with repeaters completed) or failed. + // ext1 should be a suitable error code (status_t), ext2 is + // unused for ENCRYPTION and in the case of HDCP_INITIALIZATION_COMPLETE + // holds the local TCP port the module is listening on. + HDCP_INITIALIZATION_COMPLETE, + HDCP_INITIALIZATION_FAILED, + + // Sent upon completion of a call to "HDCPModule::shutdownAsync". + // ext1 should be a suitable error code, ext2 is unused. + HDCP_SHUTDOWN_COMPLETE, + HDCP_SHUTDOWN_FAILED, + + HDCP_UNAUTHENTICATED_CONNECTION, + HDCP_UNAUTHORIZED_CONNECTION, + HDCP_REVOKED_CONNECTION, + HDCP_TOPOLOGY_EXECEEDED, + HDCP_UNKNOWN_ERROR, + + // DECRYPTION only: Indicates that a client has successfully connected, + // a secure session established and the module is ready to accept + // future calls to "decrypt". + HDCP_SESSION_ESTABLISHED, + }; + + // HDCPModule capability bit masks + enum { + // HDCP_CAPS_ENCRYPT: mandatory, meaning the HDCP module can encrypt + // from an input byte-array buffer to an output byte-array buffer + HDCP_CAPS_ENCRYPT = (1 << 0), + // HDCP_CAPS_ENCRYPT_NATIVE: the HDCP module supports encryption from + // a native buffer to an output byte-array buffer. The format of the + // input native buffer is specific to vendor's encoder implementation. + // It is the same format as that used by the encoder when + // "storeMetaDataInBuffers" extension is enabled on its output port. + HDCP_CAPS_ENCRYPT_NATIVE = (1 << 1), + }; + + // Module can call the notification function to signal completion/failure + // of asynchronous operations (such as initialization) or out of band + // events. + HDCPModule(void *cookie, ObserverFunc observerNotify) {}; + + virtual ~HDCPModule() {}; + + // ENCRYPTION: Request to setup an HDCP session with the host specified + // by addr and listening on the specified port. + // DECRYPTION: Request to setup an HDCP session, addr is the interface + // address the module should bind its socket to. port will be 0. + // The module will pick the port to listen on itself and report its choice + // in the "ext2" argument of the HDCP_INITIALIZATION_COMPLETE callback. + virtual status_t initAsync(const char *addr, unsigned port) = 0; + + // Request to shutdown the active HDCP session. + virtual status_t shutdownAsync() = 0; + + // Returns the capability bitmask of this HDCP session. + virtual uint32_t getCaps() { + return HDCP_CAPS_ENCRYPT; + } + + // ENCRYPTION only: + // Encrypt data according to the HDCP spec. "size" bytes of data are + // available at "inData" (virtual address), "size" may not be a multiple + // of 128 bits (16 bytes). An equal number of encrypted bytes should be + // written to the buffer at "outData" (virtual address). + // This operation is to be synchronous, i.e. this call does not return + // until outData contains size bytes of encrypted data. + // streamCTR will be assigned by the caller (to 0 for the first PES stream, + // 1 for the second and so on) + // inputCTR _will_be_maintained_by_the_callee_ for each PES stream. + virtual status_t encrypt( + const void *inData, size_t size, uint32_t streamCTR, + uint64_t *outInputCTR, void *outData) { + return INVALID_OPERATION; + } + + // Encrypt data according to the HDCP spec. "size" bytes of data starting + // at location "offset" are available in "buffer" (buffer handle). "size" + // may not be a multiple of 128 bits (16 bytes). An equal number of + // encrypted bytes should be written to the buffer at "outData" (virtual + // address). This operation is to be synchronous, i.e. this call does not + // return until outData contains size bytes of encrypted data. + // streamCTR will be assigned by the caller (to 0 for the first PES stream, + // 1 for the second and so on) + // inputCTR _will_be_maintained_by_the_callee_ for each PES stream. + virtual status_t encryptNative( + buffer_handle_t buffer, size_t offset, size_t size, + uint32_t streamCTR, uint64_t *outInputCTR, void *outData) { + return INVALID_OPERATION; + } + // DECRYPTION only: + // Decrypt data according to the HDCP spec. + // "size" bytes of encrypted data are available at "inData" + // (virtual address), "size" may not be a multiple of 128 bits (16 bytes). + // An equal number of decrypted bytes should be written to the buffer + // at "outData" (virtual address). + // This operation is to be synchronous, i.e. this call does not return + // until outData contains size bytes of decrypted data. + // Both streamCTR and inputCTR will be provided by the caller. + virtual status_t decrypt( + const void *inData, size_t size, + uint32_t streamCTR, uint64_t inputCTR, + void *outData) { + return INVALID_OPERATION; + } + +private: + HDCPModule(const HDCPModule &); + HDCPModule &operator=(const HDCPModule &); +}; + +} // namespace android + +// A shared library exporting the following methods should be included to +// support HDCP functionality. The shared library must be called +// "libstagefright_hdcp.so", it will be dynamically loaded into the +// mediaserver process. +extern "C" { + // Create a module for ENCRYPTION. + extern android::HDCPModule *createHDCPModule( + void *cookie, android::HDCPModule::ObserverFunc); + + // Create a module for DECRYPTION. + extern android::HDCPModule *createHDCPModuleForDecryption( + void *cookie, android::HDCPModule::ObserverFunc); +} + +#endif // HDCP_API_H_ + diff --git a/phonelibs/android_frameworks_native/include/media/hardware/HardwareAPI.h b/phonelibs/android_frameworks_native/include/media/hardware/HardwareAPI.h new file mode 100644 index 0000000000..1008c22d73 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/media/hardware/HardwareAPI.h @@ -0,0 +1,288 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HARDWARE_API_H_ + +#define HARDWARE_API_H_ + +#include +#include +#include +#include + +#include + +namespace android { + +// A pointer to this struct is passed to the OMX_SetParameter when the extension +// index for the 'OMX.google.android.index.enableAndroidNativeBuffers' extension +// is given. +// +// When Android native buffer use is disabled for a port (the default state), +// the OMX node should operate as normal, and expect UseBuffer calls to set its +// buffers. This is the mode that will be used when CPU access to the buffer is +// required. +// +// When Android native buffer use has been enabled for a given port, the video +// color format for the port is to be interpreted as an Android pixel format +// rather than an OMX color format. Enabling Android native buffers may also +// change how the component receives the native buffers. If store-metadata-mode +// is enabled on the port, the component will receive the buffers as specified +// in the section below. Otherwise, unless the node supports the +// 'OMX.google.android.index.useAndroidNativeBuffer2' extension, it should +// expect to receive UseAndroidNativeBuffer calls (via OMX_SetParameter) rather +// than UseBuffer calls for that port. +struct EnableAndroidNativeBuffersParams { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL enable; +}; + +// A pointer to this struct is passed to OMX_SetParameter() when the extension index +// "OMX.google.android.index.storeMetaDataInBuffers" or +// "OMX.google.android.index.storeANWBufferInMetadata" is given. +// +// When meta data is stored in the video buffers passed between OMX clients +// and OMX components, interpretation of the buffer data is up to the +// buffer receiver, and the data may or may not be the actual video data, but +// some information helpful for the receiver to locate the actual data. +// The buffer receiver thus needs to know how to interpret what is stored +// in these buffers, with mechanisms pre-determined externally. How to +// interpret the meta data is outside of the scope of this parameter. +// +// Currently, this is used to pass meta data from video source (camera component, for instance) to +// video encoder to avoid memcpying of input video frame data, as well as to pass dynamic output +// buffer to video decoder. To do this, bStoreMetaData is set to OMX_TRUE. +// +// If bStoreMetaData is set to false, real YUV frame data will be stored in input buffers, and +// the output buffers contain either real YUV frame data, or are themselves native handles as +// directed by enable/use-android-native-buffer parameter settings. +// In addition, if no OMX_SetParameter() call is made on a port with the corresponding extension +// index, the component should not assume that the client is not using metadata mode for the port. +// +// If the component supports this using the "OMX.google.android.index.storeANWBufferInMetadata" +// extension and bStoreMetaData is set to OMX_TRUE, data is passed using the VideoNativeMetadata +// layout as defined below. Each buffer will be accompanied by a fence. The fence must signal +// before the buffer can be used (e.g. read from or written into). When returning such buffer to +// the client, component must provide a new fence that must signal before the returned buffer can +// be used (e.g. read from or written into). The component owns the incoming fenceFd, and must close +// it when fence has signaled. The client will own and close the returned fence file descriptor. +// +// If the component supports this using the "OMX.google.android.index.storeMetaDataInBuffers" +// extension and bStoreMetaData is set to OMX_TRUE, data is passed using VideoGrallocMetadata +// (the layout of which is the VideoGrallocMetadata defined below). Camera input can be also passed +// as "CameraSource", the layout of which is vendor dependent. +// +// Metadata buffers are registered with the component using UseBuffer calls, or can be allocated +// by the component for encoder-metadata-output buffers. +struct StoreMetaDataInBuffersParams { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bStoreMetaData; +}; + +// Meta data buffer layout used to transport output frames to the decoder for +// dynamic buffer handling. +struct VideoGrallocMetadata { + MetadataBufferType eType; // must be kMetadataBufferTypeGrallocSource +#ifdef OMX_ANDROID_COMPILE_AS_32BIT_ON_64BIT_PLATFORMS + OMX_PTR pHandle; +#else + buffer_handle_t pHandle; +#endif +}; + +// Legacy name for VideoGrallocMetadata struct. +struct VideoDecoderOutputMetaData : public VideoGrallocMetadata {}; + +struct VideoNativeMetadata { + MetadataBufferType eType; // must be kMetadataBufferTypeANWBuffer +#ifdef OMX_ANDROID_COMPILE_AS_32BIT_ON_64BIT_PLATFORMS + OMX_PTR pBuffer; +#else + struct ANativeWindowBuffer* pBuffer; +#endif + int nFenceFd; // -1 if unused +}; + +// A pointer to this struct is passed to OMX_SetParameter() when the extension +// index "OMX.google.android.index.prepareForAdaptivePlayback" is given. +// +// This method is used to signal a video decoder, that the user has requested +// seamless resolution change support (if bEnable is set to OMX_TRUE). +// nMaxFrameWidth and nMaxFrameHeight are the dimensions of the largest +// anticipated frames in the video. If bEnable is OMX_FALSE, no resolution +// change is expected, and the nMaxFrameWidth/Height fields are unused. +// +// If the decoder supports dynamic output buffers, it may ignore this +// request. Otherwise, it shall request resources in such a way so that it +// avoids full port-reconfiguration (due to output port-definition change) +// during resolution changes. +// +// DO NOT USE THIS STRUCTURE AS IT WILL BE REMOVED. INSTEAD, IMPLEMENT +// METADATA SUPPORT FOR VIDEO DECODERS. +struct PrepareForAdaptivePlaybackParams { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bEnable; + OMX_U32 nMaxFrameWidth; + OMX_U32 nMaxFrameHeight; +}; + +// A pointer to this struct is passed to OMX_SetParameter when the extension +// index for the 'OMX.google.android.index.useAndroidNativeBuffer' extension is +// given. This call will only be performed if a prior call was made with the +// 'OMX.google.android.index.enableAndroidNativeBuffers' extension index, +// enabling use of Android native buffers. +struct UseAndroidNativeBufferParams { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_PTR pAppPrivate; + OMX_BUFFERHEADERTYPE **bufferHeader; + const sp& nativeBuffer; +}; + +// A pointer to this struct is passed to OMX_GetParameter when the extension +// index for the 'OMX.google.android.index.getAndroidNativeBufferUsage' +// extension is given. The usage bits returned from this query will be used to +// allocate the Gralloc buffers that get passed to the useAndroidNativeBuffer +// command. +struct GetAndroidNativeBufferUsageParams { + OMX_U32 nSize; // IN + OMX_VERSIONTYPE nVersion; // IN + OMX_U32 nPortIndex; // IN + OMX_U32 nUsage; // OUT +}; + +// An enum OMX_COLOR_FormatAndroidOpaque to indicate an opaque colorformat +// is declared in media/stagefright/openmax/OMX_IVCommon.h +// This will inform the encoder that the actual +// colorformat will be relayed by the GRalloc Buffers. +// OMX_COLOR_FormatAndroidOpaque = 0x7F000001, + +// A pointer to this struct is passed to OMX_SetParameter when the extension +// index for the 'OMX.google.android.index.prependSPSPPSToIDRFrames' extension +// is given. +// A successful result indicates that future IDR frames will be prefixed by +// SPS/PPS. +struct PrependSPSPPSToIDRFramesParams { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_BOOL bEnable; +}; + +// Structure describing a media image (frame) +// Currently only supporting YUV +struct MediaImage { + enum Type { + MEDIA_IMAGE_TYPE_UNKNOWN = 0, + MEDIA_IMAGE_TYPE_YUV, + }; + + enum PlaneIndex { + Y = 0, + U, + V, + MAX_NUM_PLANES + }; + + Type mType; + uint32_t mNumPlanes; // number of planes + uint32_t mWidth; // width of largest plane (unpadded, as in nFrameWidth) + uint32_t mHeight; // height of largest plane (unpadded, as in nFrameHeight) + uint32_t mBitDepth; // useable bit depth + struct PlaneInfo { + uint32_t mOffset; // offset of first pixel of the plane in bytes + // from buffer offset + uint32_t mColInc; // column increment in bytes + uint32_t mRowInc; // row increment in bytes + uint32_t mHorizSubsampling; // subsampling compared to the largest plane + uint32_t mVertSubsampling; // subsampling compared to the largest plane + }; + PlaneInfo mPlane[MAX_NUM_PLANES]; +}; + +// A pointer to this struct is passed to OMX_GetParameter when the extension +// index for the 'OMX.google.android.index.describeColorFormat' +// extension is given. This method can be called from any component state +// other than invalid. The color-format, frame width/height, and stride/ +// slice-height parameters are ones that are associated with a raw video +// port (input or output), but the stride/slice height parameters may be +// incorrect. bUsingNativeBuffers is OMX_TRUE if native android buffers will +// be used (while specifying this color format). +// +// The component shall fill out the MediaImage structure that +// corresponds to the described raw video format, and the potentially corrected +// stride and slice-height info. +// +// The behavior is slightly different if bUsingNativeBuffers is OMX_TRUE, +// though most implementations can ignore this difference. When using native buffers, +// the component may change the configured color format to an optimized format. +// Additionally, when allocating these buffers for flexible usecase, the framework +// will set the SW_READ/WRITE_OFTEN usage flags. In this case (if bUsingNativeBuffers +// is OMX_TRUE), the component shall fill out the MediaImage information for the +// scenario when these SW-readable/writable buffers are locked using gralloc_lock. +// Note, that these buffers may also be locked using gralloc_lock_ycbcr, which must +// be supported for vendor-specific formats. +// +// For non-YUV packed planar/semiplanar image formats, or if bUsingNativeBuffers +// is OMX_TRUE and the component does not support this color format with native +// buffers, the component shall set mNumPlanes to 0, and mType to MEDIA_IMAGE_TYPE_UNKNOWN. +struct DescribeColorFormatParams { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + // input: parameters from OMX_VIDEO_PORTDEFINITIONTYPE + OMX_COLOR_FORMATTYPE eColorFormat; + OMX_U32 nFrameWidth; + OMX_U32 nFrameHeight; + OMX_U32 nStride; + OMX_U32 nSliceHeight; + OMX_BOOL bUsingNativeBuffers; + + // output: fill out the MediaImage fields + MediaImage sMediaImage; +}; + +// A pointer to this struct is passed to OMX_SetParameter or OMX_GetParameter +// when the extension index for the +// 'OMX.google.android.index.configureVideoTunnelMode' extension is given. +// If the extension is supported then tunneled playback mode should be supported +// by the codec. If bTunneled is set to OMX_TRUE then the video decoder should +// operate in "tunneled" mode and output its decoded frames directly to the +// sink. In this case nAudioHwSync is the HW SYNC ID of the audio HAL Output +// stream to sync the video with. If bTunneled is set to OMX_FALSE, "tunneled" +// mode should be disabled and nAudioHwSync should be ignored. +// OMX_GetParameter is used to query tunneling configuration. bTunneled should +// return whether decoder is operating in tunneled mode, and if it is, +// pSidebandWindow should contain the codec allocated sideband window handle. +struct ConfigureVideoTunnelModeParams { + OMX_U32 nSize; // IN + OMX_VERSIONTYPE nVersion; // IN + OMX_U32 nPortIndex; // IN + OMX_BOOL bTunneled; // IN/OUT + OMX_U32 nAudioHwSync; // IN + OMX_PTR pSidebandWindow; // OUT +}; + +} // namespace android + +extern android::OMXPluginBase *createOMXPlugin(); + +#endif // HARDWARE_API_H_ diff --git a/phonelibs/android_frameworks_native/include/media/hardware/MetadataBufferType.h b/phonelibs/android_frameworks_native/include/media/hardware/MetadataBufferType.h new file mode 100644 index 0000000000..b765203956 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/media/hardware/MetadataBufferType.h @@ -0,0 +1,127 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef METADATA_BUFFER_TYPE_H +#define METADATA_BUFFER_TYPE_H + +#ifdef __cplusplus +extern "C" { +namespace android { +#endif + +/* + * MetadataBufferType defines the type of the metadata buffers that + * can be passed to video encoder component for encoding, via Stagefright + * media recording framework. To see how to work with the metadata buffers + * in media recording framework, please consult HardwareAPI.h + * + * The creator of metadata buffers and video encoder share common knowledge + * on what is actually being stored in these metadata buffers, and + * how the information can be used by the video encoder component + * to locate the actual pixel data as the source input for video + * encoder, plus whatever other information that is necessary. Stagefright + * media recording framework does not need to know anything specific about the + * metadata buffers, except for receving each individual metadata buffer + * as the source input, making a copy of the metadata buffer, and passing the + * copy via OpenMAX API to the video encoder component. + * + * The creator of the metadata buffers must ensure that the first + * 4 bytes in every metadata buffer indicates its buffer type, + * and the rest of the metadata buffer contains the + * actual metadata information. When a video encoder component receives + * a metadata buffer, it uses the first 4 bytes in that buffer to find + * out the type of the metadata buffer, and takes action appropriate + * to that type of metadata buffers (for instance, locate the actual + * pixel data input and then encoding the input data to produce a + * compressed output buffer). + * + * The following shows the layout of a metadata buffer, + * where buffer type is a 4-byte field of MetadataBufferType, + * and the payload is the metadata information. + * + * -------------------------------------------------------------- + * | buffer type | payload | + * -------------------------------------------------------------- + * + */ +typedef enum { + + /* + * kMetadataBufferTypeCameraSource is used to indicate that + * the source of the metadata buffer is the camera component. + */ + kMetadataBufferTypeCameraSource = 0, + + /* + * kMetadataBufferTypeGrallocSource is used to indicate that + * the payload of the metadata buffers can be interpreted as + * a buffer_handle_t. + * So in this case,the metadata that the encoder receives + * will have a byte stream that consists of two parts: + * 1. First, there is an integer indicating that it is a GRAlloc + * source (kMetadataBufferTypeGrallocSource) + * 2. This is followed by the buffer_handle_t that is a handle to the + * GRalloc buffer. The encoder needs to interpret this GRalloc handle + * and encode the frames. + * -------------------------------------------------------------- + * | kMetadataBufferTypeGrallocSource | buffer_handle_t buffer | + * -------------------------------------------------------------- + * + * See the VideoGrallocMetadata structure. + */ + kMetadataBufferTypeGrallocSource = 1, + + /* + * kMetadataBufferTypeGraphicBuffer is used to indicate that + * the payload of the metadata buffers can be interpreted as + * an ANativeWindowBuffer, and that a fence is provided. + * + * In this case, the metadata will have a byte stream that consists of three parts: + * 1. First, there is an integer indicating that the metadata + * contains an ANativeWindowBuffer (kMetadataBufferTypeANWBuffer) + * 2. This is followed by the pointer to the ANativeWindowBuffer. + * Codec must not free this buffer as it does not actually own this buffer. + * 3. Finally, there is an integer containing a fence file descriptor. + * The codec must wait on the fence before encoding or decoding into this + * buffer. When the buffer is returned, codec must replace this file descriptor + * with a new fence, that will be waited on before the buffer is replaced + * (encoder) or read (decoder). + * --------------------------------- + * | kMetadataBufferTypeANWBuffer | + * --------------------------------- + * | ANativeWindowBuffer *buffer | + * --------------------------------- + * | int fenceFd | + * --------------------------------- + * + * See the VideoNativeMetadata structure. + */ + kMetadataBufferTypeANWBuffer = 2, + + /* This value is used by framework, but is never used inside a metadata buffer */ + kMetadataBufferTypeInvalid = -1, + + + // Add more here... + +} MetadataBufferType; + +#ifdef __cplusplus +} // namespace android +} +#endif + +#endif // METADATA_BUFFER_TYPE_H diff --git a/phonelibs/android_frameworks_native/include/media/hardware/OMXPluginBase.h b/phonelibs/android_frameworks_native/include/media/hardware/OMXPluginBase.h new file mode 100644 index 0000000000..7bf414739b --- /dev/null +++ b/phonelibs/android_frameworks_native/include/media/hardware/OMXPluginBase.h @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OMX_PLUGIN_BASE_H_ + +#define OMX_PLUGIN_BASE_H_ + +#include + +#include + +#include +#include + +namespace android { + +struct OMXPluginBase { + OMXPluginBase() {} + virtual ~OMXPluginBase() {} + + virtual OMX_ERRORTYPE makeComponentInstance( + const char *name, + const OMX_CALLBACKTYPE *callbacks, + OMX_PTR appData, + OMX_COMPONENTTYPE **component) = 0; + + virtual OMX_ERRORTYPE destroyComponentInstance( + OMX_COMPONENTTYPE *component) = 0; + + virtual OMX_ERRORTYPE enumerateComponents( + OMX_STRING name, + size_t size, + OMX_U32 index) = 0; + + virtual OMX_ERRORTYPE getRolesOfComponent( + const char *name, + Vector *roles) = 0; + +private: + OMXPluginBase(const OMXPluginBase &); + OMXPluginBase &operator=(const OMXPluginBase &); +}; + +} // namespace android + +#endif // OMX_PLUGIN_BASE_H_ diff --git a/phonelibs/android_frameworks_native/include/media/openmax/OMX_AsString.h b/phonelibs/android_frameworks_native/include/media/openmax/OMX_AsString.h new file mode 100644 index 0000000000..ae8430d856 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/media/openmax/OMX_AsString.h @@ -0,0 +1,947 @@ +/* + * Copyright 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* NOTE: This file contains several sections for individual OMX include files. + Each section has its own include guard. This file should be included AFTER + the OMX include files. */ + +#ifdef OMX_Audio_h +/* asString definitions if media/openmax/OMX_Audio.h was included */ + +#ifndef AS_STRING_FOR_OMX_AUDIO_H +#define AS_STRING_FOR_OMX_AUDIO_H + +inline static const char *asString(OMX_AUDIO_CODINGTYPE i, const char *def = "??") { + switch (i) { + case OMX_AUDIO_CodingUnused: return "Unused"; // unused + case OMX_AUDIO_CodingAutoDetect: return "AutoDetect"; // unused + case OMX_AUDIO_CodingPCM: return "PCM"; + case OMX_AUDIO_CodingADPCM: return "ADPCM"; // unused + case OMX_AUDIO_CodingAMR: return "AMR"; + case OMX_AUDIO_CodingGSMFR: return "GSMFR"; + case OMX_AUDIO_CodingGSMEFR: return "GSMEFR"; // unused + case OMX_AUDIO_CodingGSMHR: return "GSMHR"; // unused + case OMX_AUDIO_CodingPDCFR: return "PDCFR"; // unused + case OMX_AUDIO_CodingPDCEFR: return "PDCEFR"; // unused + case OMX_AUDIO_CodingPDCHR: return "PDCHR"; // unused + case OMX_AUDIO_CodingTDMAFR: return "TDMAFR"; // unused + case OMX_AUDIO_CodingTDMAEFR: return "TDMAEFR"; // unused + case OMX_AUDIO_CodingQCELP8: return "QCELP8"; // unused + case OMX_AUDIO_CodingQCELP13: return "QCELP13"; // unused + case OMX_AUDIO_CodingEVRC: return "EVRC"; // unused + case OMX_AUDIO_CodingSMV: return "SMV"; // unused + case OMX_AUDIO_CodingG711: return "G711"; + case OMX_AUDIO_CodingG723: return "G723"; // unused + case OMX_AUDIO_CodingG726: return "G726"; // unused + case OMX_AUDIO_CodingG729: return "G729"; // unused + case OMX_AUDIO_CodingAAC: return "AAC"; + case OMX_AUDIO_CodingMP3: return "MP3"; + case OMX_AUDIO_CodingSBC: return "SBC"; // unused + case OMX_AUDIO_CodingVORBIS: return "VORBIS"; + case OMX_AUDIO_CodingWMA: return "WMA"; // unused + case OMX_AUDIO_CodingRA: return "RA"; // unused + case OMX_AUDIO_CodingMIDI: return "MIDI"; // unused + case OMX_AUDIO_CodingFLAC: return "FLAC"; + default: return def; + } +} + +inline static const char *asString(OMX_AUDIO_PCMMODETYPE i, const char *def = "??") { + switch (i) { + case OMX_AUDIO_PCMModeLinear: return "Linear"; + case OMX_AUDIO_PCMModeALaw: return "ALaw"; + case OMX_AUDIO_PCMModeMULaw: return "MULaw"; + default: return def; + } +} + +inline static const char *asString(OMX_AUDIO_CHANNELTYPE i, const char *def = "??") { + switch (i) { + case OMX_AUDIO_ChannelNone: return "None"; // unused + case OMX_AUDIO_ChannelLF: return "LF"; + case OMX_AUDIO_ChannelRF: return "RF"; + case OMX_AUDIO_ChannelCF: return "CF"; + case OMX_AUDIO_ChannelLS: return "LS"; + case OMX_AUDIO_ChannelRS: return "RS"; + case OMX_AUDIO_ChannelLFE: return "LFE"; + case OMX_AUDIO_ChannelCS: return "CS"; + case OMX_AUDIO_ChannelLR: return "LR"; + case OMX_AUDIO_ChannelRR: return "RR"; + default: return def; + } +} + +inline static const char *asString(OMX_AUDIO_CHANNELMODETYPE i, const char *def = "??") { + switch (i) { + case OMX_AUDIO_ChannelModeStereo: return "Stereo"; +// case OMX_AUDIO_ChannelModeJointStereo: return "JointStereo"; +// case OMX_AUDIO_ChannelModeDual: return "Dual"; + case OMX_AUDIO_ChannelModeMono: return "Mono"; + default: return def; + } +} + +inline static const char *asString(OMX_AUDIO_AACSTREAMFORMATTYPE i, const char *def = "??") { + switch (i) { +// case OMX_AUDIO_AACStreamFormatMP2ADTS: return "MP2ADTS"; + case OMX_AUDIO_AACStreamFormatMP4ADTS: return "MP4ADTS"; +// case OMX_AUDIO_AACStreamFormatMP4LOAS: return "MP4LOAS"; +// case OMX_AUDIO_AACStreamFormatMP4LATM: return "MP4LATM"; +// case OMX_AUDIO_AACStreamFormatADIF: return "ADIF"; + case OMX_AUDIO_AACStreamFormatMP4FF: return "MP4FF"; +// case OMX_AUDIO_AACStreamFormatRAW: return "RAW"; + default: return def; + } +} + +inline static const char *asString(OMX_AUDIO_AMRFRAMEFORMATTYPE i, const char *def = "??") { + switch (i) { +// case OMX_AUDIO_AMRFrameFormatConformance: return "Conformance"; +// case OMX_AUDIO_AMRFrameFormatIF1: return "IF1"; +// case OMX_AUDIO_AMRFrameFormatIF2: return "IF2"; + case OMX_AUDIO_AMRFrameFormatFSF: return "FSF"; +// case OMX_AUDIO_AMRFrameFormatRTPPayload: return "RTPPayload"; +// case OMX_AUDIO_AMRFrameFormatITU: return "ITU"; + default: return def; + } +} + +inline static const char *asString(OMX_AUDIO_AMRBANDMODETYPE i, const char *def = "??") { + switch (i) { + case OMX_AUDIO_AMRBandModeUnused: return "Unused"; + case OMX_AUDIO_AMRBandModeNB0: return "NB0"; + case OMX_AUDIO_AMRBandModeNB1: return "NB1"; + case OMX_AUDIO_AMRBandModeNB2: return "NB2"; + case OMX_AUDIO_AMRBandModeNB3: return "NB3"; + case OMX_AUDIO_AMRBandModeNB4: return "NB4"; + case OMX_AUDIO_AMRBandModeNB5: return "NB5"; + case OMX_AUDIO_AMRBandModeNB6: return "NB6"; + case OMX_AUDIO_AMRBandModeNB7: return "NB7"; + case OMX_AUDIO_AMRBandModeWB0: return "WB0"; + case OMX_AUDIO_AMRBandModeWB1: return "WB1"; + case OMX_AUDIO_AMRBandModeWB2: return "WB2"; + case OMX_AUDIO_AMRBandModeWB3: return "WB3"; + case OMX_AUDIO_AMRBandModeWB4: return "WB4"; + case OMX_AUDIO_AMRBandModeWB5: return "WB5"; + case OMX_AUDIO_AMRBandModeWB6: return "WB6"; + case OMX_AUDIO_AMRBandModeWB7: return "WB7"; + case OMX_AUDIO_AMRBandModeWB8: return "WB8"; + default: return def; + } +} + +inline static const char *asString(OMX_AUDIO_AMRDTXMODETYPE i, const char *def = "??") { + switch (i) { + case OMX_AUDIO_AMRDTXModeOff: return "ModeOff"; +// case OMX_AUDIO_AMRDTXModeOnVAD1: return "ModeOnVAD1"; +// case OMX_AUDIO_AMRDTXModeOnVAD2: return "ModeOnVAD2"; +// case OMX_AUDIO_AMRDTXModeOnAuto: return "ModeOnAuto"; +// case OMX_AUDIO_AMRDTXasEFR: return "asEFR"; + default: return def; + } +} + +#endif // AS_STRING_FOR_OMX_AUDIO_H + +#endif // OMX_Audio_h + +#ifdef OMX_AudioExt_h +/* asString definitions if media/openmax/OMX_AudioExt.h was included */ + +#ifndef AS_STRING_FOR_OMX_AUDIOEXT_H +#define AS_STRING_FOR_OMX_AUDIOEXT_H + +inline static const char *asString(OMX_AUDIO_CODINGEXTTYPE i, const char *def = "??") { + switch (i) { + case OMX_AUDIO_CodingAndroidAC3: return "AndroidAC3"; + case OMX_AUDIO_CodingAndroidOPUS: return "AndroidOPUS"; + default: return asString((OMX_AUDIO_CODINGTYPE)i, def); + } +} + +#endif // AS_STRING_FOR_OMX_AUDIOEXT_H + +#endif // OMX_AudioExt_h + +#ifdef OMX_Component_h +/* asString definitions if media/openmax/OMX_Component.h was included */ + +#ifndef AS_STRING_FOR_OMX_COMPONENT_H +#define AS_STRING_FOR_OMX_COMPONENT_H + +inline static const char *asString(OMX_PORTDOMAINTYPE i, const char *def = "??") { + switch (i) { + case OMX_PortDomainAudio: return "Audio"; + case OMX_PortDomainVideo: return "Video"; + case OMX_PortDomainImage: return "Image"; +// case OMX_PortDomainOther: return "Other"; + default: return def; + } +} + +#endif // AS_STRING_FOR_OMX_COMPONENT_H + +#endif // OMX_Component_h + +#ifdef OMX_Core_h +/* asString definitions if media/openmax/OMX_Core.h was included */ + +#ifndef AS_STRING_FOR_OMX_CORE_H +#define AS_STRING_FOR_OMX_CORE_H + +inline static const char *asString(OMX_COMMANDTYPE i, const char *def = "??") { + switch (i) { + case OMX_CommandStateSet: return "StateSet"; + case OMX_CommandFlush: return "Flush"; + case OMX_CommandPortDisable: return "PortDisable"; + case OMX_CommandPortEnable: return "PortEnable"; +// case OMX_CommandMarkBuffer: return "MarkBuffer"; + default: return def; + } +} + +inline static const char *asString(OMX_STATETYPE i, const char *def = "??") { + switch (i) { + case OMX_StateInvalid: return "Invalid"; + case OMX_StateLoaded: return "Loaded"; + case OMX_StateIdle: return "Idle"; + case OMX_StateExecuting: return "Executing"; +// case OMX_StatePause: return "Pause"; +// case OMX_StateWaitForResources: return "WaitForResources"; + default: return def; + } +} + +inline static const char *asString(OMX_ERRORTYPE i, const char *def = "??") { + switch (i) { + case OMX_ErrorNone: return "None"; + case OMX_ErrorInsufficientResources: return "InsufficientResources"; + case OMX_ErrorUndefined: return "Undefined"; + case OMX_ErrorInvalidComponentName: return "InvalidComponentName"; + case OMX_ErrorComponentNotFound: return "ComponentNotFound"; + case OMX_ErrorInvalidComponent: return "InvalidComponent"; // unused + case OMX_ErrorBadParameter: return "BadParameter"; + case OMX_ErrorNotImplemented: return "NotImplemented"; + case OMX_ErrorUnderflow: return "Underflow"; // unused + case OMX_ErrorOverflow: return "Overflow"; // unused + case OMX_ErrorHardware: return "Hardware"; // unused + case OMX_ErrorInvalidState: return "InvalidState"; + case OMX_ErrorStreamCorrupt: return "StreamCorrupt"; + case OMX_ErrorPortsNotCompatible: return "PortsNotCompatible"; // unused + case OMX_ErrorResourcesLost: return "ResourcesLost"; + case OMX_ErrorNoMore: return "NoMore"; + case OMX_ErrorVersionMismatch: return "VersionMismatch"; // unused + case OMX_ErrorNotReady: return "NotReady"; // unused + case OMX_ErrorTimeout: return "Timeout"; // unused + case OMX_ErrorSameState: return "SameState"; // unused + case OMX_ErrorResourcesPreempted: return "ResourcesPreempted"; // unused + case OMX_ErrorPortUnresponsiveDuringAllocation: + return "PortUnresponsiveDuringAllocation"; // unused + case OMX_ErrorPortUnresponsiveDuringDeallocation: + return "PortUnresponsiveDuringDeallocation"; // unused + case OMX_ErrorPortUnresponsiveDuringStop: + return "PortUnresponsiveDuringStop"; // unused + case OMX_ErrorIncorrectStateTransition: + return "IncorrectStateTransition"; // unused + case OMX_ErrorIncorrectStateOperation: + return "IncorrectStateOperation"; // unused + case OMX_ErrorUnsupportedSetting: return "UnsupportedSetting"; + case OMX_ErrorUnsupportedIndex: return "UnsupportedIndex"; + case OMX_ErrorBadPortIndex: return "BadPortIndex"; + case OMX_ErrorPortUnpopulated: return "PortUnpopulated"; // unused + case OMX_ErrorComponentSuspended: return "ComponentSuspended"; // unused + case OMX_ErrorDynamicResourcesUnavailable: + return "DynamicResourcesUnavailable"; // unused + case OMX_ErrorMbErrorsInFrame: return "MbErrorsInFrame"; // unused + case OMX_ErrorFormatNotDetected: return "FormatNotDetected"; // unused + case OMX_ErrorContentPipeOpenFailed: return "ContentPipeOpenFailed"; // unused + case OMX_ErrorContentPipeCreationFailed: + return "ContentPipeCreationFailed"; // unused + case OMX_ErrorSeperateTablesUsed: return "SeperateTablesUsed"; // unused + case OMX_ErrorTunnelingUnsupported: return "TunnelingUnsupported"; // unused + default: return def; + } +} + +inline static const char *asString(OMX_EVENTTYPE i, const char *def = "??") { + switch (i) { + case OMX_EventCmdComplete: return "CmdComplete"; + case OMX_EventError: return "Error"; +// case OMX_EventMark: return "Mark"; + case OMX_EventPortSettingsChanged: return "PortSettingsChanged"; + case OMX_EventBufferFlag: return "BufferFlag"; +// case OMX_EventResourcesAcquired: return "ResourcesAcquired"; +// case OMX_EventComponentResumed: return "ComponentResumed"; +// case OMX_EventDynamicResourcesAvailable: return "DynamicResourcesAvailable"; +// case OMX_EventPortFormatDetected: return "PortFormatDetected"; + case OMX_EventOutputRendered: return "OutputRendered"; + default: return def; + } +} + +#endif // AS_STRING_FOR_OMX_CORE_H + +#endif // OMX_Core_h + +#ifdef OMX_Image_h +/* asString definitions if media/openmax/OMX_Image.h was included */ + +#ifndef AS_STRING_FOR_OMX_IMAGE_H +#define AS_STRING_FOR_OMX_IMAGE_H + +inline static const char *asString(OMX_IMAGE_CODINGTYPE i, const char *def = "??") { + switch (i) { + case OMX_IMAGE_CodingUnused: return "Unused"; + case OMX_IMAGE_CodingAutoDetect: return "AutoDetect"; // unused + case OMX_IMAGE_CodingJPEG: return "JPEG"; + case OMX_IMAGE_CodingJPEG2K: return "JPEG2K"; // unused + case OMX_IMAGE_CodingEXIF: return "EXIF"; // unused + case OMX_IMAGE_CodingTIFF: return "TIFF"; // unused + case OMX_IMAGE_CodingGIF: return "GIF"; // unused + case OMX_IMAGE_CodingPNG: return "PNG"; // unused + case OMX_IMAGE_CodingLZW: return "LZW"; // unused + case OMX_IMAGE_CodingBMP: return "BMP"; // unused + default: return def; + } +} + +#endif // AS_STRING_FOR_OMX_IMAGE_H + +#endif // OMX_Image_h + +#ifdef OMX_Index_h +/* asString definitions if media/openmax/OMX_Index.h was included */ + +#ifndef AS_STRING_FOR_OMX_INDEX_H +#define AS_STRING_FOR_OMX_INDEX_H + +inline static const char *asString(OMX_INDEXTYPE i, const char *def = "??") { + switch (i) { +// case OMX_IndexParamPriorityMgmt: return "ParamPriorityMgmt"; +// case OMX_IndexParamAudioInit: return "ParamAudioInit"; +// case OMX_IndexParamImageInit: return "ParamImageInit"; +// case OMX_IndexParamVideoInit: return "ParamVideoInit"; +// case OMX_IndexParamOtherInit: return "ParamOtherInit"; +// case OMX_IndexParamNumAvailableStreams: return "ParamNumAvailableStreams"; +// case OMX_IndexParamActiveStream: return "ParamActiveStream"; +// case OMX_IndexParamSuspensionPolicy: return "ParamSuspensionPolicy"; +// case OMX_IndexParamComponentSuspended: return "ParamComponentSuspended"; +// case OMX_IndexConfigCapturing: return "ConfigCapturing"; +// case OMX_IndexConfigCaptureMode: return "ConfigCaptureMode"; +// case OMX_IndexAutoPauseAfterCapture: return "AutoPauseAfterCapture"; +// case OMX_IndexParamContentURI: return "ParamContentURI"; +// case OMX_IndexParamCustomContentPipe: return "ParamCustomContentPipe"; +// case OMX_IndexParamDisableResourceConcealment: +// return "ParamDisableResourceConcealment"; +// case OMX_IndexConfigMetadataItemCount: return "ConfigMetadataItemCount"; +// case OMX_IndexConfigContainerNodeCount: return "ConfigContainerNodeCount"; +// case OMX_IndexConfigMetadataItem: return "ConfigMetadataItem"; +// case OMX_IndexConfigCounterNodeID: return "ConfigCounterNodeID"; +// case OMX_IndexParamMetadataFilterType: return "ParamMetadataFilterType"; +// case OMX_IndexParamMetadataKeyFilter: return "ParamMetadataKeyFilter"; +// case OMX_IndexConfigPriorityMgmt: return "ConfigPriorityMgmt"; + case OMX_IndexParamStandardComponentRole: return "ParamStandardComponentRole"; + case OMX_IndexParamPortDefinition: return "ParamPortDefinition"; +// case OMX_IndexParamCompBufferSupplier: return "ParamCompBufferSupplier"; + case OMX_IndexParamAudioPortFormat: return "ParamAudioPortFormat"; + case OMX_IndexParamAudioPcm: return "ParamAudioPcm"; + case OMX_IndexParamAudioAac: return "ParamAudioAac"; +// case OMX_IndexParamAudioRa: return "ParamAudioRa"; + case OMX_IndexParamAudioMp3: return "ParamAudioMp3"; +// case OMX_IndexParamAudioAdpcm: return "ParamAudioAdpcm"; +// case OMX_IndexParamAudioG723: return "ParamAudioG723"; +// case OMX_IndexParamAudioG729: return "ParamAudioG729"; + case OMX_IndexParamAudioAmr: return "ParamAudioAmr"; +// case OMX_IndexParamAudioWma: return "ParamAudioWma"; +// case OMX_IndexParamAudioSbc: return "ParamAudioSbc"; +// case OMX_IndexParamAudioMidi: return "ParamAudioMidi"; +// case OMX_IndexParamAudioGsm_FR: return "ParamAudioGsm_FR"; +// case OMX_IndexParamAudioMidiLoadUserSound: return "ParamAudioMidiLoadUserSound"; +// case OMX_IndexParamAudioG726: return "ParamAudioG726"; +// case OMX_IndexParamAudioGsm_EFR: return "ParamAudioGsm_EFR"; +// case OMX_IndexParamAudioGsm_HR: return "ParamAudioGsm_HR"; +// case OMX_IndexParamAudioPdc_FR: return "ParamAudioPdc_FR"; +// case OMX_IndexParamAudioPdc_EFR: return "ParamAudioPdc_EFR"; +// case OMX_IndexParamAudioPdc_HR: return "ParamAudioPdc_HR"; +// case OMX_IndexParamAudioTdma_FR: return "ParamAudioTdma_FR"; +// case OMX_IndexParamAudioTdma_EFR: return "ParamAudioTdma_EFR"; +// case OMX_IndexParamAudioQcelp8: return "ParamAudioQcelp8"; +// case OMX_IndexParamAudioQcelp13: return "ParamAudioQcelp13"; +// case OMX_IndexParamAudioEvrc: return "ParamAudioEvrc"; +// case OMX_IndexParamAudioSmv: return "ParamAudioSmv"; + case OMX_IndexParamAudioVorbis: return "ParamAudioVorbis"; + case OMX_IndexParamAudioFlac: return "ParamAudioFlac"; +// case OMX_IndexConfigAudioMidiImmediateEvent: return "ConfigAudioMidiImmediateEvent"; +// case OMX_IndexConfigAudioMidiControl: return "ConfigAudioMidiControl"; +// case OMX_IndexConfigAudioMidiSoundBankProgram: +// return "ConfigAudioMidiSoundBankProgram"; +// case OMX_IndexConfigAudioMidiStatus: return "ConfigAudioMidiStatus"; +// case OMX_IndexConfigAudioMidiMetaEvent: return "ConfigAudioMidiMetaEvent"; +// case OMX_IndexConfigAudioMidiMetaEventData: return "ConfigAudioMidiMetaEventData"; +// case OMX_IndexConfigAudioVolume: return "ConfigAudioVolume"; +// case OMX_IndexConfigAudioBalance: return "ConfigAudioBalance"; +// case OMX_IndexConfigAudioChannelMute: return "ConfigAudioChannelMute"; +// case OMX_IndexConfigAudioMute: return "ConfigAudioMute"; +// case OMX_IndexConfigAudioLoudness: return "ConfigAudioLoudness"; +// case OMX_IndexConfigAudioEchoCancelation: return "ConfigAudioEchoCancelation"; +// case OMX_IndexConfigAudioNoiseReduction: return "ConfigAudioNoiseReduction"; +// case OMX_IndexConfigAudioBass: return "ConfigAudioBass"; +// case OMX_IndexConfigAudioTreble: return "ConfigAudioTreble"; +// case OMX_IndexConfigAudioStereoWidening: return "ConfigAudioStereoWidening"; +// case OMX_IndexConfigAudioChorus: return "ConfigAudioChorus"; +// case OMX_IndexConfigAudioEqualizer: return "ConfigAudioEqualizer"; +// case OMX_IndexConfigAudioReverberation: return "ConfigAudioReverberation"; +// case OMX_IndexConfigAudioChannelVolume: return "ConfigAudioChannelVolume"; +// case OMX_IndexParamImagePortFormat: return "ParamImagePortFormat"; +// case OMX_IndexParamFlashControl: return "ParamFlashControl"; +// case OMX_IndexConfigFocusControl: return "ConfigFocusControl"; +// case OMX_IndexParamQFactor: return "ParamQFactor"; +// case OMX_IndexParamQuantizationTable: return "ParamQuantizationTable"; +// case OMX_IndexParamHuffmanTable: return "ParamHuffmanTable"; +// case OMX_IndexConfigFlashControl: return "ConfigFlashControl"; + case OMX_IndexParamVideoPortFormat: return "ParamVideoPortFormat"; +// case OMX_IndexParamVideoQuantization: return "ParamVideoQuantization"; +// case OMX_IndexParamVideoFastUpdate: return "ParamVideoFastUpdate"; + case OMX_IndexParamVideoBitrate: return "ParamVideoBitrate"; +// case OMX_IndexParamVideoMotionVector: return "ParamVideoMotionVector"; + case OMX_IndexParamVideoIntraRefresh: return "ParamVideoIntraRefresh"; + case OMX_IndexParamVideoErrorCorrection: return "ParamVideoErrorCorrection"; +// case OMX_IndexParamVideoVBSMC: return "ParamVideoVBSMC"; +// case OMX_IndexParamVideoMpeg2: return "ParamVideoMpeg2"; + case OMX_IndexParamVideoMpeg4: return "ParamVideoMpeg4"; +// case OMX_IndexParamVideoWmv: return "ParamVideoWmv"; +// case OMX_IndexParamVideoRv: return "ParamVideoRv"; + case OMX_IndexParamVideoAvc: return "ParamVideoAvc"; + case OMX_IndexParamVideoH263: return "ParamVideoH263"; + case OMX_IndexParamVideoProfileLevelQuerySupported: + return "ParamVideoProfileLevelQuerySupported"; + case OMX_IndexParamVideoProfileLevelCurrent: return "ParamVideoProfileLevelCurrent"; + case OMX_IndexConfigVideoBitrate: return "ConfigVideoBitrate"; +// case OMX_IndexConfigVideoFramerate: return "ConfigVideoFramerate"; + case OMX_IndexConfigVideoIntraVOPRefresh: return "ConfigVideoIntraVOPRefresh"; +// case OMX_IndexConfigVideoIntraMBRefresh: return "ConfigVideoIntraMBRefresh"; +// case OMX_IndexConfigVideoMBErrorReporting: return "ConfigVideoMBErrorReporting"; +// case OMX_IndexParamVideoMacroblocksPerFrame: return "ParamVideoMacroblocksPerFrame"; +// case OMX_IndexConfigVideoMacroBlockErrorMap: return "ConfigVideoMacroBlockErrorMap"; +// case OMX_IndexParamVideoSliceFMO: return "ParamVideoSliceFMO"; +// case OMX_IndexConfigVideoAVCIntraPeriod: return "ConfigVideoAVCIntraPeriod"; +// case OMX_IndexConfigVideoNalSize: return "ConfigVideoNalSize"; +// case OMX_IndexParamCommonDeblocking: return "ParamCommonDeblocking"; +// case OMX_IndexParamCommonSensorMode: return "ParamCommonSensorMode"; +// case OMX_IndexParamCommonInterleave: return "ParamCommonInterleave"; +// case OMX_IndexConfigCommonColorFormatConversion: +// return "ConfigCommonColorFormatConversion"; + case OMX_IndexConfigCommonScale: return "ConfigCommonScale"; +// case OMX_IndexConfigCommonImageFilter: return "ConfigCommonImageFilter"; +// case OMX_IndexConfigCommonColorEnhancement: return "ConfigCommonColorEnhancement"; +// case OMX_IndexConfigCommonColorKey: return "ConfigCommonColorKey"; +// case OMX_IndexConfigCommonColorBlend: return "ConfigCommonColorBlend"; +// case OMX_IndexConfigCommonFrameStabilisation: return "ConfigCommonFrameStabilisation"; +// case OMX_IndexConfigCommonRotate: return "ConfigCommonRotate"; +// case OMX_IndexConfigCommonMirror: return "ConfigCommonMirror"; +// case OMX_IndexConfigCommonOutputPosition: return "ConfigCommonOutputPosition"; + case OMX_IndexConfigCommonInputCrop: return "ConfigCommonInputCrop"; + case OMX_IndexConfigCommonOutputCrop: return "ConfigCommonOutputCrop"; +// case OMX_IndexConfigCommonDigitalZoom: return "ConfigCommonDigitalZoom"; +// case OMX_IndexConfigCommonOpticalZoom: return "ConfigCommonOpticalZoom"; +// case OMX_IndexConfigCommonWhiteBalance: return "ConfigCommonWhiteBalance"; +// case OMX_IndexConfigCommonExposure: return "ConfigCommonExposure"; +// case OMX_IndexConfigCommonContrast: return "ConfigCommonContrast"; +// case OMX_IndexConfigCommonBrightness: return "ConfigCommonBrightness"; +// case OMX_IndexConfigCommonBacklight: return "ConfigCommonBacklight"; +// case OMX_IndexConfigCommonGamma: return "ConfigCommonGamma"; +// case OMX_IndexConfigCommonSaturation: return "ConfigCommonSaturation"; +// case OMX_IndexConfigCommonLightness: return "ConfigCommonLightness"; +// case OMX_IndexConfigCommonExclusionRect: return "ConfigCommonExclusionRect"; +// case OMX_IndexConfigCommonDithering: return "ConfigCommonDithering"; +// case OMX_IndexConfigCommonPlaneBlend: return "ConfigCommonPlaneBlend"; +// case OMX_IndexConfigCommonExposureValue: return "ConfigCommonExposureValue"; +// case OMX_IndexConfigCommonOutputSize: return "ConfigCommonOutputSize"; +// case OMX_IndexParamCommonExtraQuantData: return "ParamCommonExtraQuantData"; +// case OMX_IndexConfigCommonFocusRegion: return "ConfigCommonFocusRegion"; +// case OMX_IndexConfigCommonFocusStatus: return "ConfigCommonFocusStatus"; +// case OMX_IndexConfigCommonTransitionEffect: return "ConfigCommonTransitionEffect"; +// case OMX_IndexParamOtherPortFormat: return "ParamOtherPortFormat"; +// case OMX_IndexConfigOtherPower: return "ConfigOtherPower"; +// case OMX_IndexConfigOtherStats: return "ConfigOtherStats"; +// case OMX_IndexConfigTimeScale: return "ConfigTimeScale"; +// case OMX_IndexConfigTimeClockState: return "ConfigTimeClockState"; +// case OMX_IndexConfigTimeActiveRefClock: return "ConfigTimeActiveRefClock"; +// case OMX_IndexConfigTimeCurrentMediaTime: return "ConfigTimeCurrentMediaTime"; +// case OMX_IndexConfigTimeCurrentWallTime: return "ConfigTimeCurrentWallTime"; +// case OMX_IndexConfigTimeCurrentAudioReference: +// return "ConfigTimeCurrentAudioReference"; +// case OMX_IndexConfigTimeCurrentVideoReference: +// return "ConfigTimeCurrentVideoReference"; +// case OMX_IndexConfigTimeMediaTimeRequest: return "ConfigTimeMediaTimeRequest"; +// case OMX_IndexConfigTimeClientStartTime: return "ConfigTimeClientStartTime"; +// case OMX_IndexConfigTimePosition: return "ConfigTimePosition"; +// case OMX_IndexConfigTimeSeekMode: return "ConfigTimeSeekMode"; + default: return def; + } +} + +#endif // AS_STRING_FOR_OMX_INDEX_H + +#endif // OMX_Index_h + +#ifdef OMX_IndexExt_h +/* asString definitions if media/openmax/OMX_IndexExt.h was included */ + +#ifndef AS_STRING_FOR_OMX_INDEXEXT_H +#define AS_STRING_FOR_OMX_INDEXEXT_H + +inline static const char *asString(OMX_INDEXEXTTYPE i, const char *def = "??") { + switch (i) { +// case OMX_IndexConfigCallbackRequest: return "ConfigCallbackRequest"; +// case OMX_IndexConfigCommitMode: return "ConfigCommitMode"; +// case OMX_IndexConfigCommit: return "ConfigCommit"; + case OMX_IndexParamAudioAndroidAc3: return "ParamAudioAndroidAc3"; + case OMX_IndexParamAudioAndroidOpus: return "ParamAudioAndroidOpus"; + case OMX_IndexParamAudioAndroidAacPresentation: return "ParamAudioAndroidAacPresentation"; +// case OMX_IndexParamNalStreamFormatSupported: return "ParamNalStreamFormatSupported"; +// case OMX_IndexParamNalStreamFormat: return "ParamNalStreamFormat"; +// case OMX_IndexParamNalStreamFormatSelect: return "ParamNalStreamFormatSelect"; + case OMX_IndexParamVideoVp8: return "ParamVideoVp8"; +// case OMX_IndexConfigVideoVp8ReferenceFrame: return "ConfigVideoVp8ReferenceFrame"; +// case OMX_IndexConfigVideoVp8ReferenceFrameType: return "ConfigVideoVp8ReferenceFrameType"; + case OMX_IndexParamVideoAndroidVp8Encoder: return "ParamVideoAndroidVp8Encoder"; + case OMX_IndexParamVideoHevc: return "ParamVideoHevc"; +// case OMX_IndexParamSliceSegments: return "ParamSliceSegments"; + case OMX_IndexConfigAutoFramerateConversion: return "ConfigAutoFramerateConversion"; + case OMX_IndexConfigPriority: return "ConfigPriority"; + case OMX_IndexConfigOperatingRate: return "ConfigOperatingRate"; + case OMX_IndexParamConsumerUsageBits: return "ParamConsumerUsageBits"; + default: return asString((OMX_INDEXTYPE)i, def); + } +} + +#endif // AS_STRING_FOR_OMX_INDEXEXT_H + +#endif // OMX_IndexExt_h + +#ifdef OMX_IVCommon_h +/* asString definitions if media/openmax/OMX_IVCommon.h was included */ + +#ifndef AS_STRING_FOR_OMX_IVCOMMON_H +#define AS_STRING_FOR_OMX_IVCOMMON_H + +inline static const char *asString(OMX_COLOR_FORMATTYPE i, const char *def = "??") { + switch (i) { + case OMX_COLOR_FormatUnused: + return "COLOR_FormatUnused"; + case OMX_COLOR_FormatMonochrome: + return "COLOR_FormatMonochrome"; + case OMX_COLOR_Format8bitRGB332: + return "COLOR_Format8bitRGB332"; + case OMX_COLOR_Format12bitRGB444: + return "COLOR_Format12bitRGB444"; + case OMX_COLOR_Format16bitARGB4444: + return "COLOR_Format16bitARGB4444"; + case OMX_COLOR_Format16bitARGB1555: + return "COLOR_Format16bitARGB1555"; + case OMX_COLOR_Format16bitRGB565: + return "COLOR_Format16bitRGB565"; + case OMX_COLOR_Format16bitBGR565: + return "COLOR_Format16bitBGR565"; + case OMX_COLOR_Format18bitRGB666: + return "COLOR_Format18bitRGB666"; + case OMX_COLOR_Format18bitARGB1665: + return "COLOR_Format18bitARGB1665"; + case OMX_COLOR_Format19bitARGB1666: + return "COLOR_Format19bitARGB1666"; + case OMX_COLOR_Format24bitRGB888: + return "COLOR_Format24bitRGB888"; + case OMX_COLOR_Format24bitBGR888: + return "COLOR_Format24bitBGR888"; + case OMX_COLOR_Format24bitARGB1887: + return "COLOR_Format24bitARGB1887"; + case OMX_COLOR_Format25bitARGB1888: + return "COLOR_Format25bitARGB1888"; + case OMX_COLOR_Format32bitBGRA8888: + return "COLOR_Format32bitBGRA8888"; + case OMX_COLOR_Format32bitARGB8888: + return "COLOR_Format32bitARGB8888"; + case OMX_COLOR_FormatYUV411Planar: + return "COLOR_FormatYUV411Planar"; + case OMX_COLOR_FormatYUV411PackedPlanar: + return "COLOR_FormatYUV411PackedPlanar"; + case OMX_COLOR_FormatYUV420Planar: + return "COLOR_FormatYUV420Planar"; + case OMX_COLOR_FormatYUV420PackedPlanar: + return "COLOR_FormatYUV420PackedPlanar"; + case OMX_COLOR_FormatYUV420SemiPlanar: + return "COLOR_FormatYUV420SemiPlanar"; + case OMX_COLOR_FormatYUV422Planar: + return "COLOR_FormatYUV422Planar"; + case OMX_COLOR_FormatYUV422PackedPlanar: + return "COLOR_FormatYUV422PackedPlanar"; + case OMX_COLOR_FormatYUV422SemiPlanar: + return "COLOR_FormatYUV422SemiPlanar"; + case OMX_COLOR_FormatYCbYCr: + return "COLOR_FormatYCbYCr"; + case OMX_COLOR_FormatYCrYCb: + return "COLOR_FormatYCrYCb"; + case OMX_COLOR_FormatCbYCrY: + return "COLOR_FormatCbYCrY"; + case OMX_COLOR_FormatCrYCbY: + return "COLOR_FormatCrYCbY"; + case OMX_COLOR_FormatYUV444Interleaved: + return "COLOR_FormatYUV444Interleaved"; + case OMX_COLOR_FormatRawBayer8bit: + return "COLOR_FormatRawBayer8bit"; + case OMX_COLOR_FormatRawBayer10bit: + return "COLOR_FormatRawBayer10bit"; + case OMX_COLOR_FormatRawBayer8bitcompressed: + return "COLOR_FormatRawBayer8bitcompressed"; + case OMX_COLOR_FormatL2: + return "COLOR_FormatL2"; + case OMX_COLOR_FormatL4: + return "COLOR_FormatL4"; + case OMX_COLOR_FormatL8: + return "COLOR_FormatL8"; + case OMX_COLOR_FormatL16: + return "COLOR_FormatL16"; + case OMX_COLOR_FormatL24: + return "COLOR_FormatL24"; + case OMX_COLOR_FormatL32: + return "COLOR_FormatL32"; + case OMX_COLOR_FormatYUV420PackedSemiPlanar: + return "COLOR_FormatYUV420PackedSemiPlanar"; + case OMX_COLOR_FormatYUV422PackedSemiPlanar: + return "COLOR_FormatYUV422PackedSemiPlanar"; + case OMX_COLOR_Format18BitBGR666: + return "COLOR_Format18BitBGR666"; + case OMX_COLOR_Format24BitARGB6666: + return "COLOR_Format24BitARGB6666"; + case OMX_COLOR_Format24BitABGR6666: + return "COLOR_Format24BitABGR6666"; + case OMX_COLOR_FormatAndroidOpaque: + return "COLOR_FormatAndroidOpaque"; + case OMX_COLOR_FormatYUV420Flexible: + return "COLOR_FormatYUV420Flexible"; + case OMX_TI_COLOR_FormatYUV420PackedSemiPlanar: + return "TI_COLOR_FormatYUV420PackedSemiPlanar"; + case OMX_QCOM_COLOR_FormatYVU420SemiPlanar: + return "QCOM_COLOR_FormatYVU420SemiPlanar"; +// case OMX_QCOM_COLOR_FormatYUV420PackedSemiPlanar64x32Tile2m8ka: +// return "QCOM_COLOR_FormatYUV420PackedSemiPlanar64x32Tile2m8ka"; +// case OMX_SEC_COLOR_FormatNV12Tiled: +// return "SEC_COLOR_FormatNV12Tiled"; +// case OMX_QCOM_COLOR_FormatYUV420PackedSemiPlanar32m: +// return "QCOM_COLOR_FormatYUV420PackedSemiPlanar32m"; + default: + return def; + } +} + +#endif // AS_STRING_FOR_OMX_IVCOMMON_H + +#endif // OMX_IVCommon_h + +#ifdef OMX_Types_h +/* asString definitions if media/openmax/OMX_Types.h was included */ + +#ifndef AS_STRING_FOR_OMX_TYPES_H +#define AS_STRING_FOR_OMX_TYPES_H + +inline static const char *asString(OMX_BOOL i, const char *def = "??") { + switch (i) { + case OMX_FALSE: return "FALSE"; + case OMX_TRUE: return "TRUE"; + default: return def; + } +} + +inline static const char *asString(OMX_DIRTYPE i, const char *def = "??") { + switch (i) { + case OMX_DirInput: return "Input"; + case OMX_DirOutput: return "Output"; + default: return def; + } +} + +inline static const char *asString(OMX_ENDIANTYPE i, const char *def = "??") { + switch (i) { + case OMX_EndianBig: return "Big"; +// case OMX_EndianLittle: return "Little"; + default: return def; + } +} + +inline static const char *asString(OMX_NUMERICALDATATYPE i, const char *def = "??") { + switch (i) { + case OMX_NumericalDataSigned: return "Signed"; +// case OMX_NumericalDataUnsigned: return "Unsigned"; + default: return def; + } +} + +#endif // AS_STRING_FOR_OMX_TYPES_H + +#endif // OMX_Types_h + +#ifdef OMX_Video_h +/* asString definitions if media/openmax/OMX_Video.h was included */ + +#ifndef AS_STRING_FOR_OMX_VIDEO_H +#define AS_STRING_FOR_OMX_VIDEO_H + +inline static const char *asString(OMX_VIDEO_CODINGTYPE i, const char *def = "??") { + switch (i) { + case OMX_VIDEO_CodingUnused: return "Unused"; + case OMX_VIDEO_CodingAutoDetect: return "AutoDetect"; // unused + case OMX_VIDEO_CodingMPEG2: return "MPEG2"; + case OMX_VIDEO_CodingH263: return "H263"; + case OMX_VIDEO_CodingMPEG4: return "MPEG4"; + case OMX_VIDEO_CodingWMV: return "WMV"; // unused + case OMX_VIDEO_CodingRV: return "RV"; // unused + case OMX_VIDEO_CodingAVC: return "AVC"; + case OMX_VIDEO_CodingMJPEG: return "MJPEG"; // unused + case OMX_VIDEO_CodingVP8: return "VP8"; + case OMX_VIDEO_CodingVP9: return "VP9"; + case OMX_VIDEO_CodingHEVC: return "HEVC"; + default: return def; + } +} + +inline static const char *asString(OMX_VIDEO_CONTROLRATETYPE i, const char *def = "??") { + switch (i) { +// case OMX_Video_ControlRateDisable: return "Disable"; + case OMX_Video_ControlRateVariable: return "Variable"; + case OMX_Video_ControlRateConstant: return "Constant"; +// case OMX_Video_ControlRateVariableSkipFrames: return "VariableSkipFrames"; +// case OMX_Video_ControlRateConstantSkipFrames: return "ConstantSkipFrames"; + default: return def; + } +} + +inline static const char *asString(OMX_VIDEO_INTRAREFRESHTYPE i, const char *def = "??") { + switch (i) { + case OMX_VIDEO_IntraRefreshCyclic: return "Cyclic"; + case OMX_VIDEO_IntraRefreshAdaptive: return "Adaptive"; + case OMX_VIDEO_IntraRefreshBoth: return "Both"; + default: return def; + } +} + +inline static const char *asString(OMX_VIDEO_H263PROFILETYPE i, const char *def = "??") { + switch (i) { + case OMX_VIDEO_H263ProfileBaseline: return "Baseline"; + case OMX_VIDEO_H263ProfileH320Coding: return "H320Coding"; + case OMX_VIDEO_H263ProfileBackwardCompatible: return "BackwardCompatible"; + case OMX_VIDEO_H263ProfileISWV2: return "ISWV2"; + case OMX_VIDEO_H263ProfileISWV3: return "ISWV3"; + case OMX_VIDEO_H263ProfileHighCompression: return "HighCompression"; + case OMX_VIDEO_H263ProfileInternet: return "Internet"; + case OMX_VIDEO_H263ProfileInterlace: return "Interlace"; + case OMX_VIDEO_H263ProfileHighLatency: return "HighLatency"; + default: return def; + } +} + +inline static const char *asString(OMX_VIDEO_H263LEVELTYPE i, const char *def = "??") { + switch (i) { + case OMX_VIDEO_H263Level10: return "Level10"; + case OMX_VIDEO_H263Level20: return "Level20"; + case OMX_VIDEO_H263Level30: return "Level30"; + case OMX_VIDEO_H263Level40: return "Level40"; + case OMX_VIDEO_H263Level45: return "Level45"; + case OMX_VIDEO_H263Level50: return "Level50"; + case OMX_VIDEO_H263Level60: return "Level60"; + case OMX_VIDEO_H263Level70: return "Level70"; + default: return def; + } +} + +inline static const char *asString(OMX_VIDEO_PICTURETYPE i, const char *def = "??") { + switch (i) { + case OMX_VIDEO_PictureTypeI: return "I"; + case OMX_VIDEO_PictureTypeP: return "P"; + case OMX_VIDEO_PictureTypeB: return "B"; +// case OMX_VIDEO_PictureTypeSI: return "SI"; +// case OMX_VIDEO_PictureTypeSP: return "SP"; +// case OMX_VIDEO_PictureTypeEI: return "EI"; +// case OMX_VIDEO_PictureTypeEP: return "EP"; +// case OMX_VIDEO_PictureTypeS: return "S"; + default: return def; + } +} + +inline static const char *asString(OMX_VIDEO_MPEG4PROFILETYPE i, const char *def = "??") { + switch (i) { + case OMX_VIDEO_MPEG4ProfileSimple: return "Simple"; + case OMX_VIDEO_MPEG4ProfileSimpleScalable: return "SimpleScalable"; + case OMX_VIDEO_MPEG4ProfileCore: return "Core"; + case OMX_VIDEO_MPEG4ProfileMain: return "Main"; + case OMX_VIDEO_MPEG4ProfileNbit: return "Nbit"; + case OMX_VIDEO_MPEG4ProfileScalableTexture: return "ScalableTexture"; + case OMX_VIDEO_MPEG4ProfileSimpleFace: return "SimpleFace"; + case OMX_VIDEO_MPEG4ProfileSimpleFBA: return "SimpleFBA"; + case OMX_VIDEO_MPEG4ProfileBasicAnimated: return "BasicAnimated"; + case OMX_VIDEO_MPEG4ProfileHybrid: return "Hybrid"; + case OMX_VIDEO_MPEG4ProfileAdvancedRealTime: return "AdvancedRealTime"; + case OMX_VIDEO_MPEG4ProfileCoreScalable: return "CoreScalable"; + case OMX_VIDEO_MPEG4ProfileAdvancedCoding: return "AdvancedCoding"; + case OMX_VIDEO_MPEG4ProfileAdvancedCore: return "AdvancedCore"; + case OMX_VIDEO_MPEG4ProfileAdvancedScalable: return "AdvancedScalable"; + case OMX_VIDEO_MPEG4ProfileAdvancedSimple: return "AdvancedSimple"; + default: return def; + } +} + +inline static const char *asString(OMX_VIDEO_MPEG4LEVELTYPE i, const char *def = "??") { + switch (i) { + case OMX_VIDEO_MPEG4Level0: return "Level0"; + case OMX_VIDEO_MPEG4Level0b: return "Level0b"; + case OMX_VIDEO_MPEG4Level1: return "Level1"; + case OMX_VIDEO_MPEG4Level2: return "Level2"; + case OMX_VIDEO_MPEG4Level3: return "Level3"; + case OMX_VIDEO_MPEG4Level4: return "Level4"; + case OMX_VIDEO_MPEG4Level4a: return "Level4a"; + case OMX_VIDEO_MPEG4Level5: return "Level5"; + default: return def; + } +} + +inline static const char *asString(OMX_VIDEO_AVCPROFILETYPE i, const char *def = "??") { + switch (i) { + case OMX_VIDEO_AVCProfileBaseline: return "Baseline"; + case OMX_VIDEO_AVCProfileMain: return "Main"; + case OMX_VIDEO_AVCProfileExtended: return "Extended"; + case OMX_VIDEO_AVCProfileHigh: return "High"; + case OMX_VIDEO_AVCProfileHigh10: return "High10"; + case OMX_VIDEO_AVCProfileHigh422: return "High422"; + case OMX_VIDEO_AVCProfileHigh444: return "High444"; + default: return def; + } +} + +inline static const char *asString(OMX_VIDEO_AVCLEVELTYPE i, const char *def = "??") { + switch (i) { + case OMX_VIDEO_AVCLevel1: return "Level1"; + case OMX_VIDEO_AVCLevel1b: return "Level1b"; + case OMX_VIDEO_AVCLevel11: return "Level11"; + case OMX_VIDEO_AVCLevel12: return "Level12"; + case OMX_VIDEO_AVCLevel13: return "Level13"; + case OMX_VIDEO_AVCLevel2: return "Level2"; + case OMX_VIDEO_AVCLevel21: return "Level21"; + case OMX_VIDEO_AVCLevel22: return "Level22"; + case OMX_VIDEO_AVCLevel3: return "Level3"; + case OMX_VIDEO_AVCLevel31: return "Level31"; + case OMX_VIDEO_AVCLevel32: return "Level32"; + case OMX_VIDEO_AVCLevel4: return "Level4"; + case OMX_VIDEO_AVCLevel41: return "Level41"; + case OMX_VIDEO_AVCLevel42: return "Level42"; + case OMX_VIDEO_AVCLevel5: return "Level5"; + case OMX_VIDEO_AVCLevel51: return "Level51"; + case OMX_VIDEO_AVCLevel52: return "Level52"; + default: return def; + } +} + +inline static const char *asString(OMX_VIDEO_AVCLOOPFILTERTYPE i, const char *def = "??") { + switch (i) { + case OMX_VIDEO_AVCLoopFilterEnable: return "Enable"; +// case OMX_VIDEO_AVCLoopFilterDisable: return "Disable"; +// case OMX_VIDEO_AVCLoopFilterDisableSliceBoundary: return "DisableSliceBoundary"; + default: return def; + } +} + +#endif // AS_STRING_FOR_OMX_VIDEO_H + +#endif // OMX_Video_h + +#ifdef OMX_VideoExt_h +/* asString definitions if media/openmax/OMX_VideoExt.h was included */ + +#ifndef AS_STRING_FOR_OMX_VIDEOEXT_H +#define AS_STRING_FOR_OMX_VIDEOEXT_H + +inline static const char *asString(OMX_VIDEO_VP8PROFILETYPE i, const char *def = "!!") { + switch (i) { + case OMX_VIDEO_VP8ProfileMain: return "Main"; + case OMX_VIDEO_VP8ProfileUnknown: return "Unknown"; // unused + default: return def; + } +} + +inline static const char *asString(OMX_VIDEO_VP8LEVELTYPE i, const char *def = "!!") { + switch (i) { + case OMX_VIDEO_VP8Level_Version0: return "_Version0"; + case OMX_VIDEO_VP8Level_Version1: return "_Version1"; + case OMX_VIDEO_VP8Level_Version2: return "_Version2"; + case OMX_VIDEO_VP8Level_Version3: return "_Version3"; + case OMX_VIDEO_VP8LevelUnknown: return "Unknown"; // unused + default: return def; + } +} + +inline static const char *asString( + OMX_VIDEO_ANDROID_VPXTEMPORALLAYERPATTERNTYPE i, const char *def = "??") { + switch (i) { + case OMX_VIDEO_VPXTemporalLayerPatternNone: return "VPXTemporalLayerPatternNone"; + case OMX_VIDEO_VPXTemporalLayerPatternWebRTC: return "VPXTemporalLayerPatternWebRTC"; + default: return def; + } +} + +inline static const char *asString(OMX_VIDEO_HEVCPROFILETYPE i, const char *def = "!!") { + switch (i) { + case OMX_VIDEO_HEVCProfileUnknown: return "Unknown"; // unused + case OMX_VIDEO_HEVCProfileMain: return "Main"; + case OMX_VIDEO_HEVCProfileMain10: return "Main10"; + default: return def; + } +} + +inline static const char *asString(OMX_VIDEO_HEVCLEVELTYPE i, const char *def = "!!") { + switch (i) { + case OMX_VIDEO_HEVCLevelUnknown: return "LevelUnknown"; // unused + case OMX_VIDEO_HEVCMainTierLevel1: return "MainTierLevel1"; + case OMX_VIDEO_HEVCHighTierLevel1: return "HighTierLevel1"; + case OMX_VIDEO_HEVCMainTierLevel2: return "MainTierLevel2"; + case OMX_VIDEO_HEVCHighTierLevel2: return "HighTierLevel2"; + case OMX_VIDEO_HEVCMainTierLevel21: return "MainTierLevel21"; + case OMX_VIDEO_HEVCHighTierLevel21: return "HighTierLevel21"; + case OMX_VIDEO_HEVCMainTierLevel3: return "MainTierLevel3"; + case OMX_VIDEO_HEVCHighTierLevel3: return "HighTierLevel3"; + case OMX_VIDEO_HEVCMainTierLevel31: return "MainTierLevel31"; + case OMX_VIDEO_HEVCHighTierLevel31: return "HighTierLevel31"; + case OMX_VIDEO_HEVCMainTierLevel4: return "MainTierLevel4"; + case OMX_VIDEO_HEVCHighTierLevel4: return "HighTierLevel4"; + case OMX_VIDEO_HEVCMainTierLevel41: return "MainTierLevel41"; + case OMX_VIDEO_HEVCHighTierLevel41: return "HighTierLevel41"; + case OMX_VIDEO_HEVCMainTierLevel5: return "MainTierLevel5"; + case OMX_VIDEO_HEVCHighTierLevel5: return "HighTierLevel5"; + case OMX_VIDEO_HEVCMainTierLevel51: return "MainTierLevel51"; + case OMX_VIDEO_HEVCHighTierLevel51: return "HighTierLevel51"; + case OMX_VIDEO_HEVCMainTierLevel52: return "MainTierLevel52"; + case OMX_VIDEO_HEVCHighTierLevel52: return "HighTierLevel52"; + case OMX_VIDEO_HEVCMainTierLevel6: return "MainTierLevel6"; + case OMX_VIDEO_HEVCHighTierLevel6: return "HighTierLevel6"; + case OMX_VIDEO_HEVCMainTierLevel61: return "MainTierLevel61"; + case OMX_VIDEO_HEVCHighTierLevel61: return "HighTierLevel61"; + case OMX_VIDEO_HEVCMainTierLevel62: return "MainTierLevel62"; + case OMX_VIDEO_HEVCHighTierLevel62: return "HighTierLevel62"; + default: return def; + } +} + +#endif // AS_STRING_FOR_OMX_VIDEOEXT_H + +#endif // OMX_VideoExt_h diff --git a/phonelibs/android_frameworks_native/include/media/openmax/OMX_Audio.h b/phonelibs/android_frameworks_native/include/media/openmax/OMX_Audio.h new file mode 100644 index 0000000000..a0cbd3bb99 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/media/openmax/OMX_Audio.h @@ -0,0 +1,1342 @@ +/* ------------------------------------------------------------------ + * Copyright (C) 1998-2009 PacketVideo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. + * See the License for the specific language governing permissions + * and limitations under the License. + * ------------------------------------------------------------------- + */ +/* + * Copyright (c) 2008 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** @file OMX_Audio.h - OpenMax IL version 1.1.2 + * The structures needed by Audio components to exchange + * parameters and configuration data with the componenmilts. + */ + +#ifndef OMX_Audio_h +#define OMX_Audio_h + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* Each OMX header must include all required header files to allow the + * header to compile without errors. The includes below are required + * for this header file to compile successfully + */ + +#include + +/** @defgroup midi MIDI + * @ingroup audio + */ + +/** @defgroup effects Audio effects + * @ingroup audio + */ + +/** @defgroup audio OpenMAX IL Audio Domain + * Structures for OpenMAX IL Audio domain + * @{ + */ + +/** Enumeration used to define the possible audio codings. + * If "OMX_AUDIO_CodingUnused" is selected, the coding selection must + * be done in a vendor specific way. Since this is for an audio + * processing element this enum is relevant. However, for another + * type of component other enums would be in this area. + */ +typedef enum OMX_AUDIO_CODINGTYPE { + OMX_AUDIO_CodingUnused = 0, /**< Placeholder value when coding is N/A */ + OMX_AUDIO_CodingAutoDetect, /**< auto detection of audio format */ + OMX_AUDIO_CodingPCM, /**< Any variant of PCM coding */ + OMX_AUDIO_CodingADPCM, /**< Any variant of ADPCM encoded data */ + OMX_AUDIO_CodingAMR, /**< Any variant of AMR encoded data */ + OMX_AUDIO_CodingGSMFR, /**< Any variant of GSM fullrate (i.e. GSM610) */ + OMX_AUDIO_CodingGSMEFR, /**< Any variant of GSM Enhanced Fullrate encoded data*/ + OMX_AUDIO_CodingGSMHR, /**< Any variant of GSM Halfrate encoded data */ + OMX_AUDIO_CodingPDCFR, /**< Any variant of PDC Fullrate encoded data */ + OMX_AUDIO_CodingPDCEFR, /**< Any variant of PDC Enhanced Fullrate encoded data */ + OMX_AUDIO_CodingPDCHR, /**< Any variant of PDC Halfrate encoded data */ + OMX_AUDIO_CodingTDMAFR, /**< Any variant of TDMA Fullrate encoded data (TIA/EIA-136-420) */ + OMX_AUDIO_CodingTDMAEFR, /**< Any variant of TDMA Enhanced Fullrate encoded data (TIA/EIA-136-410) */ + OMX_AUDIO_CodingQCELP8, /**< Any variant of QCELP 8kbps encoded data */ + OMX_AUDIO_CodingQCELP13, /**< Any variant of QCELP 13kbps encoded data */ + OMX_AUDIO_CodingEVRC, /**< Any variant of EVRC encoded data */ + OMX_AUDIO_CodingSMV, /**< Any variant of SMV encoded data */ + OMX_AUDIO_CodingG711, /**< Any variant of G.711 encoded data */ + OMX_AUDIO_CodingG723, /**< Any variant of G.723 dot 1 encoded data */ + OMX_AUDIO_CodingG726, /**< Any variant of G.726 encoded data */ + OMX_AUDIO_CodingG729, /**< Any variant of G.729 encoded data */ + OMX_AUDIO_CodingAAC, /**< Any variant of AAC encoded data */ + OMX_AUDIO_CodingMP3, /**< Any variant of MP3 encoded data */ + OMX_AUDIO_CodingSBC, /**< Any variant of SBC encoded data */ + OMX_AUDIO_CodingVORBIS, /**< Any variant of VORBIS encoded data */ + OMX_AUDIO_CodingWMA, /**< Any variant of WMA encoded data */ + OMX_AUDIO_CodingRA, /**< Any variant of RA encoded data */ + OMX_AUDIO_CodingMIDI, /**< Any variant of MIDI encoded data */ + OMX_AUDIO_CodingFLAC, /**< Any variant of FLAC encoded data */ + OMX_AUDIO_CodingKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_CodingVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_CodingMax = 0x7FFFFFFF +} OMX_AUDIO_CODINGTYPE; + + +/** The PortDefinition structure is used to define all of the parameters + * necessary for the compliant component to setup an input or an output audio + * path. If additional information is needed to define the parameters of the + * port (such as frequency), additional structures must be sent such as the + * OMX_AUDIO_PARAM_PCMMODETYPE structure to supply the extra parameters for the port. + */ +typedef struct OMX_AUDIO_PORTDEFINITIONTYPE { + OMX_STRING cMIMEType; /**< MIME type of data for the port */ + OMX_NATIVE_DEVICETYPE pNativeRender; /** < platform specific reference + for an output device, + otherwise this field is 0 */ + OMX_BOOL bFlagErrorConcealment; /**< Turns on error concealment if it is + supported by the OMX component */ + OMX_AUDIO_CODINGTYPE eEncoding; /**< Type of data expected for this + port (e.g. PCM, AMR, MP3, etc) */ +} OMX_AUDIO_PORTDEFINITIONTYPE; + + +/** Port format parameter. This structure is used to enumerate + * the various data input/output format supported by the port. + */ +typedef struct OMX_AUDIO_PARAM_PORTFORMATTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Indicates which port to set */ + OMX_U32 nIndex; /**< Indicates the enumeration index for the format from 0x0 to N-1 */ + OMX_AUDIO_CODINGTYPE eEncoding; /**< Type of data expected for this port (e.g. PCM, AMR, MP3, etc) */ +} OMX_AUDIO_PARAM_PORTFORMATTYPE; + + +/** PCM mode type */ +typedef enum OMX_AUDIO_PCMMODETYPE { + OMX_AUDIO_PCMModeLinear = 0, /**< Linear PCM encoded data */ + OMX_AUDIO_PCMModeALaw, /**< A law PCM encoded data (G.711) */ + OMX_AUDIO_PCMModeMULaw, /**< Mu law PCM encoded data (G.711) */ + OMX_AUDIO_PCMModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_PCMModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_PCMModeMax = 0x7FFFFFFF +} OMX_AUDIO_PCMMODETYPE; + + +typedef enum OMX_AUDIO_CHANNELTYPE { + OMX_AUDIO_ChannelNone = 0x0, /**< Unused or empty */ + OMX_AUDIO_ChannelLF = 0x1, /**< Left front */ + OMX_AUDIO_ChannelRF = 0x2, /**< Right front */ + OMX_AUDIO_ChannelCF = 0x3, /**< Center front */ + OMX_AUDIO_ChannelLS = 0x4, /**< Left surround */ + OMX_AUDIO_ChannelRS = 0x5, /**< Right surround */ + OMX_AUDIO_ChannelLFE = 0x6, /**< Low frequency effects */ + OMX_AUDIO_ChannelCS = 0x7, /**< Back surround */ + OMX_AUDIO_ChannelLR = 0x8, /**< Left rear. */ + OMX_AUDIO_ChannelRR = 0x9, /**< Right rear. */ + OMX_AUDIO_ChannelKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_ChannelVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_ChannelMax = 0x7FFFFFFF +} OMX_AUDIO_CHANNELTYPE; + +#define OMX_AUDIO_MAXCHANNELS 16 /**< maximum number distinct audio channels that a buffer may contain */ +#define OMX_MIN_PCMPAYLOAD_MSEC 5 /**< Minimum audio buffer payload size for uncompressed (PCM) audio */ + +/** PCM format description */ +typedef struct OMX_AUDIO_PARAM_PCMMODETYPE { + OMX_U32 nSize; /**< Size of this structure, in Bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels (e.g. 2 for stereo) */ + OMX_NUMERICALDATATYPE eNumData; /**< indicates PCM data as signed or unsigned */ + OMX_ENDIANTYPE eEndian; /**< indicates PCM data as little or big endian */ + OMX_BOOL bInterleaved; /**< True for normal interleaved data; false for + non-interleaved data (e.g. block data) */ + OMX_U32 nBitPerSample; /**< Bit per sample */ + OMX_U32 nSamplingRate; /**< Sampling rate of the source data. Use 0 for + variable or unknown sampling rate. */ + OMX_AUDIO_PCMMODETYPE ePCMMode; /**< PCM mode enumeration */ + OMX_AUDIO_CHANNELTYPE eChannelMapping[OMX_AUDIO_MAXCHANNELS]; /**< Slot i contains channel defined by eChannelMap[i] */ + +} OMX_AUDIO_PARAM_PCMMODETYPE; + + +/** Audio channel mode. This is used by both AAC and MP3, although the names are more appropriate + * for the MP3. For example, JointStereo for MP3 is CouplingChannels for AAC. + */ +typedef enum OMX_AUDIO_CHANNELMODETYPE { + OMX_AUDIO_ChannelModeStereo = 0, /**< 2 channels, the bitrate allocation between those + two channels changes accordingly to each channel information */ + OMX_AUDIO_ChannelModeJointStereo, /**< mode that takes advantage of what is common between + 2 channels for higher compression gain */ + OMX_AUDIO_ChannelModeDual, /**< 2 mono-channels, each channel is encoded with half + the bitrate of the overall bitrate */ + OMX_AUDIO_ChannelModeMono, /**< Mono channel mode */ + OMX_AUDIO_ChannelModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_ChannelModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_ChannelModeMax = 0x7FFFFFFF +} OMX_AUDIO_CHANNELMODETYPE; + + +typedef enum OMX_AUDIO_MP3STREAMFORMATTYPE { + OMX_AUDIO_MP3StreamFormatMP1Layer3 = 0, /**< MP3 Audio MPEG 1 Layer 3 Stream format */ + OMX_AUDIO_MP3StreamFormatMP2Layer3, /**< MP3 Audio MPEG 2 Layer 3 Stream format */ + OMX_AUDIO_MP3StreamFormatMP2_5Layer3, /**< MP3 Audio MPEG2.5 Layer 3 Stream format */ + OMX_AUDIO_MP3StreamFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_MP3StreamFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_MP3StreamFormatMax = 0x7FFFFFFF +} OMX_AUDIO_MP3STREAMFORMATTYPE; + +/** MP3 params */ +typedef struct OMX_AUDIO_PARAM_MP3TYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels */ + OMX_U32 nBitRate; /**< Bit rate of the input data. Use 0 for variable + rate or unknown bit rates */ + OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for + variable or unknown sampling rate. */ + OMX_U32 nAudioBandWidth; /**< Audio band width (in Hz) to which an encoder should + limit the audio signal. Use 0 to let encoder decide */ + OMX_AUDIO_CHANNELMODETYPE eChannelMode; /**< Channel mode enumeration */ + OMX_AUDIO_MP3STREAMFORMATTYPE eFormat; /**< MP3 stream format */ +} OMX_AUDIO_PARAM_MP3TYPE; + + +typedef enum OMX_AUDIO_AACSTREAMFORMATTYPE { + OMX_AUDIO_AACStreamFormatMP2ADTS = 0, /**< AAC Audio Data Transport Stream 2 format */ + OMX_AUDIO_AACStreamFormatMP4ADTS, /**< AAC Audio Data Transport Stream 4 format */ + OMX_AUDIO_AACStreamFormatMP4LOAS, /**< AAC Low Overhead Audio Stream format */ + OMX_AUDIO_AACStreamFormatMP4LATM, /**< AAC Low overhead Audio Transport Multiplex */ + OMX_AUDIO_AACStreamFormatADIF, /**< AAC Audio Data Interchange Format */ + OMX_AUDIO_AACStreamFormatMP4FF, /**< AAC inside MPEG-4/ISO File Format */ + OMX_AUDIO_AACStreamFormatRAW, /**< AAC Raw Format */ + OMX_AUDIO_AACStreamFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_AACStreamFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_AACStreamFormatMax = 0x7FFFFFFF +} OMX_AUDIO_AACSTREAMFORMATTYPE; + + +/** AAC mode type. Note that the term profile is used with the MPEG-2 + * standard and the term object type and profile is used with MPEG-4 */ +typedef enum OMX_AUDIO_AACPROFILETYPE{ + OMX_AUDIO_AACObjectNull = 0, /**< Null, not used */ + OMX_AUDIO_AACObjectMain = 1, /**< AAC Main object */ + OMX_AUDIO_AACObjectLC, /**< AAC Low Complexity object (AAC profile) */ + OMX_AUDIO_AACObjectSSR, /**< AAC Scalable Sample Rate object */ + OMX_AUDIO_AACObjectLTP, /**< AAC Long Term Prediction object */ + OMX_AUDIO_AACObjectHE, /**< AAC High Efficiency (object type SBR, HE-AAC profile) */ + OMX_AUDIO_AACObjectScalable, /**< AAC Scalable object */ + OMX_AUDIO_AACObjectERLC = 17, /**< ER AAC Low Complexity object (Error Resilient AAC-LC) */ + OMX_AUDIO_AACObjectLD = 23, /**< AAC Low Delay object (Error Resilient) */ + OMX_AUDIO_AACObjectHE_PS = 29, /**< AAC High Efficiency with Parametric Stereo coding (HE-AAC v2, object type PS) */ + OMX_AUDIO_AACObjectELD = 39, /** AAC Enhanced Low Delay. NOTE: Pending Khronos standardization **/ + OMX_AUDIO_AACObjectKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_AACObjectVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_AACObjectMax = 0x7FFFFFFF +} OMX_AUDIO_AACPROFILETYPE; + + +/** AAC tool usage (for nAACtools in OMX_AUDIO_PARAM_AACPROFILETYPE). + * Required for encoder configuration and optional as decoder info output. + * For MP3, OMX_AUDIO_CHANNELMODETYPE is sufficient. */ +#define OMX_AUDIO_AACToolNone 0x00000000 /**< no AAC tools allowed (encoder config) or active (decoder info output) */ +#define OMX_AUDIO_AACToolMS 0x00000001 /**< MS: Mid/side joint coding tool allowed or active */ +#define OMX_AUDIO_AACToolIS 0x00000002 /**< IS: Intensity stereo tool allowed or active */ +#define OMX_AUDIO_AACToolTNS 0x00000004 /**< TNS: Temporal Noise Shaping tool allowed or active */ +#define OMX_AUDIO_AACToolPNS 0x00000008 /**< PNS: MPEG-4 Perceptual Noise substitution tool allowed or active */ +#define OMX_AUDIO_AACToolLTP 0x00000010 /**< LTP: MPEG-4 Long Term Prediction tool allowed or active */ +#define OMX_AUDIO_AACToolVendor 0x00010000 /**< NOT A KHRONOS VALUE, offset for vendor-specific additions */ +#define OMX_AUDIO_AACToolAll 0x7FFFFFFF /**< all AAC tools allowed or active (*/ + +/** MPEG-4 AAC error resilience (ER) tool usage (for nAACERtools in OMX_AUDIO_PARAM_AACPROFILETYPE). + * Required for ER encoder configuration and optional as decoder info output */ +#define OMX_AUDIO_AACERNone 0x00000000 /**< no AAC ER tools allowed/used */ +#define OMX_AUDIO_AACERVCB11 0x00000001 /**< VCB11: Virtual Code Books for AAC section data */ +#define OMX_AUDIO_AACERRVLC 0x00000002 /**< RVLC: Reversible Variable Length Coding */ +#define OMX_AUDIO_AACERHCR 0x00000004 /**< HCR: Huffman Codeword Reordering */ +#define OMX_AUDIO_AACERAll 0x7FFFFFFF /**< all AAC ER tools allowed/used */ + + +/** AAC params */ +typedef struct OMX_AUDIO_PARAM_AACPROFILETYPE { + OMX_U32 nSize; /**< Size of this structure, in Bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels */ + OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for + variable or unknown sampling rate. */ + OMX_U32 nBitRate; /**< Bit rate of the input data. Use 0 for variable + rate or unknown bit rates */ + OMX_U32 nAudioBandWidth; /**< Audio band width (in Hz) to which an encoder should + limit the audio signal. Use 0 to let encoder decide */ + OMX_U32 nFrameLength; /**< Frame length (in audio samples per channel) of the codec. + Can be 1024 or 960 (AAC-LC), 2048 (HE-AAC), 480 or 512 (AAC-LD). + Use 0 to let encoder decide */ + OMX_U32 nAACtools; /**< AAC tool usage */ + OMX_U32 nAACERtools; /**< MPEG-4 AAC error resilience tool usage */ + OMX_AUDIO_AACPROFILETYPE eAACProfile; /**< AAC profile enumeration */ + OMX_AUDIO_AACSTREAMFORMATTYPE eAACStreamFormat; /**< AAC stream format enumeration */ + OMX_AUDIO_CHANNELMODETYPE eChannelMode; /**< Channel mode enumeration */ +} OMX_AUDIO_PARAM_AACPROFILETYPE; + + +/** VORBIS params */ +typedef struct OMX_AUDIO_PARAM_VORBISTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels */ + OMX_U32 nBitRate; /**< Bit rate of the encoded data data. Use 0 for variable + rate or unknown bit rates. Encoding is set to the + bitrate closest to specified value (in bps) */ + OMX_U32 nMinBitRate; /**< Sets minimum bitrate (in bps). */ + OMX_U32 nMaxBitRate; /**< Sets maximum bitrate (in bps). */ + + OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for + variable or unknown sampling rate. */ + OMX_U32 nAudioBandWidth; /**< Audio band width (in Hz) to which an encoder should + limit the audio signal. Use 0 to let encoder decide */ + OMX_S32 nQuality; /**< Sets encoding quality to n, between -1 (low) and 10 (high). + In the default mode of operation, teh quality level is 3. + Normal quality range is 0 - 10. */ + OMX_BOOL bManaged; /**< Set bitrate management mode. This turns off the + normal VBR encoding, but allows hard or soft bitrate + constraints to be enforced by the encoder. This mode can + be slower, and may also be lower quality. It is + primarily useful for streaming. */ + OMX_BOOL bDownmix; /**< Downmix input from stereo to mono (has no effect on + non-stereo streams). Useful for lower-bitrate encoding. */ +} OMX_AUDIO_PARAM_VORBISTYPE; + + +/** FLAC params */ +typedef struct OMX_AUDIO_PARAM_FLACTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels */ + OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for + unknown sampling rate. */ + OMX_U32 nCompressionLevel;/**< FLAC compression level, from 0 (fastest compression) + to 8 (highest compression */ +} OMX_AUDIO_PARAM_FLACTYPE; + + +/** WMA Version */ +typedef enum OMX_AUDIO_WMAFORMATTYPE { + OMX_AUDIO_WMAFormatUnused = 0, /**< format unused or unknown */ + OMX_AUDIO_WMAFormat7, /**< Windows Media Audio format 7 */ + OMX_AUDIO_WMAFormat8, /**< Windows Media Audio format 8 */ + OMX_AUDIO_WMAFormat9, /**< Windows Media Audio format 9 */ + OMX_AUDIO_WMAFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_WMAFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_WMAFormatMax = 0x7FFFFFFF +} OMX_AUDIO_WMAFORMATTYPE; + + +/** WMA Profile */ +typedef enum OMX_AUDIO_WMAPROFILETYPE { + OMX_AUDIO_WMAProfileUnused = 0, /**< profile unused or unknown */ + OMX_AUDIO_WMAProfileL1, /**< Windows Media audio version 9 profile L1 */ + OMX_AUDIO_WMAProfileL2, /**< Windows Media audio version 9 profile L2 */ + OMX_AUDIO_WMAProfileL3, /**< Windows Media audio version 9 profile L3 */ + OMX_AUDIO_WMAProfileKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_WMAProfileVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_WMAProfileMax = 0x7FFFFFFF +} OMX_AUDIO_WMAPROFILETYPE; + + +/** WMA params */ +typedef struct OMX_AUDIO_PARAM_WMATYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U16 nChannels; /**< Number of channels */ + OMX_U32 nBitRate; /**< Bit rate of the input data. Use 0 for variable + rate or unknown bit rates */ + OMX_AUDIO_WMAFORMATTYPE eFormat; /**< Version of WMA stream / data */ + OMX_AUDIO_WMAPROFILETYPE eProfile; /**< Profile of WMA stream / data */ + OMX_U32 nSamplingRate; /**< Sampling rate of the source data */ + OMX_U16 nBlockAlign; /**< is the block alignment, or block size, in bytes of the audio codec */ + OMX_U16 nEncodeOptions; /**< WMA Type-specific data */ + OMX_U32 nSuperBlockAlign; /**< WMA Type-specific data */ +} OMX_AUDIO_PARAM_WMATYPE; + +/** + * RealAudio format + */ +typedef enum OMX_AUDIO_RAFORMATTYPE { + OMX_AUDIO_RAFormatUnused = 0, /**< Format unused or unknown */ + OMX_AUDIO_RA8, /**< RealAudio 8 codec */ + OMX_AUDIO_RA9, /**< RealAudio 9 codec */ + OMX_AUDIO_RA10_AAC, /**< MPEG-4 AAC codec for bitrates of more than 128kbps */ + OMX_AUDIO_RA10_CODEC, /**< RealAudio codec for bitrates less than 128 kbps */ + OMX_AUDIO_RA10_LOSSLESS, /**< RealAudio Lossless */ + OMX_AUDIO_RA10_MULTICHANNEL, /**< RealAudio Multichannel */ + OMX_AUDIO_RA10_VOICE, /**< RealAudio Voice for bitrates below 15 kbps */ + OMX_AUDIO_RAFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_RAFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_RAFormatMax = 0x7FFFFFFF +} OMX_AUDIO_RAFORMATTYPE; + +/** RA (Real Audio) params */ +typedef struct OMX_AUDIO_PARAM_RATYPE { + OMX_U32 nSize; /**< Size of this structure, in Bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels */ + OMX_U32 nSamplingRate; /**< is the sampling rate of the source data */ + OMX_U32 nBitsPerFrame; /**< is the value for bits per frame */ + OMX_U32 nSamplePerFrame; /**< is the value for samples per frame */ + OMX_U32 nCouplingQuantBits; /**< is the number of coupling quantization bits in the stream */ + OMX_U32 nCouplingStartRegion; /**< is the coupling start region in the stream */ + OMX_U32 nNumRegions; /**< is the number of regions value */ + OMX_AUDIO_RAFORMATTYPE eFormat; /**< is the RealAudio audio format */ +} OMX_AUDIO_PARAM_RATYPE; + + +/** SBC Allocation Method Type */ +typedef enum OMX_AUDIO_SBCALLOCMETHODTYPE { + OMX_AUDIO_SBCAllocMethodLoudness, /**< Loudness allocation method */ + OMX_AUDIO_SBCAllocMethodSNR, /**< SNR allocation method */ + OMX_AUDIO_SBCAllocMethodKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_SBCAllocMethodVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_SBCAllocMethodMax = 0x7FFFFFFF +} OMX_AUDIO_SBCALLOCMETHODTYPE; + + +/** SBC params */ +typedef struct OMX_AUDIO_PARAM_SBCTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels */ + OMX_U32 nBitRate; /**< Bit rate of the input data. Use 0 for variable + rate or unknown bit rates */ + OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for + variable or unknown sampling rate. */ + OMX_U32 nBlocks; /**< Number of blocks */ + OMX_U32 nSubbands; /**< Number of subbands */ + OMX_U32 nBitPool; /**< Bitpool value */ + OMX_BOOL bEnableBitrate; /**< Use bitrate value instead of bitpool */ + OMX_AUDIO_CHANNELMODETYPE eChannelMode; /**< Channel mode enumeration */ + OMX_AUDIO_SBCALLOCMETHODTYPE eSBCAllocType; /**< SBC Allocation method type */ +} OMX_AUDIO_PARAM_SBCTYPE; + + +/** ADPCM stream format parameters */ +typedef struct OMX_AUDIO_PARAM_ADPCMTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_U32 nBitsPerSample; /**< Number of bits in each sample */ + OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for + variable or unknown sampling rate. */ +} OMX_AUDIO_PARAM_ADPCMTYPE; + + +/** G723 rate */ +typedef enum OMX_AUDIO_G723RATE { + OMX_AUDIO_G723ModeUnused = 0, /**< AMRNB Mode unused / unknown */ + OMX_AUDIO_G723ModeLow, /**< 5300 bps */ + OMX_AUDIO_G723ModeHigh, /**< 6300 bps */ + OMX_AUDIO_G723ModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_G723ModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_G723ModeMax = 0x7FFFFFFF +} OMX_AUDIO_G723RATE; + + +/** G723 - Sample rate must be 8 KHz */ +typedef struct OMX_AUDIO_PARAM_G723TYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_AUDIO_G723RATE eBitRate; /**< todo: Should this be moved to a config? */ + OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ + OMX_BOOL bPostFilter; /**< Enable Post Filter */ +} OMX_AUDIO_PARAM_G723TYPE; + + +/** ITU G726 (ADPCM) rate */ +typedef enum OMX_AUDIO_G726MODE { + OMX_AUDIO_G726ModeUnused = 0, /**< G726 Mode unused / unknown */ + OMX_AUDIO_G726Mode16, /**< 16 kbps */ + OMX_AUDIO_G726Mode24, /**< 24 kbps */ + OMX_AUDIO_G726Mode32, /**< 32 kbps, most common rate, also G721 */ + OMX_AUDIO_G726Mode40, /**< 40 kbps */ + OMX_AUDIO_G726ModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_G726ModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_G726ModeMax = 0x7FFFFFFF +} OMX_AUDIO_G726MODE; + + +/** G.726 stream format parameters - must be at 8KHz */ +typedef struct OMX_AUDIO_PARAM_G726TYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_AUDIO_G726MODE eG726Mode; +} OMX_AUDIO_PARAM_G726TYPE; + + +/** G729 coder type */ +typedef enum OMX_AUDIO_G729TYPE { + OMX_AUDIO_G729 = 0, /**< ITU G.729 encoded data */ + OMX_AUDIO_G729A, /**< ITU G.729 annex A encoded data */ + OMX_AUDIO_G729B, /**< ITU G.729 with annex B encoded data */ + OMX_AUDIO_G729AB, /**< ITU G.729 annexes A and B encoded data */ + OMX_AUDIO_G729KhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_G729VendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_G729Max = 0x7FFFFFFF +} OMX_AUDIO_G729TYPE; + + +/** G729 stream format parameters - fixed 6KHz sample rate */ +typedef struct OMX_AUDIO_PARAM_G729TYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_AUDIO_G729TYPE eBitType; +} OMX_AUDIO_PARAM_G729TYPE; + + +/** AMR Frame format */ +typedef enum OMX_AUDIO_AMRFRAMEFORMATTYPE { + OMX_AUDIO_AMRFrameFormatConformance = 0, /**< Frame Format is AMR Conformance + (Standard) Format */ + OMX_AUDIO_AMRFrameFormatIF1, /**< Frame Format is AMR Interface + Format 1 */ + OMX_AUDIO_AMRFrameFormatIF2, /**< Frame Format is AMR Interface + Format 2*/ + OMX_AUDIO_AMRFrameFormatFSF, /**< Frame Format is AMR File Storage + Format */ + OMX_AUDIO_AMRFrameFormatRTPPayload, /**< Frame Format is AMR Real-Time + Transport Protocol Payload Format */ + OMX_AUDIO_AMRFrameFormatITU, /**< Frame Format is ITU Format (added at Motorola request) */ + OMX_AUDIO_AMRFrameFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_AMRFrameFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_AMRFrameFormatMax = 0x7FFFFFFF +} OMX_AUDIO_AMRFRAMEFORMATTYPE; + + +/** AMR band mode */ +typedef enum OMX_AUDIO_AMRBANDMODETYPE { + OMX_AUDIO_AMRBandModeUnused = 0, /**< AMRNB Mode unused / unknown */ + OMX_AUDIO_AMRBandModeNB0, /**< AMRNB Mode 0 = 4750 bps */ + OMX_AUDIO_AMRBandModeNB1, /**< AMRNB Mode 1 = 5150 bps */ + OMX_AUDIO_AMRBandModeNB2, /**< AMRNB Mode 2 = 5900 bps */ + OMX_AUDIO_AMRBandModeNB3, /**< AMRNB Mode 3 = 6700 bps */ + OMX_AUDIO_AMRBandModeNB4, /**< AMRNB Mode 4 = 7400 bps */ + OMX_AUDIO_AMRBandModeNB5, /**< AMRNB Mode 5 = 7950 bps */ + OMX_AUDIO_AMRBandModeNB6, /**< AMRNB Mode 6 = 10200 bps */ + OMX_AUDIO_AMRBandModeNB7, /**< AMRNB Mode 7 = 12200 bps */ + OMX_AUDIO_AMRBandModeWB0, /**< AMRWB Mode 0 = 6600 bps */ + OMX_AUDIO_AMRBandModeWB1, /**< AMRWB Mode 1 = 8850 bps */ + OMX_AUDIO_AMRBandModeWB2, /**< AMRWB Mode 2 = 12650 bps */ + OMX_AUDIO_AMRBandModeWB3, /**< AMRWB Mode 3 = 14250 bps */ + OMX_AUDIO_AMRBandModeWB4, /**< AMRWB Mode 4 = 15850 bps */ + OMX_AUDIO_AMRBandModeWB5, /**< AMRWB Mode 5 = 18250 bps */ + OMX_AUDIO_AMRBandModeWB6, /**< AMRWB Mode 6 = 19850 bps */ + OMX_AUDIO_AMRBandModeWB7, /**< AMRWB Mode 7 = 23050 bps */ + OMX_AUDIO_AMRBandModeWB8, /**< AMRWB Mode 8 = 23850 bps */ + OMX_AUDIO_AMRBandModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_AMRBandModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_AMRBandModeMax = 0x7FFFFFFF +} OMX_AUDIO_AMRBANDMODETYPE; + + +/** AMR Discontinuous Transmission mode */ +typedef enum OMX_AUDIO_AMRDTXMODETYPE { + OMX_AUDIO_AMRDTXModeOff = 0, /**< AMR Discontinuous Transmission Mode is disabled */ + OMX_AUDIO_AMRDTXModeOnVAD1, /**< AMR Discontinuous Transmission Mode using + Voice Activity Detector 1 (VAD1) is enabled */ + OMX_AUDIO_AMRDTXModeOnVAD2, /**< AMR Discontinuous Transmission Mode using + Voice Activity Detector 2 (VAD2) is enabled */ + OMX_AUDIO_AMRDTXModeOnAuto, /**< The codec will automatically select between + Off, VAD1 or VAD2 modes */ + + OMX_AUDIO_AMRDTXasEFR, /**< DTX as EFR instead of AMR standard (3GPP 26.101, frame type =8,9,10) */ + + OMX_AUDIO_AMRDTXModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_AMRDTXModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_AMRDTXModeMax = 0x7FFFFFFF +} OMX_AUDIO_AMRDTXMODETYPE; + + +/** AMR params */ +typedef struct OMX_AUDIO_PARAM_AMRTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels */ + OMX_U32 nBitRate; /**< Bit rate read only field */ + OMX_AUDIO_AMRBANDMODETYPE eAMRBandMode; /**< AMR Band Mode enumeration */ + OMX_AUDIO_AMRDTXMODETYPE eAMRDTXMode; /**< AMR DTX Mode enumeration */ + OMX_AUDIO_AMRFRAMEFORMATTYPE eAMRFrameFormat; /**< AMR frame format enumeration */ +} OMX_AUDIO_PARAM_AMRTYPE; + + +/** GSM_FR (ETSI 06.10, 3GPP 46.010) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_GSMFRTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ +} OMX_AUDIO_PARAM_GSMFRTYPE; + + +/** GSM-HR (ETSI 06.20, 3GPP 46.020) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_GSMHRTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ +} OMX_AUDIO_PARAM_GSMHRTYPE; + + +/** GSM-EFR (ETSI 06.60, 3GPP 46.060) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_GSMEFRTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ +} OMX_AUDIO_PARAM_GSMEFRTYPE; + + +/** TDMA FR (TIA/EIA-136-420, VSELP 7.95kbps coder) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_TDMAFRTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ +} OMX_AUDIO_PARAM_TDMAFRTYPE; + + +/** TDMA EFR (TIA/EIA-136-410, ACELP 7.4kbps coder) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_TDMAEFRTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ +} OMX_AUDIO_PARAM_TDMAEFRTYPE; + + +/** PDC FR ( RCR-27, VSELP 6.7kbps coder) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_PDCFRTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ +} OMX_AUDIO_PARAM_PDCFRTYPE; + + +/** PDC EFR ( RCR-27, ACELP 6.7kbps coder) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_PDCEFRTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ +} OMX_AUDIO_PARAM_PDCEFRTYPE; + +/** PDC HR ( RCR-27, PSI-CELP 3.45kbps coder) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_PDCHRTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ +} OMX_AUDIO_PARAM_PDCHRTYPE; + + +/** CDMA Rate types */ +typedef enum OMX_AUDIO_CDMARATETYPE { + OMX_AUDIO_CDMARateBlank = 0, /**< CDMA encoded frame is blank */ + OMX_AUDIO_CDMARateFull, /**< CDMA encoded frame in full rate */ + OMX_AUDIO_CDMARateHalf, /**< CDMA encoded frame in half rate */ + OMX_AUDIO_CDMARateQuarter, /**< CDMA encoded frame in quarter rate */ + OMX_AUDIO_CDMARateEighth, /**< CDMA encoded frame in eighth rate (DTX)*/ + OMX_AUDIO_CDMARateErasure, /**< CDMA erasure frame */ + OMX_AUDIO_CDMARateKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_CDMARateVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_CDMARateMax = 0x7FFFFFFF +} OMX_AUDIO_CDMARATETYPE; + + +/** QCELP8 (TIA/EIA-96, up to 8kbps coder) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_QCELP8TYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_U32 nBitRate; /**< Bit rate of the input data. Use 0 for variable + rate or unknown bit rates */ + OMX_AUDIO_CDMARATETYPE eCDMARate; /**< Frame rate */ + OMX_U32 nMinBitRate; /**< minmal rate for the encoder = 1,2,3,4, default = 1 */ + OMX_U32 nMaxBitRate; /**< maximal rate for the encoder = 1,2,3,4, default = 4 */ +} OMX_AUDIO_PARAM_QCELP8TYPE; + + +/** QCELP13 ( CDMA, EIA/TIA-733, 13.3kbps coder) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_QCELP13TYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_AUDIO_CDMARATETYPE eCDMARate; /**< Frame rate */ + OMX_U32 nMinBitRate; /**< minmal rate for the encoder = 1,2,3,4, default = 1 */ + OMX_U32 nMaxBitRate; /**< maximal rate for the encoder = 1,2,3,4, default = 4 */ +} OMX_AUDIO_PARAM_QCELP13TYPE; + + +/** EVRC ( CDMA, EIA/TIA-127, RCELP up to 8.55kbps coder) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_EVRCTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_AUDIO_CDMARATETYPE eCDMARate; /**< actual Frame rate */ + OMX_BOOL bRATE_REDUCon; /**< RATE_REDUCtion is requested for this frame */ + OMX_U32 nMinBitRate; /**< minmal rate for the encoder = 1,2,3,4, default = 1 */ + OMX_U32 nMaxBitRate; /**< maximal rate for the encoder = 1,2,3,4, default = 4 */ + OMX_BOOL bHiPassFilter; /**< Enable encoder's High Pass Filter */ + OMX_BOOL bNoiseSuppressor; /**< Enable encoder's noise suppressor pre-processing */ + OMX_BOOL bPostFilter; /**< Enable decoder's post Filter */ +} OMX_AUDIO_PARAM_EVRCTYPE; + + +/** SMV ( up to 8.55kbps coder) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_SMVTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_AUDIO_CDMARATETYPE eCDMARate; /**< Frame rate */ + OMX_BOOL bRATE_REDUCon; /**< RATE_REDUCtion is requested for this frame */ + OMX_U32 nMinBitRate; /**< minmal rate for the encoder = 1,2,3,4, default = 1 ??*/ + OMX_U32 nMaxBitRate; /**< maximal rate for the encoder = 1,2,3,4, default = 4 ??*/ + OMX_BOOL bHiPassFilter; /**< Enable encoder's High Pass Filter ??*/ + OMX_BOOL bNoiseSuppressor; /**< Enable encoder's noise suppressor pre-processing */ + OMX_BOOL bPostFilter; /**< Enable decoder's post Filter ??*/ +} OMX_AUDIO_PARAM_SMVTYPE; + + +/** MIDI Format + * @ingroup midi + */ +typedef enum OMX_AUDIO_MIDIFORMATTYPE +{ + OMX_AUDIO_MIDIFormatUnknown = 0, /**< MIDI Format unknown or don't care */ + OMX_AUDIO_MIDIFormatSMF0, /**< Standard MIDI File Type 0 */ + OMX_AUDIO_MIDIFormatSMF1, /**< Standard MIDI File Type 1 */ + OMX_AUDIO_MIDIFormatSMF2, /**< Standard MIDI File Type 2 */ + OMX_AUDIO_MIDIFormatSPMIDI, /**< SP-MIDI */ + OMX_AUDIO_MIDIFormatXMF0, /**< eXtensible Music Format type 0 */ + OMX_AUDIO_MIDIFormatXMF1, /**< eXtensible Music Format type 1 */ + OMX_AUDIO_MIDIFormatMobileXMF, /**< Mobile XMF (eXtensible Music Format type 2) */ + OMX_AUDIO_MIDIFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_MIDIFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_MIDIFormatMax = 0x7FFFFFFF +} OMX_AUDIO_MIDIFORMATTYPE; + + +/** MIDI params + * @ingroup midi + */ +typedef struct OMX_AUDIO_PARAM_MIDITYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nFileSize; /**< size of the MIDI file in bytes, where the entire + MIDI file passed in, otherwise if 0x0, the MIDI data + is merged and streamed (instead of passed as an + entire MIDI file) */ + OMX_BU32 sMaxPolyphony; /**< Specifies the maximum simultaneous polyphonic + voices. A value of zero indicates that the default + polyphony of the device is used */ + OMX_BOOL bLoadDefaultSound; /**< Whether to load default sound + bank at initialization */ + OMX_AUDIO_MIDIFORMATTYPE eMidiFormat; /**< Version of the MIDI file */ +} OMX_AUDIO_PARAM_MIDITYPE; + + +/** Type of the MIDI sound bank + * @ingroup midi + */ +typedef enum OMX_AUDIO_MIDISOUNDBANKTYPE { + OMX_AUDIO_MIDISoundBankUnused = 0, /**< unused/unknown soundbank type */ + OMX_AUDIO_MIDISoundBankDLS1, /**< DLS version 1 */ + OMX_AUDIO_MIDISoundBankDLS2, /**< DLS version 2 */ + OMX_AUDIO_MIDISoundBankMobileDLSBase, /**< Mobile DLS, using the base functionality */ + OMX_AUDIO_MIDISoundBankMobileDLSPlusOptions, /**< Mobile DLS, using the specification-defined optional feature set */ + OMX_AUDIO_MIDISoundBankKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_MIDISoundBankVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_MIDISoundBankMax = 0x7FFFFFFF +} OMX_AUDIO_MIDISOUNDBANKTYPE; + + +/** Bank Layout describes how bank MSB & LSB are used in the DLS instrument definitions sound bank + * @ingroup midi + */ +typedef enum OMX_AUDIO_MIDISOUNDBANKLAYOUTTYPE { + OMX_AUDIO_MIDISoundBankLayoutUnused = 0, /**< unused/unknown soundbank type */ + OMX_AUDIO_MIDISoundBankLayoutGM, /**< GS layout (based on bank MSB 0x00) */ + OMX_AUDIO_MIDISoundBankLayoutGM2, /**< General MIDI 2 layout (using MSB 0x78/0x79, LSB 0x00) */ + OMX_AUDIO_MIDISoundBankLayoutUser, /**< Does not conform to any bank numbering standards */ + OMX_AUDIO_MIDISoundBankLayoutKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_MIDISoundBankLayoutVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_MIDISoundBankLayoutMax = 0x7FFFFFFF +} OMX_AUDIO_MIDISOUNDBANKLAYOUTTYPE; + + +/** MIDI params to load/unload user soundbank + * @ingroup midi + */ +typedef struct OMX_AUDIO_PARAM_MIDILOADUSERSOUNDTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nDLSIndex; /**< DLS file index to be loaded */ + OMX_U32 nDLSSize; /**< Size in bytes */ + OMX_PTR pDLSData; /**< Pointer to DLS file data */ + OMX_AUDIO_MIDISOUNDBANKTYPE eMidiSoundBank; /**< Midi sound bank type enumeration */ + OMX_AUDIO_MIDISOUNDBANKLAYOUTTYPE eMidiSoundBankLayout; /**< Midi sound bank layout enumeration */ +} OMX_AUDIO_PARAM_MIDILOADUSERSOUNDTYPE; + + +/** Structure for Live MIDI events and MIP messages. + * (MIP = Maximum Instantaneous Polyphony; part of the SP-MIDI standard.) + * @ingroup midi + */ +typedef struct OMX_AUDIO_CONFIG_MIDIIMMEDIATEEVENTTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Port that this structure applies to */ + OMX_U32 nMidiEventSize; /**< Size of immediate MIDI events or MIP message in bytes */ + OMX_U8 nMidiEvents[1]; /**< MIDI event array to be rendered immediately, or an + array for the MIP message buffer, where the size is + indicated by nMidiEventSize */ +} OMX_AUDIO_CONFIG_MIDIIMMEDIATEEVENTTYPE; + + +/** MIDI sound bank/ program pair in a given channel + * @ingroup midi + */ +typedef struct OMX_AUDIO_CONFIG_MIDISOUNDBANKPROGRAMTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Port that this structure applies to */ + OMX_U32 nChannel; /**< Valid channel values range from 1 to 16 */ + OMX_U16 nIDProgram; /**< Valid program ID range is 1 to 128 */ + OMX_U16 nIDSoundBank; /**< Sound bank ID */ + OMX_U32 nUserSoundBankIndex;/**< User soundbank index, easier to access soundbanks + by index if multiple banks are present */ +} OMX_AUDIO_CONFIG_MIDISOUNDBANKPROGRAMTYPE; + + +/** MIDI control + * @ingroup midi + */ +typedef struct OMX_AUDIO_CONFIG_MIDICONTROLTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BS32 sPitchTransposition; /**< Pitch transposition in semitones, stored as Q22.10 + format based on JAVA MMAPI (JSR-135) requirement */ + OMX_BU32 sPlayBackRate; /**< Relative playback rate, stored as Q14.17 fixed-point + number based on JSR-135 requirement */ + OMX_BU32 sTempo ; /**< Tempo in beats per minute (BPM), stored as Q22.10 + fixed-point number based on JSR-135 requirement */ + OMX_U32 nMaxPolyphony; /**< Specifies the maximum simultaneous polyphonic + voices. A value of zero indicates that the default + polyphony of the device is used */ + OMX_U32 nNumRepeat; /**< Number of times to repeat playback */ + OMX_U32 nStopTime; /**< Time in milliseconds to indicate when playback + will stop automatically. Set to zero if not used */ + OMX_U16 nChannelMuteMask; /**< 16 bit mask for channel mute status */ + OMX_U16 nChannelSoloMask; /**< 16 bit mask for channel solo status */ + OMX_U32 nTrack0031MuteMask; /**< 32 bit mask for track mute status. Note: This is for tracks 0-31 */ + OMX_U32 nTrack3263MuteMask; /**< 32 bit mask for track mute status. Note: This is for tracks 32-63 */ + OMX_U32 nTrack0031SoloMask; /**< 32 bit mask for track solo status. Note: This is for tracks 0-31 */ + OMX_U32 nTrack3263SoloMask; /**< 32 bit mask for track solo status. Note: This is for tracks 32-63 */ + +} OMX_AUDIO_CONFIG_MIDICONTROLTYPE; + + +/** MIDI Playback States + * @ingroup midi + */ +typedef enum OMX_AUDIO_MIDIPLAYBACKSTATETYPE { + OMX_AUDIO_MIDIPlayBackStateUnknown = 0, /**< Unknown state or state does not map to + other defined states */ + OMX_AUDIO_MIDIPlayBackStateClosedEngaged, /**< No MIDI resource is currently open. + The MIDI engine is currently processing + MIDI events. */ + OMX_AUDIO_MIDIPlayBackStateParsing, /**< A MIDI resource is open and is being + primed. The MIDI engine is currently + processing MIDI events. */ + OMX_AUDIO_MIDIPlayBackStateOpenEngaged, /**< A MIDI resource is open and primed but + not playing. The MIDI engine is currently + processing MIDI events. The transition to + this state is only possible from the + OMX_AUDIO_MIDIPlayBackStatePlaying state, + when the 'playback head' reaches the end + of media data or the playback stops due + to stop time set.*/ + OMX_AUDIO_MIDIPlayBackStatePlaying, /**< A MIDI resource is open and currently + playing. The MIDI engine is currently + processing MIDI events.*/ + OMX_AUDIO_MIDIPlayBackStatePlayingPartially, /**< Best-effort playback due to SP-MIDI/DLS + resource constraints */ + OMX_AUDIO_MIDIPlayBackStatePlayingSilently, /**< Due to system resource constraints and + SP-MIDI content constraints, there is + no audible MIDI content during playback + currently. The situation may change if + resources are freed later.*/ + OMX_AUDIO_MIDIPlayBackStateKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_MIDIPlayBackStateVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_MIDIPlayBackStateMax = 0x7FFFFFFF +} OMX_AUDIO_MIDIPLAYBACKSTATETYPE; + + +/** MIDI status + * @ingroup midi + */ +typedef struct OMX_AUDIO_CONFIG_MIDISTATUSTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U16 nNumTracks; /**< Number of MIDI tracks in the file, read only field. + NOTE: May not return a meaningful value until the entire + file is parsed and buffered. */ + OMX_U32 nDuration; /**< The length of the currently open MIDI resource + in milliseconds. NOTE: May not return a meaningful value + until the entire file is parsed and buffered. */ + OMX_U32 nPosition; /**< Current Position of the MIDI resource being played + in milliseconds */ + OMX_BOOL bVibra; /**< Does Vibra track exist? NOTE: May not return a meaningful + value until the entire file is parsed and buffered. */ + OMX_U32 nNumMetaEvents; /**< Total number of MIDI Meta Events in the currently + open MIDI resource. NOTE: May not return a meaningful value + until the entire file is parsed and buffered. */ + OMX_U32 nNumActiveVoices; /**< Number of active voices in the currently playing + MIDI resource. NOTE: May not return a meaningful value until + the entire file is parsed and buffered. */ + OMX_AUDIO_MIDIPLAYBACKSTATETYPE eMIDIPlayBackState; /**< MIDI playback state enumeration, read only field */ +} OMX_AUDIO_CONFIG_MIDISTATUSTYPE; + + +/** MIDI Meta Event structure one per Meta Event. + * MIDI Meta Events are like audio metadata, except that they are interspersed + * with the MIDI content throughout the file and are not localized in the header. + * As such, it is necessary to retrieve information about these Meta Events from + * the engine, as it encounters these Meta Events within the MIDI content. + * For example, SMF files can have up to 14 types of MIDI Meta Events (copyright, + * author, default tempo, etc.) scattered throughout the file. + * @ingroup midi + */ +typedef struct OMX_AUDIO_CONFIG_MIDIMETAEVENTTYPE{ + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nIndex; /**< Index of Meta Event */ + OMX_U8 nMetaEventType; /**< Meta Event Type, 7bits (i.e. 0 - 127) */ + OMX_U32 nMetaEventSize; /**< size of the Meta Event in bytes */ + OMX_U32 nTrack; /**< track number for the meta event */ + OMX_U32 nPosition; /**< Position of the meta-event in milliseconds */ +} OMX_AUDIO_CONFIG_MIDIMETAEVENTTYPE; + + +/** MIDI Meta Event Data structure - one per Meta Event. + * @ingroup midi + */ +typedef struct OMX_AUDIO_CONFIG_MIDIMETAEVENTDATATYPE{ + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nIndex; /**< Index of Meta Event */ + OMX_U32 nMetaEventSize; /**< size of the Meta Event in bytes */ + OMX_U8 nData[1]; /**< array of one or more bytes of meta data + as indicated by the nMetaEventSize field */ +} OMX_AUDIO_CONFIG__MIDIMETAEVENTDATATYPE; + + +/** Audio Volume adjustment for a port */ +typedef struct OMX_AUDIO_CONFIG_VOLUMETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Port index indicating which port to + set. Select the input port to set + just that port's volume. Select the + output port to adjust the master + volume. */ + OMX_BOOL bLinear; /**< Is the volume to be set in linear (0.100) + or logarithmic scale (mB) */ + OMX_BS32 sVolume; /**< Volume linear setting in the 0..100 range, OR + Volume logarithmic setting for this port. The values + for volume are in mB (millibels = 1/100 dB) relative + to a gain of 1 (e.g. the output is the same as the + input level). Values are in mB from nMax + (maximum volume) to nMin mB (typically negative). + Since the volume is "voltage" + and not a "power", it takes a setting of + -600 mB to decrease the volume by 1/2. If + a component cannot accurately set the + volume to the requested value, it must + set the volume to the closest value BELOW + the requested value. When getting the + volume setting, the current actual volume + must be returned. */ +} OMX_AUDIO_CONFIG_VOLUMETYPE; + + +/** Audio Volume adjustment for a channel */ +typedef struct OMX_AUDIO_CONFIG_CHANNELVOLUMETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Port index indicating which port to + set. Select the input port to set + just that port's volume. Select the + output port to adjust the master + volume. */ + OMX_U32 nChannel; /**< channel to select from 0 to N-1, + using OMX_ALL to apply volume settings + to all channels */ + OMX_BOOL bLinear; /**< Is the volume to be set in linear (0.100) or + logarithmic scale (mB) */ + OMX_BS32 sVolume; /**< Volume linear setting in the 0..100 range, OR + Volume logarithmic setting for this port. + The values for volume are in mB + (millibels = 1/100 dB) relative to a gain + of 1 (e.g. the output is the same as the + input level). Values are in mB from nMax + (maximum volume) to nMin mB (typically negative). + Since the volume is "voltage" + and not a "power", it takes a setting of + -600 mB to decrease the volume by 1/2. If + a component cannot accurately set the + volume to the requested value, it must + set the volume to the closest value BELOW + the requested value. When getting the + volume setting, the current actual volume + must be returned. */ + OMX_BOOL bIsMIDI; /**< TRUE if nChannel refers to a MIDI channel, + FALSE otherwise */ +} OMX_AUDIO_CONFIG_CHANNELVOLUMETYPE; + + +/** Audio balance setting */ +typedef struct OMX_AUDIO_CONFIG_BALANCETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Port index indicating which port to + set. Select the input port to set + just that port's balance. Select the + output port to adjust the master + balance. */ + OMX_S32 nBalance; /**< balance setting for this port + (-100 to 100, where -100 indicates + all left, and no right */ +} OMX_AUDIO_CONFIG_BALANCETYPE; + + +/** Audio Port mute */ +typedef struct OMX_AUDIO_CONFIG_MUTETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Port index indicating which port to + set. Select the input port to set + just that port's mute. Select the + output port to adjust the master + mute. */ + OMX_BOOL bMute; /**< Mute setting for this port */ +} OMX_AUDIO_CONFIG_MUTETYPE; + + +/** Audio Channel mute */ +typedef struct OMX_AUDIO_CONFIG_CHANNELMUTETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannel; /**< channel to select from 0 to N-1, + using OMX_ALL to apply mute settings + to all channels */ + OMX_BOOL bMute; /**< Mute setting for this channel */ + OMX_BOOL bIsMIDI; /**< TRUE if nChannel refers to a MIDI channel, + FALSE otherwise */ +} OMX_AUDIO_CONFIG_CHANNELMUTETYPE; + + + +/** Enable / Disable for loudness control, which boosts bass and to a + * smaller extent high end frequencies to compensate for hearing + * ability at the extreme ends of the audio spectrum + */ +typedef struct OMX_AUDIO_CONFIG_LOUDNESSTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bLoudness; /**< Enable/disable for loudness */ +} OMX_AUDIO_CONFIG_LOUDNESSTYPE; + + +/** Enable / Disable for bass, which controls low frequencies + */ +typedef struct OMX_AUDIO_CONFIG_BASSTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bEnable; /**< Enable/disable for bass control */ + OMX_S32 nBass; /**< bass setting for the port, as a + continuous value from -100 to 100 + (0 means no change in bass level)*/ +} OMX_AUDIO_CONFIG_BASSTYPE; + + +/** Enable / Disable for treble, which controls high frequencies tones + */ +typedef struct OMX_AUDIO_CONFIG_TREBLETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bEnable; /**< Enable/disable for treble control */ + OMX_S32 nTreble; /**< treble setting for the port, as a + continuous value from -100 to 100 + (0 means no change in treble level) */ +} OMX_AUDIO_CONFIG_TREBLETYPE; + + +/** An equalizer is typically used for two reasons: to compensate for an + * sub-optimal frequency response of a system to make it sound more natural + * or to create intentionally some unnatural coloring to the sound to create + * an effect. + * @ingroup effects + */ +typedef struct OMX_AUDIO_CONFIG_EQUALIZERTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bEnable; /**< Enable/disable for equalizer */ + OMX_BU32 sBandIndex; /**< Band number to be set. Upper Limit is + N-1, where N is the number of bands, lower limit is 0 */ + OMX_BU32 sCenterFreq; /**< Center frequecies in Hz. This is a + read only element and is used to determine + the lower, center and upper frequency of + this band. */ + OMX_BS32 sBandLevel; /**< band level in millibels */ +} OMX_AUDIO_CONFIG_EQUALIZERTYPE; + + +/** Stereo widening mode type + * @ingroup effects + */ +typedef enum OMX_AUDIO_STEREOWIDENINGTYPE { + OMX_AUDIO_StereoWideningHeadphones, /**< Stereo widening for loudspeakers */ + OMX_AUDIO_StereoWideningLoudspeakers, /**< Stereo widening for closely spaced loudspeakers */ + OMX_AUDIO_StereoWideningKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_StereoWideningVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_StereoWideningMax = 0x7FFFFFFF +} OMX_AUDIO_STEREOWIDENINGTYPE; + + +/** Control for stereo widening, which is a special 2-channel + * case of the audio virtualizer effect. For example, for 5.1-channel + * output, it translates to virtual surround sound. + * @ingroup effects + */ +typedef struct OMX_AUDIO_CONFIG_STEREOWIDENINGTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bEnable; /**< Enable/disable for stereo widening control */ + OMX_AUDIO_STEREOWIDENINGTYPE eWideningType; /**< Stereo widening algorithm type */ + OMX_U32 nStereoWidening; /**< stereo widening setting for the port, + as a continuous value from 0 to 100 */ +} OMX_AUDIO_CONFIG_STEREOWIDENINGTYPE; + + +/** The chorus effect (or ``choralizer'') is any signal processor which makes + * one sound source (such as a voice) sound like many such sources singing + * (or playing) in unison. Since performance in unison is never exact, chorus + * effects simulate this by making independently modified copies of the input + * signal. Modifications may include (1) delay, (2) frequency shift, and + * (3) amplitude modulation. + * @ingroup effects + */ +typedef struct OMX_AUDIO_CONFIG_CHORUSTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bEnable; /**< Enable/disable for chorus */ + OMX_BU32 sDelay; /**< average delay in milliseconds */ + OMX_BU32 sModulationRate; /**< rate of modulation in millihertz */ + OMX_U32 nModulationDepth; /**< depth of modulation as a percentage of + delay (i.e. 0 to 100) */ + OMX_BU32 nFeedback; /**< Feedback from chorus output to input in percentage */ +} OMX_AUDIO_CONFIG_CHORUSTYPE; + + +/** Reverberation is part of the reflected sound that follows the early + * reflections. In a typical room, this consists of a dense succession of + * echoes whose energy decays exponentially. The reverberation effect structure + * as defined here includes both (early) reflections as well as (late) reverberations. + * @ingroup effects + */ +typedef struct OMX_AUDIO_CONFIG_REVERBERATIONTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bEnable; /**< Enable/disable for reverberation control */ + OMX_BS32 sRoomLevel; /**< Intensity level for the whole room effect + (i.e. both early reflections and late + reverberation) in millibels */ + OMX_BS32 sRoomHighFreqLevel; /**< Attenuation at high frequencies + relative to the intensity at low + frequencies in millibels */ + OMX_BS32 sReflectionsLevel; /**< Intensity level of early reflections + (relative to room value), in millibels */ + OMX_BU32 sReflectionsDelay; /**< Delay time of the first reflection relative + to the direct path, in milliseconds */ + OMX_BS32 sReverbLevel; /**< Intensity level of late reverberation + relative to room level, in millibels */ + OMX_BU32 sReverbDelay; /**< Time delay from the first early reflection + to the beginning of the late reverberation + section, in milliseconds */ + OMX_BU32 sDecayTime; /**< Late reverberation decay time at low + frequencies, in milliseconds */ + OMX_BU32 nDecayHighFreqRatio; /**< Ratio of high frequency decay time relative + to low frequency decay time in percent */ + OMX_U32 nDensity; /**< Modal density in the late reverberation decay, + in percent (i.e. 0 - 100) */ + OMX_U32 nDiffusion; /**< Echo density in the late reverberation decay, + in percent (i.e. 0 - 100) */ + OMX_BU32 sReferenceHighFreq; /**< Reference high frequency in Hertz. This is + the frequency used as the reference for all + the high-frequency settings above */ + +} OMX_AUDIO_CONFIG_REVERBERATIONTYPE; + + +/** Possible settings for the Echo Cancelation structure to use + * @ingroup effects + */ +typedef enum OMX_AUDIO_ECHOCANTYPE { + OMX_AUDIO_EchoCanOff = 0, /**< Echo Cancellation is disabled */ + OMX_AUDIO_EchoCanNormal, /**< Echo Cancellation normal operation - + echo from plastics and face */ + OMX_AUDIO_EchoCanHFree, /**< Echo Cancellation optimized for + Hands Free operation */ + OMX_AUDIO_EchoCanCarKit, /**< Echo Cancellation optimized for + Car Kit (longer echo) */ + OMX_AUDIO_EchoCanKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_EchoCanVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_EchoCanMax = 0x7FFFFFFF +} OMX_AUDIO_ECHOCANTYPE; + + +/** Enable / Disable for echo cancelation, which removes undesired echo's + * from the audio + * @ingroup effects + */ +typedef struct OMX_AUDIO_CONFIG_ECHOCANCELATIONTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_AUDIO_ECHOCANTYPE eEchoCancelation; /**< Echo cancelation settings */ +} OMX_AUDIO_CONFIG_ECHOCANCELATIONTYPE; + + +/** Enable / Disable for noise reduction, which undesired noise from + * the audio + * @ingroup effects + */ +typedef struct OMX_AUDIO_CONFIG_NOISEREDUCTIONTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bNoiseReduction; /**< Enable/disable for noise reduction */ +} OMX_AUDIO_CONFIG_NOISEREDUCTIONTYPE; + +/** @} */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif +/* File EOF */ diff --git a/phonelibs/android_frameworks_native/include/media/openmax/OMX_AudioExt.h b/phonelibs/android_frameworks_native/include/media/openmax/OMX_AudioExt.h new file mode 100644 index 0000000000..2a1c3f2e18 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/media/openmax/OMX_AudioExt.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2010 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** OMX_AudioExt.h - OpenMax IL version 1.1.2 + * The OMX_AudioExt header file contains extensions to the + * definitions used by both the application and the component to + * access video items. + */ + +#ifndef OMX_AudioExt_h +#define OMX_AudioExt_h + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* Each OMX header shall include all required header files to allow the + * header to compile without errors. The includes below are required + * for this header file to compile successfully + */ +#include + +#define OMX_AUDIO_AACToolAndroidSSBR (OMX_AUDIO_AACToolVendor << 0) /**< SSBR: MPEG-4 Single-rate (downsampled) Spectral Band Replication tool allowed or active */ +#define OMX_AUDIO_AACToolAndroidDSBR (OMX_AUDIO_AACToolVendor << 1) /**< DSBR: MPEG-4 Dual-rate Spectral Band Replication tool allowed or active */ + +typedef enum OMX_AUDIO_CODINGEXTTYPE { + OMX_AUDIO_CodingAndroidUnused = OMX_AUDIO_CodingKhronosExtensions + 0x00100000, + OMX_AUDIO_CodingAndroidAC3, /**< AC3 encoded data */ + OMX_AUDIO_CodingAndroidOPUS, /**< OPUS encoded data */ + OMX_AUDIO_CodingAndroidEAC3, /**< EAC3 encoded data */ +} OMX_AUDIO_CODINGEXTTYPE; + +typedef struct OMX_AUDIO_PARAM_ANDROID_AC3TYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels */ + OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for + variable or unknown sampling rate. */ +} OMX_AUDIO_PARAM_ANDROID_AC3TYPE; + +typedef struct OMX_AUDIO_PARAM_ANDROID_EAC3TYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels */ + OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for + variable or unknown sampling rate. */ +} OMX_AUDIO_PARAM_ANDROID_EAC3TYPE; + +typedef struct OMX_AUDIO_PARAM_ANDROID_OPUSTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels */ + OMX_U32 nBitRate; /**< Bit rate of the encoded data data. Use 0 for variable + rate or unknown bit rates. Encoding is set to the + bitrate closest to specified value (in bps) */ + OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for + variable or unknown sampling rate. */ + OMX_U32 nAudioBandWidth; /**< Audio band width (in Hz) to which an encoder should + limit the audio signal. Use 0 to let encoder decide */ +} OMX_AUDIO_PARAM_ANDROID_OPUSTYPE; + +typedef struct OMX_AUDIO_PARAM_ANDROID_AACPRESENTATIONTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_S32 nMaxOutputChannels; /**< Maximum channel count to be output, -1 if unspecified, 0 if downmixing disabled */ + OMX_S32 nDrcCut; /**< The DRC attenuation factor, between 0 and 127, -1 if unspecified */ + OMX_S32 nDrcBoost; /**< The DRC amplification factor, between 0 and 127, -1 if unspecified */ + OMX_S32 nHeavyCompression; /**< 0 for light compression, 1 for heavy compression, -1 if unspecified */ + OMX_S32 nTargetReferenceLevel; /**< Target reference level, between 0 and 127, -1 if unspecified */ + OMX_S32 nEncodedTargetLevel; /**< Target reference level assumed at the encoder, between 0 and 127, -1 if unspecified */ + OMX_S32 nPCMLimiterEnable; /**< Signal level limiting, 0 for disable, 1 for enable, -1 if unspecified */ +} OMX_AUDIO_PARAM_ANDROID_AACPRESENTATIONTYPE; + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OMX_AudioExt_h */ +/* File EOF */ diff --git a/phonelibs/android_frameworks_native/include/media/openmax/OMX_Component.h b/phonelibs/android_frameworks_native/include/media/openmax/OMX_Component.h new file mode 100644 index 0000000000..0dc2c76972 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/media/openmax/OMX_Component.h @@ -0,0 +1,596 @@ +/* ------------------------------------------------------------------ + * Copyright (C) 1998-2009 PacketVideo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. + * See the License for the specific language governing permissions + * and limitations under the License. + * ------------------------------------------------------------------- + */ +/* + * Copyright (c) 2008 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** OMX_Component.h - OpenMax IL version 1.1.2 + * The OMX_Component header file contains the definitions used to define + * the public interface of a component. This header file is intended to + * be used by both the application and the component. + */ + +#ifndef OMX_Component_h +#define OMX_Component_h + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + + +/* Each OMX header must include all required header files to allow the + * header to compile without errors. The includes below are required + * for this header file to compile successfully + */ + +#include +#include +#include +#include + +/** @ingroup comp */ +typedef enum OMX_PORTDOMAINTYPE { + OMX_PortDomainAudio, + OMX_PortDomainVideo, + OMX_PortDomainImage, + OMX_PortDomainOther, + OMX_PortDomainKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_PortDomainVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_PortDomainMax = 0x7ffffff +} OMX_PORTDOMAINTYPE; + +/** @ingroup comp */ +typedef struct OMX_PARAM_PORTDEFINITIONTYPE { + OMX_U32 nSize; /**< Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Port number the structure applies to */ + OMX_DIRTYPE eDir; /**< Direction (input or output) of this port */ + OMX_U32 nBufferCountActual; /**< The actual number of buffers allocated on this port */ + OMX_U32 nBufferCountMin; /**< The minimum number of buffers this port requires */ + OMX_U32 nBufferSize; /**< Size, in bytes, for buffers to be used for this channel */ + OMX_BOOL bEnabled; /**< Ports default to enabled and are enabled/disabled by + OMX_CommandPortEnable/OMX_CommandPortDisable. + When disabled a port is unpopulated. A disabled port + is not populated with buffers on a transition to IDLE. */ + OMX_BOOL bPopulated; /**< Port is populated with all of its buffers as indicated by + nBufferCountActual. A disabled port is always unpopulated. + An enabled port is populated on a transition to OMX_StateIdle + and unpopulated on a transition to loaded. */ + OMX_PORTDOMAINTYPE eDomain; /**< Domain of the port. Determines the contents of metadata below. */ + union { + OMX_AUDIO_PORTDEFINITIONTYPE audio; + OMX_VIDEO_PORTDEFINITIONTYPE video; + OMX_IMAGE_PORTDEFINITIONTYPE image; + OMX_OTHER_PORTDEFINITIONTYPE other; + } format; + OMX_BOOL bBuffersContiguous; + OMX_U32 nBufferAlignment; +} OMX_PARAM_PORTDEFINITIONTYPE; + +/** @ingroup comp */ +typedef struct OMX_PARAM_U32TYPE { + OMX_U32 nSize; /**< Size of this structure, in Bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nU32; /**< U32 value */ +} OMX_PARAM_U32TYPE; + +/** @ingroup rpm */ +typedef enum OMX_SUSPENSIONPOLICYTYPE { + OMX_SuspensionDisabled, /**< No suspension; v1.0 behavior */ + OMX_SuspensionEnabled, /**< Suspension allowed */ + OMX_SuspensionPolicyKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_SuspensionPolicyStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_SuspensionPolicyMax = 0x7fffffff +} OMX_SUSPENSIONPOLICYTYPE; + +/** @ingroup rpm */ +typedef struct OMX_PARAM_SUSPENSIONPOLICYTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_SUSPENSIONPOLICYTYPE ePolicy; +} OMX_PARAM_SUSPENSIONPOLICYTYPE; + +/** @ingroup rpm */ +typedef enum OMX_SUSPENSIONTYPE { + OMX_NotSuspended, /**< component is not suspended */ + OMX_Suspended, /**< component is suspended */ + OMX_SuspensionKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_SuspensionVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_SuspendMax = 0x7FFFFFFF +} OMX_SUSPENSIONTYPE; + +/** @ingroup rpm */ +typedef struct OMX_PARAM_SUSPENSIONTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_SUSPENSIONTYPE eType; +} OMX_PARAM_SUSPENSIONTYPE ; + +typedef struct OMX_CONFIG_BOOLEANTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_BOOL bEnabled; +} OMX_CONFIG_BOOLEANTYPE; + +/* Parameter specifying the content uri to use. */ +/** @ingroup cp */ +typedef struct OMX_PARAM_CONTENTURITYPE +{ + OMX_U32 nSize; /**< size of the structure in bytes, including + actual URI name */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U8 contentURI[1]; /**< The URI name */ +} OMX_PARAM_CONTENTURITYPE; + +/* Parameter specifying the pipe to use. */ +/** @ingroup cp */ +typedef struct OMX_PARAM_CONTENTPIPETYPE +{ + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_HANDLETYPE hPipe; /**< The pipe handle*/ +} OMX_PARAM_CONTENTPIPETYPE; + +/** @ingroup rpm */ +typedef struct OMX_RESOURCECONCEALMENTTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_BOOL bResourceConcealmentForbidden; /**< disallow the use of resource concealment + methods (like degrading algorithm quality to + lower resource consumption or functional bypass) + on a component as a resolution to resource conflicts. */ +} OMX_RESOURCECONCEALMENTTYPE; + + +/** @ingroup metadata */ +typedef enum OMX_METADATACHARSETTYPE { + OMX_MetadataCharsetUnknown = 0, + OMX_MetadataCharsetASCII, + OMX_MetadataCharsetBinary, + OMX_MetadataCharsetCodePage1252, + OMX_MetadataCharsetUTF8, + OMX_MetadataCharsetJavaConformantUTF8, + OMX_MetadataCharsetUTF7, + OMX_MetadataCharsetImapUTF7, + OMX_MetadataCharsetUTF16LE, + OMX_MetadataCharsetUTF16BE, + OMX_MetadataCharsetGB12345, + OMX_MetadataCharsetHZGB2312, + OMX_MetadataCharsetGB2312, + OMX_MetadataCharsetGB18030, + OMX_MetadataCharsetGBK, + OMX_MetadataCharsetBig5, + OMX_MetadataCharsetISO88591, + OMX_MetadataCharsetISO88592, + OMX_MetadataCharsetISO88593, + OMX_MetadataCharsetISO88594, + OMX_MetadataCharsetISO88595, + OMX_MetadataCharsetISO88596, + OMX_MetadataCharsetISO88597, + OMX_MetadataCharsetISO88598, + OMX_MetadataCharsetISO88599, + OMX_MetadataCharsetISO885910, + OMX_MetadataCharsetISO885913, + OMX_MetadataCharsetISO885914, + OMX_MetadataCharsetISO885915, + OMX_MetadataCharsetShiftJIS, + OMX_MetadataCharsetISO2022JP, + OMX_MetadataCharsetISO2022JP1, + OMX_MetadataCharsetISOEUCJP, + OMX_MetadataCharsetSMS7Bit, + OMX_MetadataCharsetKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_MetadataCharsetVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_MetadataCharsetTypeMax= 0x7FFFFFFF +} OMX_METADATACHARSETTYPE; + +/** @ingroup metadata */ +typedef enum OMX_METADATASCOPETYPE +{ + OMX_MetadataScopeAllLevels, + OMX_MetadataScopeTopLevel, + OMX_MetadataScopePortLevel, + OMX_MetadataScopeNodeLevel, + OMX_MetadataScopeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_MetadataScopeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_MetadataScopeTypeMax = 0x7fffffff +} OMX_METADATASCOPETYPE; + +/** @ingroup metadata */ +typedef enum OMX_METADATASEARCHMODETYPE +{ + OMX_MetadataSearchValueSizeByIndex, + OMX_MetadataSearchItemByIndex, + OMX_MetadataSearchNextItemByKey, + OMX_MetadataSearchKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_MetadataSearchVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_MetadataSearchTypeMax = 0x7fffffff +} OMX_METADATASEARCHMODETYPE; +/** @ingroup metadata */ +typedef struct OMX_CONFIG_METADATAITEMCOUNTTYPE +{ + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_METADATASCOPETYPE eScopeMode; + OMX_U32 nScopeSpecifier; + OMX_U32 nMetadataItemCount; +} OMX_CONFIG_METADATAITEMCOUNTTYPE; + +/** @ingroup metadata */ +typedef struct OMX_CONFIG_METADATAITEMTYPE +{ + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_METADATASCOPETYPE eScopeMode; + OMX_U32 nScopeSpecifier; + OMX_U32 nMetadataItemIndex; + OMX_METADATASEARCHMODETYPE eSearchMode; + OMX_METADATACHARSETTYPE eKeyCharset; + OMX_U8 nKeySizeUsed; + OMX_U8 nKey[128]; + OMX_METADATACHARSETTYPE eValueCharset; + OMX_STRING sLanguageCountry; + OMX_U32 nValueMaxSize; + OMX_U32 nValueSizeUsed; + OMX_U8 nValue[1]; +} OMX_CONFIG_METADATAITEMTYPE; + +/* @ingroup metadata */ +typedef struct OMX_CONFIG_CONTAINERNODECOUNTTYPE +{ + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_BOOL bAllKeys; + OMX_U32 nParentNodeID; + OMX_U32 nNumNodes; +} OMX_CONFIG_CONTAINERNODECOUNTTYPE; + +/** @ingroup metadata */ +typedef struct OMX_CONFIG_CONTAINERNODEIDTYPE +{ + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_BOOL bAllKeys; + OMX_U32 nParentNodeID; + OMX_U32 nNodeIndex; + OMX_U32 nNodeID; + OMX_STRING cNodeName; + OMX_BOOL bIsLeafType; +} OMX_CONFIG_CONTAINERNODEIDTYPE; + +/** @ingroup metadata */ +typedef struct OMX_PARAM_METADATAFILTERTYPE +{ + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_BOOL bAllKeys; /* if true then this structure refers to all keys and + * the three key fields below are ignored */ + OMX_METADATACHARSETTYPE eKeyCharset; + OMX_U32 nKeySizeUsed; + OMX_U8 nKey [128]; + OMX_U32 nLanguageCountrySizeUsed; + OMX_U8 nLanguageCountry[128]; + OMX_BOOL bEnabled; /* if true then key is part of filter (e.g. + * retained for query later). If false then + * key is not part of filter */ +} OMX_PARAM_METADATAFILTERTYPE; + +/** The OMX_HANDLETYPE structure defines the component handle. The component + * handle is used to access all of the component's public methods and also + * contains pointers to the component's private data area. The component + * handle is initialized by the OMX core (with help from the component) + * during the process of loading the component. After the component is + * successfully loaded, the application can safely access any of the + * component's public functions (although some may return an error because + * the state is inappropriate for the access). + * + * @ingroup comp + */ +typedef struct OMX_COMPONENTTYPE +{ + /** The size of this structure, in bytes. It is the responsibility + of the allocator of this structure to fill in this value. Since + this structure is allocated by the GetHandle function, this + function will fill in this value. */ + OMX_U32 nSize; + + /** nVersion is the version of the OMX specification that the structure + is built against. It is the responsibility of the creator of this + structure to initialize this value and every user of this structure + should verify that it knows how to use the exact version of + this structure found herein. */ + OMX_VERSIONTYPE nVersion; + + /** pComponentPrivate is a pointer to the component private data area. + This member is allocated and initialized by the component when the + component is first loaded. The application should not access this + data area. */ + OMX_PTR pComponentPrivate; + + /** pApplicationPrivate is a pointer that is a parameter to the + OMX_GetHandle method, and contains an application private value + provided by the IL client. This application private data is + returned to the IL Client by OMX in all callbacks */ + OMX_PTR pApplicationPrivate; + + /** refer to OMX_GetComponentVersion in OMX_core.h or the OMX IL + specification for details on the GetComponentVersion method. + */ + OMX_ERRORTYPE (*GetComponentVersion)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_OUT OMX_STRING pComponentName, + OMX_OUT OMX_VERSIONTYPE* pComponentVersion, + OMX_OUT OMX_VERSIONTYPE* pSpecVersion, + OMX_OUT OMX_UUIDTYPE* pComponentUUID); + + /** refer to OMX_SendCommand in OMX_core.h or the OMX IL + specification for details on the SendCommand method. + */ + OMX_ERRORTYPE (*SendCommand)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_COMMANDTYPE Cmd, + OMX_IN OMX_U32 nParam1, + OMX_IN OMX_PTR pCmdData); + + /** refer to OMX_GetParameter in OMX_core.h or the OMX IL + specification for details on the GetParameter method. + */ + OMX_ERRORTYPE (*GetParameter)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_INDEXTYPE nParamIndex, + OMX_INOUT OMX_PTR pComponentParameterStructure); + + + /** refer to OMX_SetParameter in OMX_core.h or the OMX IL + specification for details on the SetParameter method. + */ + OMX_ERRORTYPE (*SetParameter)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_INDEXTYPE nIndex, + OMX_IN OMX_PTR pComponentParameterStructure); + + + /** refer to OMX_GetConfig in OMX_core.h or the OMX IL + specification for details on the GetConfig method. + */ + OMX_ERRORTYPE (*GetConfig)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_INDEXTYPE nIndex, + OMX_INOUT OMX_PTR pComponentConfigStructure); + + + /** refer to OMX_SetConfig in OMX_core.h or the OMX IL + specification for details on the SetConfig method. + */ + OMX_ERRORTYPE (*SetConfig)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_INDEXTYPE nIndex, + OMX_IN OMX_PTR pComponentConfigStructure); + + + /** refer to OMX_GetExtensionIndex in OMX_core.h or the OMX IL + specification for details on the GetExtensionIndex method. + */ + OMX_ERRORTYPE (*GetExtensionIndex)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_STRING cParameterName, + OMX_OUT OMX_INDEXTYPE* pIndexType); + + + /** refer to OMX_GetState in OMX_core.h or the OMX IL + specification for details on the GetState method. + */ + OMX_ERRORTYPE (*GetState)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_OUT OMX_STATETYPE* pState); + + + /** The ComponentTunnelRequest method will interact with another OMX + component to determine if tunneling is possible and to setup the + tunneling. The return codes for this method can be used to + determine if tunneling is not possible, or if tunneling is not + supported. + + Base profile components (i.e. non-interop) do not support this + method and should return OMX_ErrorNotImplemented + + The interop profile component MUST support tunneling to another + interop profile component with a compatible port parameters. + A component may also support proprietary communication. + + If proprietary communication is supported the negotiation of + proprietary communication is done outside of OMX in a vendor + specific way. It is only required that the proper result be + returned and the details of how the setup is done is left + to the component implementation. + + When this method is invoked when nPort in an output port, the + component will: + 1. Populate the pTunnelSetup structure with the output port's + requirements and constraints for the tunnel. + + When this method is invoked when nPort in an input port, the + component will: + 1. Query the necessary parameters from the output port to + determine if the ports are compatible for tunneling + 2. If the ports are compatible, the component should store + the tunnel step provided by the output port + 3. Determine which port (either input or output) is the buffer + supplier, and call OMX_SetParameter on the output port to + indicate this selection. + + The component will return from this call within 5 msec. + + @param [in] hComp + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle method. + @param [in] nPort + nPort is used to select the port on the component to be used + for tunneling. + @param [in] hTunneledComp + Handle of the component to tunnel with. This is the component + handle returned by the call to the OMX_GetHandle method. When + this parameter is 0x0 the component should setup the port for + communication with the application / IL Client. + @param [in] nPortOutput + nPortOutput is used indicate the port the component should + tunnel with. + @param [in] pTunnelSetup + Pointer to the tunnel setup structure. When nPort is an output port + the component should populate the fields of this structure. When + When nPort is an input port the component should review the setup + provided by the component with the output port. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup tun + */ + + OMX_ERRORTYPE (*ComponentTunnelRequest)( + OMX_IN OMX_HANDLETYPE hComp, + OMX_IN OMX_U32 nPort, + OMX_IN OMX_HANDLETYPE hTunneledComp, + OMX_IN OMX_U32 nTunneledPort, + OMX_INOUT OMX_TUNNELSETUPTYPE* pTunnelSetup); + + /** refer to OMX_UseBuffer in OMX_core.h or the OMX IL + specification for details on the UseBuffer method. + @ingroup buf + */ + OMX_ERRORTYPE (*UseBuffer)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_INOUT OMX_BUFFERHEADERTYPE** ppBufferHdr, + OMX_IN OMX_U32 nPortIndex, + OMX_IN OMX_PTR pAppPrivate, + OMX_IN OMX_U32 nSizeBytes, + OMX_IN OMX_U8* pBuffer); + + /** refer to OMX_AllocateBuffer in OMX_core.h or the OMX IL + specification for details on the AllocateBuffer method. + @ingroup buf + */ + OMX_ERRORTYPE (*AllocateBuffer)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_INOUT OMX_BUFFERHEADERTYPE** ppBuffer, + OMX_IN OMX_U32 nPortIndex, + OMX_IN OMX_PTR pAppPrivate, + OMX_IN OMX_U32 nSizeBytes); + + /** refer to OMX_FreeBuffer in OMX_core.h or the OMX IL + specification for details on the FreeBuffer method. + @ingroup buf + */ + OMX_ERRORTYPE (*FreeBuffer)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_U32 nPortIndex, + OMX_IN OMX_BUFFERHEADERTYPE* pBuffer); + + /** refer to OMX_EmptyThisBuffer in OMX_core.h or the OMX IL + specification for details on the EmptyThisBuffer method. + @ingroup buf + */ + OMX_ERRORTYPE (*EmptyThisBuffer)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_BUFFERHEADERTYPE* pBuffer); + + /** refer to OMX_FillThisBuffer in OMX_core.h or the OMX IL + specification for details on the FillThisBuffer method. + @ingroup buf + */ + OMX_ERRORTYPE (*FillThisBuffer)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_BUFFERHEADERTYPE* pBuffer); + + /** The SetCallbacks method is used by the core to specify the callback + structure from the application to the component. This is a blocking + call. The component will return from this call within 5 msec. + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the GetHandle function. + @param [in] pCallbacks + pointer to an OMX_CALLBACKTYPE structure used to provide the + callback information to the component + @param [in] pAppData + pointer to an application defined value. It is anticipated that + the application will pass a pointer to a data structure or a "this + pointer" in this area to allow the callback (in the application) + to determine the context of the call + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + */ + OMX_ERRORTYPE (*SetCallbacks)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_CALLBACKTYPE* pCallbacks, + OMX_IN OMX_PTR pAppData); + + /** ComponentDeInit method is used to deinitialize the component + providing a means to free any resources allocated at component + initialization. NOTE: After this call the component handle is + not valid for further use. + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the GetHandle function. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + */ + OMX_ERRORTYPE (*ComponentDeInit)( + OMX_IN OMX_HANDLETYPE hComponent); + + /** @ingroup buf */ + OMX_ERRORTYPE (*UseEGLImage)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_INOUT OMX_BUFFERHEADERTYPE** ppBufferHdr, + OMX_IN OMX_U32 nPortIndex, + OMX_IN OMX_PTR pAppPrivate, + OMX_IN void* eglImage); + + OMX_ERRORTYPE (*ComponentRoleEnum)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_OUT OMX_U8 *cRole, + OMX_IN OMX_U32 nIndex); + +} OMX_COMPONENTTYPE; + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif +/* File EOF */ diff --git a/phonelibs/android_frameworks_native/include/media/openmax/OMX_ContentPipe.h b/phonelibs/android_frameworks_native/include/media/openmax/OMX_ContentPipe.h new file mode 100644 index 0000000000..0224c8a2ee --- /dev/null +++ b/phonelibs/android_frameworks_native/include/media/openmax/OMX_ContentPipe.h @@ -0,0 +1,212 @@ +/* ------------------------------------------------------------------ + * Copyright (C) 1998-2009 PacketVideo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. + * See the License for the specific language governing permissions + * and limitations under the License. + * ------------------------------------------------------------------- + */ +/* + * Copyright (c) 2008 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** OMX_ContentPipe.h - OpenMax IL version 1.1.2 + * The OMX_ContentPipe header file contains the definitions used to define + * the public interface for content piples. This header file is intended to + * be used by the component. + */ + +#ifndef OMX_CONTENTPIPE_H +#define OMX_CONTENTPIPE_H + +#ifndef KD_EACCES +/* OpenKODE error codes. CPResult values may be zero (indicating success + or one of the following values) */ +#define KD_EACCES (1) +#define KD_EADDRINUSE (2) +#define KD_EAGAIN (5) +#define KD_EBADF (7) +#define KD_EBUSY (8) +#define KD_ECONNREFUSED (9) +#define KD_ECONNRESET (10) +#define KD_EDEADLK (11) +#define KD_EDESTADDRREQ (12) +#define KD_ERANGE (35) +#define KD_EEXIST (13) +#define KD_EFBIG (14) +#define KD_EHOSTUNREACH (15) +#define KD_EINVAL (17) +#define KD_EIO (18) +#define KD_EISCONN (20) +#define KD_EISDIR (21) +#define KD_EMFILE (22) +#define KD_ENAMETOOLONG (23) +#define KD_ENOENT (24) +#define KD_ENOMEM (25) +#define KD_ENOSPC (26) +#define KD_ENOSYS (27) +#define KD_ENOTCONN (28) +#define KD_EPERM (33) +#define KD_ETIMEDOUT (36) +#define KD_EILSEQ (19) +#endif + +/** Map types from OMX standard types only here so interface is as generic as possible. */ +typedef OMX_U32 CPresult; +typedef char * CPstring; +typedef void * CPhandle; +typedef OMX_U32 CPuint; +typedef OMX_S32 CPint; +typedef char CPbyte; +typedef OMX_BOOL CPbool; + +/** enumeration of origin types used in the CP_PIPETYPE's Seek function + * @ingroup cp + */ +typedef enum CP_ORIGINTYPE { + CP_OriginBegin, + CP_OriginCur, + CP_OriginEnd, + CP_OriginKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + CP_OriginVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + CP_OriginMax = 0X7FFFFFFF +} CP_ORIGINTYPE; + +/** enumeration of contact access types used in the CP_PIPETYPE's Open function + * @ingroup cp + */ +typedef enum CP_ACCESSTYPE { + CP_AccessRead, + CP_AccessWrite, + CP_AccessReadWrite, + CP_AccessKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + CP_AccessVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + CP_AccessMax = 0X7FFFFFFF +} CP_ACCESSTYPE; + +/** enumeration of results returned by the CP_PIPETYPE's CheckAvailableBytes function + * @ingroup cp + */ +typedef enum CP_CHECKBYTESRESULTTYPE +{ + CP_CheckBytesOk, /**< There are at least the request number + of bytes available */ + CP_CheckBytesNotReady, /**< The pipe is still retrieving bytes + and presently lacks sufficient bytes. + Client will be called when they are + sufficient bytes are available. */ + CP_CheckBytesInsufficientBytes, /**< The pipe has retrieved all bytes + but those available are less than those + requested */ + CP_CheckBytesAtEndOfStream, /**< The pipe has reached the end of stream + and no more bytes are available. */ + CP_CheckBytesOutOfBuffers, /**< All read/write buffers are currently in use. */ + CP_CheckBytesKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + CP_CheckBytesVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + CP_CheckBytesMax = 0X7FFFFFFF +} CP_CHECKBYTESRESULTTYPE; + +/** enumeration of content pipe events sent to the client callback. + * @ingroup cp + */ +typedef enum CP_EVENTTYPE{ + CP_BytesAvailable, /** bytes requested in a CheckAvailableBytes call are now available*/ + CP_Overflow, /** enumeration of content pipe events sent to the client callback*/ + CP_PipeDisconnected, /** enumeration of content pipe events sent to the client callback*/ + CP_EventKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + CP_EventVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + CP_EventMax = 0X7FFFFFFF +} CP_EVENTTYPE; + +/** content pipe definition + * @ingroup cp + */ +typedef struct CP_PIPETYPE +{ + /** Open a content stream for reading or writing. */ + CPresult (*Open)( CPhandle* hContent, CPstring szURI, CP_ACCESSTYPE eAccess ); + + /** Close a content stream. */ + CPresult (*Close)( CPhandle hContent ); + + /** Create a content source and open it for writing. */ + CPresult (*Create)( CPhandle *hContent, CPstring szURI ); + + /** Check the that specified number of bytes are available for reading or writing (depending on access type).*/ + CPresult (*CheckAvailableBytes)( CPhandle hContent, CPuint nBytesRequested, CP_CHECKBYTESRESULTTYPE *eResult ); + + /** Seek to certain position in the content relative to the specified origin. */ + CPresult (*SetPosition)( CPhandle hContent, CPint nOffset, CP_ORIGINTYPE eOrigin); + + /** Retrieve the current position relative to the start of the content. */ + CPresult (*GetPosition)( CPhandle hContent, CPuint *pPosition); + + /** Retrieve data of the specified size from the content stream (advance content pointer by size of data). + Note: pipe client provides pointer. This function is appropriate for small high frequency reads. */ + CPresult (*Read)( CPhandle hContent, CPbyte *pData, CPuint nSize); + + /** Retrieve a buffer allocated by the pipe that contains the requested number of bytes. + Buffer contains the next block of bytes, as specified by nSize, of the content. nSize also + returns the size of the block actually read. Content pointer advances the by the returned size. + Note: pipe provides pointer. This function is appropriate for large reads. The client must call + ReleaseReadBuffer when done with buffer. + + In some cases the requested block may not reside in contiguous memory within the + pipe implementation. For instance if the pipe leverages a circular buffer then the requested + block may straddle the boundary of the circular buffer. By default a pipe implementation + performs a copy in this case to provide the block to the pipe client in one contiguous buffer. + If, however, the client sets bForbidCopy, then the pipe returns only those bytes preceding the memory + boundary. Here the client may retrieve the data in segments over successive calls. */ + CPresult (*ReadBuffer)( CPhandle hContent, CPbyte **ppBuffer, CPuint *nSize, CPbool bForbidCopy); + + /** Release a buffer obtained by ReadBuffer back to the pipe. */ + CPresult (*ReleaseReadBuffer)(CPhandle hContent, CPbyte *pBuffer); + + /** Write data of the specified size to the content (advance content pointer by size of data). + Note: pipe client provides pointer. This function is appropriate for small high frequency writes. */ + CPresult (*Write)( CPhandle hContent, CPbyte *data, CPuint nSize); + + /** Retrieve a buffer allocated by the pipe used to write data to the content. + Client will fill buffer with output data. Note: pipe provides pointer. This function is appropriate + for large writes. The client must call WriteBuffer when done it has filled the buffer with data.*/ + CPresult (*GetWriteBuffer)( CPhandle hContent, CPbyte **ppBuffer, CPuint nSize); + + /** Deliver a buffer obtained via GetWriteBuffer to the pipe. Pipe will write the + the contents of the buffer to content and advance content pointer by the size of the buffer */ + CPresult (*WriteBuffer)( CPhandle hContent, CPbyte *pBuffer, CPuint nFilledSize); + + /** Register a per-handle client callback with the content pipe. */ + CPresult (*RegisterCallback)( CPhandle hContent, CPresult (*ClientCallback)(CP_EVENTTYPE eEvent, CPuint iParam)); + +} CP_PIPETYPE; + +#endif + diff --git a/phonelibs/android_frameworks_native/include/media/openmax/OMX_Core.h b/phonelibs/android_frameworks_native/include/media/openmax/OMX_Core.h new file mode 100644 index 0000000000..f746a69d2a --- /dev/null +++ b/phonelibs/android_frameworks_native/include/media/openmax/OMX_Core.h @@ -0,0 +1,1464 @@ +/* ------------------------------------------------------------------ + * Copyright (C) 1998-2009 PacketVideo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. + * See the License for the specific language governing permissions + * and limitations under the License. + * ------------------------------------------------------------------- + */ +/* + * Copyright (c) 2008 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** OMX_Core.h - OpenMax IL version 1.1.2 + * The OMX_Core header file contains the definitions used by both the + * application and the component to access common items. + */ + +#ifndef OMX_Core_h +#define OMX_Core_h + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +/* Each OMX header shall include all required header files to allow the + * header to compile without errors. The includes below are required + * for this header file to compile successfully + */ + +#include + + +/** The OMX_COMMANDTYPE enumeration is used to specify the action in the + * OMX_SendCommand macro. + * @ingroup core + */ +typedef enum OMX_COMMANDTYPE +{ + OMX_CommandStateSet, /**< Change the component state */ + OMX_CommandFlush, /**< Flush the data queue(s) of a component */ + OMX_CommandPortDisable, /**< Disable a port on a component. */ + OMX_CommandPortEnable, /**< Enable a port on a component. */ + OMX_CommandMarkBuffer, /**< Mark a component/buffer for observation */ + OMX_CommandKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_CommandVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_CommandMax = 0X7FFFFFFF +} OMX_COMMANDTYPE; + + + +/** The OMX_STATETYPE enumeration is used to indicate or change the component + * state. This enumeration reflects the current state of the component when + * used with the OMX_GetState macro or becomes the parameter in a state change + * command when used with the OMX_SendCommand macro. + * + * The component will be in the Loaded state after the component is initially + * loaded into memory. In the Loaded state, the component is not allowed to + * allocate or hold resources other than to build it's internal parameter + * and configuration tables. The application will send one or more + * SetParameters/GetParameters and SetConfig/GetConfig commands to the + * component and the component will record each of these parameter and + * configuration changes for use later. When the application sends the + * Idle command, the component will acquire the resources needed for the + * specified configuration and will transition to the idle state if the + * allocation is successful. If the component cannot successfully + * transition to the idle state for any reason, the state of the component + * shall be fully rolled back to the Loaded state (e.g. all allocated + * resources shall be released). When the component receives the command + * to go to the Executing state, it shall begin processing buffers by + * sending all input buffers it holds to the application. While + * the component is in the Idle state, the application may also send the + * Pause command. If the component receives the pause command while in the + * Idle state, the component shall send all input buffers it holds to the + * application, but shall not begin processing buffers. This will allow the + * application to prefill buffers. + * + * @ingroup comp + */ + +typedef enum OMX_STATETYPE +{ + OMX_StateInvalid, /**< component has detected that it's internal data + structures are corrupted to the point that + it cannot determine it's state properly */ + OMX_StateLoaded, /**< component has been loaded but has not completed + initialization. The OMX_SetParameter macro + and the OMX_GetParameter macro are the only + valid macros allowed to be sent to the + component in this state. */ + OMX_StateIdle, /**< component initialization has been completed + successfully and the component is ready to + to start. */ + OMX_StateExecuting, /**< component has accepted the start command and + is processing data (if data is available) */ + OMX_StatePause, /**< component has received pause command */ + OMX_StateWaitForResources, /**< component is waiting for resources, either after + preemption or before it gets the resources requested. + See specification for complete details. */ + OMX_StateKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_StateVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_StateMax = 0X7FFFFFFF +} OMX_STATETYPE; + +/** The OMX_ERRORTYPE enumeration defines the standard OMX Errors. These + * errors should cover most of the common failure cases. However, + * vendors are free to add additional error messages of their own as + * long as they follow these rules: + * 1. Vendor error messages shall be in the range of 0x90000000 to + * 0x9000FFFF. + * 2. Vendor error messages shall be defined in a header file provided + * with the component. No error messages are allowed that are + * not defined. + */ +typedef enum OMX_ERRORTYPE +{ + OMX_ErrorNone = 0, + + /** There were insufficient resources to perform the requested operation */ + OMX_ErrorInsufficientResources = (OMX_S32) 0x80001000, + + /** There was an error, but the cause of the error could not be determined */ + OMX_ErrorUndefined = (OMX_S32) 0x80001001, + + /** The component name string was not valid */ + OMX_ErrorInvalidComponentName = (OMX_S32) 0x80001002, + + /** No component with the specified name string was found */ + OMX_ErrorComponentNotFound = (OMX_S32) 0x80001003, + + /** The component specified did not have a "OMX_ComponentInit" or + "OMX_ComponentDeInit entry point */ + OMX_ErrorInvalidComponent = (OMX_S32) 0x80001004, + + /** One or more parameters were not valid */ + OMX_ErrorBadParameter = (OMX_S32) 0x80001005, + + /** The requested function is not implemented */ + OMX_ErrorNotImplemented = (OMX_S32) 0x80001006, + + /** The buffer was emptied before the next buffer was ready */ + OMX_ErrorUnderflow = (OMX_S32) 0x80001007, + + /** The buffer was not available when it was needed */ + OMX_ErrorOverflow = (OMX_S32) 0x80001008, + + /** The hardware failed to respond as expected */ + OMX_ErrorHardware = (OMX_S32) 0x80001009, + + /** The component is in the state OMX_StateInvalid */ + OMX_ErrorInvalidState = (OMX_S32) 0x8000100A, + + /** Stream is found to be corrupt */ + OMX_ErrorStreamCorrupt = (OMX_S32) 0x8000100B, + + /** Ports being connected are not compatible */ + OMX_ErrorPortsNotCompatible = (OMX_S32) 0x8000100C, + + /** Resources allocated to an idle component have been + lost resulting in the component returning to the loaded state */ + OMX_ErrorResourcesLost = (OMX_S32) 0x8000100D, + + /** No more indicies can be enumerated */ + OMX_ErrorNoMore = (OMX_S32) 0x8000100E, + + /** The component detected a version mismatch */ + OMX_ErrorVersionMismatch = (OMX_S32) 0x8000100F, + + /** The component is not ready to return data at this time */ + OMX_ErrorNotReady = (OMX_S32) 0x80001010, + + /** There was a timeout that occurred */ + OMX_ErrorTimeout = (OMX_S32) 0x80001011, + + /** This error occurs when trying to transition into the state you are already in */ + OMX_ErrorSameState = (OMX_S32) 0x80001012, + + /** Resources allocated to an executing or paused component have been + preempted, causing the component to return to the idle state */ + OMX_ErrorResourcesPreempted = (OMX_S32) 0x80001013, + + /** A non-supplier port sends this error to the IL client (via the EventHandler callback) + during the allocation of buffers (on a transition from the LOADED to the IDLE state or + on a port restart) when it deems that it has waited an unusually long time for the supplier + to send it an allocated buffer via a UseBuffer call. */ + OMX_ErrorPortUnresponsiveDuringAllocation = (OMX_S32) 0x80001014, + + /** A non-supplier port sends this error to the IL client (via the EventHandler callback) + during the deallocation of buffers (on a transition from the IDLE to LOADED state or + on a port stop) when it deems that it has waited an unusually long time for the supplier + to request the deallocation of a buffer header via a FreeBuffer call. */ + OMX_ErrorPortUnresponsiveDuringDeallocation = (OMX_S32) 0x80001015, + + /** A supplier port sends this error to the IL client (via the EventHandler callback) + during the stopping of a port (either on a transition from the IDLE to LOADED + state or a port stop) when it deems that it has waited an unusually long time for + the non-supplier to return a buffer via an EmptyThisBuffer or FillThisBuffer call. */ + OMX_ErrorPortUnresponsiveDuringStop = (OMX_S32) 0x80001016, + + /** Attempting a state transtion that is not allowed */ + OMX_ErrorIncorrectStateTransition = (OMX_S32) 0x80001017, + + /* Attempting a command that is not allowed during the present state. */ + OMX_ErrorIncorrectStateOperation = (OMX_S32) 0x80001018, + + /** The values encapsulated in the parameter or config structure are not supported. */ + OMX_ErrorUnsupportedSetting = (OMX_S32) 0x80001019, + + /** The parameter or config indicated by the given index is not supported. */ + OMX_ErrorUnsupportedIndex = (OMX_S32) 0x8000101A, + + /** The port index supplied is incorrect. */ + OMX_ErrorBadPortIndex = (OMX_S32) 0x8000101B, + + /** The port has lost one or more of its buffers and it thus unpopulated. */ + OMX_ErrorPortUnpopulated = (OMX_S32) 0x8000101C, + + /** Component suspended due to temporary loss of resources */ + OMX_ErrorComponentSuspended = (OMX_S32) 0x8000101D, + + /** Component suspended due to an inability to acquire dynamic resources */ + OMX_ErrorDynamicResourcesUnavailable = (OMX_S32) 0x8000101E, + + /** When the macroblock error reporting is enabled the component returns new error + for every frame that has errors */ + OMX_ErrorMbErrorsInFrame = (OMX_S32) 0x8000101F, + + /** A component reports this error when it cannot parse or determine the format of an input stream. */ + OMX_ErrorFormatNotDetected = (OMX_S32) 0x80001020, + + /** The content open operation failed. */ + OMX_ErrorContentPipeOpenFailed = (OMX_S32) 0x80001021, + + /** The content creation operation failed. */ + OMX_ErrorContentPipeCreationFailed = (OMX_S32) 0x80001022, + + /** Separate table information is being used */ + OMX_ErrorSeperateTablesUsed = (OMX_S32) 0x80001023, + + /** Tunneling is unsupported by the component*/ + OMX_ErrorTunnelingUnsupported = (OMX_S32) 0x80001024, + + OMX_ErrorKhronosExtensions = (OMX_S32)0x8F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_ErrorVendorStartUnused = (OMX_S32)0x90000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_ErrorMax = 0x7FFFFFFF +} OMX_ERRORTYPE; + +/** @ingroup core */ +typedef OMX_ERRORTYPE (* OMX_COMPONENTINITTYPE)(OMX_IN OMX_HANDLETYPE hComponent); + +/** @ingroup core */ +typedef struct OMX_COMPONENTREGISTERTYPE +{ + const char * pName; /* Component name, 128 byte limit (including '\0') applies */ + OMX_COMPONENTINITTYPE pInitialize; /* Component instance initialization function */ +} OMX_COMPONENTREGISTERTYPE; + +/** @ingroup core */ +extern OMX_COMPONENTREGISTERTYPE OMX_ComponentRegistered[]; + +/** @ingroup rpm */ +typedef struct OMX_PRIORITYMGMTTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nGroupPriority; /**< Priority of the component group */ + OMX_U32 nGroupID; /**< ID of the component group */ +} OMX_PRIORITYMGMTTYPE; + +/* Component name and Role names are limited to 128 characters including the terminating '\0'. */ +#define OMX_MAX_STRINGNAME_SIZE 128 + +/** @ingroup comp */ +typedef struct OMX_PARAM_COMPONENTROLETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U8 cRole[OMX_MAX_STRINGNAME_SIZE]; /**< name of standard component which defines component role */ +} OMX_PARAM_COMPONENTROLETYPE; + +/** End of Stream Buffer Flag: + * + * A component sets EOS when it has no more data to emit on a particular + * output port. Thus an output port shall set EOS on the last buffer it + * emits. A component's determination of when an output port should + * cease sending data is implemenation specific. + * @ingroup buf + */ + +#define OMX_BUFFERFLAG_EOS 0x00000001 + +/** Start Time Buffer Flag: + * + * The source of a stream (e.g. a demux component) sets the STARTTIME + * flag on the buffer that contains the starting timestamp for the + * stream. The starting timestamp corresponds to the first data that + * should be displayed at startup or after a seek. + * The first timestamp of the stream is not necessarily the start time. + * For instance, in the case of a seek to a particular video frame, + * the target frame may be an interframe. Thus the first buffer of + * the stream will be the intra-frame preceding the target frame and + * the starttime will occur with the target frame (with any other + * required frames required to reconstruct the target intervening). + * + * The STARTTIME flag is directly associated with the buffer's + * timestamp ' thus its association to buffer data and its + * propagation is identical to the timestamp's. + * + * When a Sync Component client receives a buffer with the + * STARTTIME flag it shall perform a SetConfig on its sync port + * using OMX_ConfigTimeClientStartTime and passing the buffer's + * timestamp. + * + * @ingroup buf + */ + +#define OMX_BUFFERFLAG_STARTTIME 0x00000002 + + + +/** Decode Only Buffer Flag: + * + * The source of a stream (e.g. a demux component) sets the DECODEONLY + * flag on any buffer that should shall be decoded but should not be + * displayed. This flag is used, for instance, when a source seeks to + * a target interframe that requires the decode of frames preceding the + * target to facilitate the target's reconstruction. In this case the + * source would emit the frames preceding the target downstream + * but mark them as decode only. + * + * The DECODEONLY is associated with buffer data and propagated in a + * manner identical to the buffer timestamp. + * + * A component that renders data should ignore all buffers with + * the DECODEONLY flag set. + * + * @ingroup buf + */ + +#define OMX_BUFFERFLAG_DECODEONLY 0x00000004 + + +/* Data Corrupt Flag: This flag is set when the IL client believes the data in the associated buffer is corrupt + * @ingroup buf + */ + +#define OMX_BUFFERFLAG_DATACORRUPT 0x00000008 + +/* End of Frame: The buffer contains exactly one end of frame and no data + * occurs after the end of frame. This flag is an optional hint. The absence + * of this flag does not imply the absence of an end of frame within the buffer. + * @ingroup buf +*/ +#define OMX_BUFFERFLAG_ENDOFFRAME 0x00000010 + +/* Sync Frame Flag: This flag is set when the buffer content contains a coded sync frame ' + * a frame that has no dependency on any other frame information + * @ingroup buf + */ +#define OMX_BUFFERFLAG_SYNCFRAME 0x00000020 + +/* Extra data present flag: there is extra data appended to the data stream + * residing in the buffer + * @ingroup buf + */ +#define OMX_BUFFERFLAG_EXTRADATA 0x00000040 + +/** Codec Config Buffer Flag: +* OMX_BUFFERFLAG_CODECCONFIG is an optional flag that is set by an +* output port when all bytes in the buffer form part or all of a set of +* codec specific configuration data. Examples include SPS/PPS nal units +* for OMX_VIDEO_CodingAVC or AudioSpecificConfig data for +* OMX_AUDIO_CodingAAC. Any component that for a given stream sets +* OMX_BUFFERFLAG_CODECCONFIG shall not mix codec configuration bytes +* with frame data in the same buffer, and shall send all buffers +* containing codec configuration bytes before any buffers containing +* frame data that those configurations bytes describe. +* If the stream format for a particular codec has a frame specific +* header at the start of each frame, for example OMX_AUDIO_CodingMP3 or +* OMX_AUDIO_CodingAAC in ADTS mode, then these shall be presented as +* normal without setting OMX_BUFFERFLAG_CODECCONFIG. + * @ingroup buf + */ +#define OMX_BUFFERFLAG_CODECCONFIG 0x00000080 + + + +/** @ingroup buf */ +typedef struct OMX_BUFFERHEADERTYPE +{ + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U8* pBuffer; /**< Pointer to actual block of memory + that is acting as the buffer */ + OMX_U32 nAllocLen; /**< size of the buffer allocated, in bytes */ + OMX_U32 nFilledLen; /**< number of bytes currently in the + buffer */ + OMX_U32 nOffset; /**< start offset of valid data in bytes from + the start of the buffer */ + OMX_PTR pAppPrivate; /**< pointer to any data the application + wants to associate with this buffer */ + OMX_PTR pPlatformPrivate; /**< pointer to any data the platform + wants to associate with this buffer */ + OMX_PTR pInputPortPrivate; /**< pointer to any data the input port + wants to associate with this buffer */ + OMX_PTR pOutputPortPrivate; /**< pointer to any data the output port + wants to associate with this buffer */ + OMX_HANDLETYPE hMarkTargetComponent; /**< The component that will generate a + mark event upon processing this buffer. */ + OMX_PTR pMarkData; /**< Application specific data associated with + the mark sent on a mark event to disambiguate + this mark from others. */ + OMX_U32 nTickCount; /**< Optional entry that the component and + application can update with a tick count + when they access the component. This + value should be in microseconds. Since + this is a value relative to an arbitrary + starting point, this value cannot be used + to determine absolute time. This is an + optional entry and not all components + will update it.*/ + OMX_TICKS nTimeStamp; /**< Timestamp corresponding to the sample + starting at the first logical sample + boundary in the buffer. Timestamps of + successive samples within the buffer may + be inferred by adding the duration of the + of the preceding buffer to the timestamp + of the preceding buffer.*/ + OMX_U32 nFlags; /**< buffer specific flags */ + OMX_U32 nOutputPortIndex; /**< The index of the output port (if any) using + this buffer */ + OMX_U32 nInputPortIndex; /**< The index of the input port (if any) using + this buffer */ +} OMX_BUFFERHEADERTYPE; + +/** The OMX_EXTRADATATYPE enumeration is used to define the + * possible extra data payload types. + * NB: this enum is binary backwards compatible with the previous + * OMX_EXTRADATA_QUANT define. This should be replaced with + * OMX_ExtraDataQuantization. + */ +typedef enum OMX_EXTRADATATYPE +{ + OMX_ExtraDataNone = 0, /**< Indicates that no more extra data sections follow */ + OMX_ExtraDataQuantization, /**< The data payload contains quantization data */ + OMX_ExtraDataKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_ExtraDataVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_ExtraDataMax = 0x7FFFFFFF +} OMX_EXTRADATATYPE; + + +typedef struct OMX_OTHER_EXTRADATATYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_EXTRADATATYPE eType; /* Extra Data type */ + OMX_U32 nDataSize; /* Size of the supporting data to follow */ + OMX_U8 data[1]; /* Supporting data hint */ +} OMX_OTHER_EXTRADATATYPE; + +/** @ingroup comp */ +typedef struct OMX_PORT_PARAM_TYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPorts; /**< The number of ports for this component */ + OMX_U32 nStartPortNumber; /** first port number for this type of port */ +} OMX_PORT_PARAM_TYPE; + +/** @ingroup comp */ +typedef enum OMX_EVENTTYPE +{ + OMX_EventCmdComplete, /**< component has sucessfully completed a command */ + OMX_EventError, /**< component has detected an error condition */ + OMX_EventMark, /**< component has detected a buffer mark */ + OMX_EventPortSettingsChanged, /**< component is reported a port settings change */ + OMX_EventBufferFlag, /**< component has detected an EOS */ + OMX_EventResourcesAcquired, /**< component has been granted resources and is + automatically starting the state change from + OMX_StateWaitForResources to OMX_StateIdle. */ + OMX_EventComponentResumed, /**< Component resumed due to reacquisition of resources */ + OMX_EventDynamicResourcesAvailable, /**< Component has acquired previously unavailable dynamic resources */ + OMX_EventPortFormatDetected, /**< Component has detected a supported format. */ + OMX_EventKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_EventVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + + /** Event when tunneled decoder has rendered an output or reached EOS + * nData1 must contain the number of timestamps returned + * pEventData must point to an array of the OMX_VIDEO_RENDEREVENTTYPE structs containing the + * render-timestamps of each frame. Component may batch rendered timestamps using this event, + * but must signal the event no more than 40ms after the first frame in the batch. The frames + * must be ordered by system timestamp inside and across batches. + * + * If component is doing frame-rate conversion, it must signal the render time of each + * converted frame, and must interpolate media timestamps for in-between frames. + * + * When the component reached EOS, it must signal an EOS timestamp using the same mechanism. + * This is in addition to the timestamp of the last rendered frame, and should follow that + * frame. + */ + OMX_EventOutputRendered = 0x7F000001, + OMX_EventMax = 0x7FFFFFFF +} OMX_EVENTTYPE; + +typedef struct OMX_CALLBACKTYPE +{ + /** The EventHandler method is used to notify the application when an + event of interest occurs. Events are defined in the OMX_EVENTTYPE + enumeration. Please see that enumeration for details of what will + be returned for each type of event. Callbacks should not return + an error to the component, so if an error occurs, the application + shall handle it internally. This is a blocking call. + + The application should return from this call within 5 msec to avoid + blocking the component for an excessively long period of time. + + @param hComponent + handle of the component to access. This is the component + handle returned by the call to the GetHandle function. + @param pAppData + pointer to an application defined value that was provided in the + pAppData parameter to the OMX_GetHandle method for the component. + This application defined value is provided so that the application + can have a component specific context when receiving the callback. + @param eEvent + Event that the component wants to notify the application about. + @param nData1 + nData will be the OMX_ERRORTYPE for an error event and will be + an OMX_COMMANDTYPE for a command complete event and OMX_INDEXTYPE for a OMX_PortSettingsChanged event. + @param nData2 + nData2 will hold further information related to the event. Can be OMX_STATETYPE for + a OMX_CommandStateSet command or port index for a OMX_PortSettingsChanged event. + Default value is 0 if not used. ) + @param pEventData + Pointer to additional event-specific data (see spec for meaning). + */ + + OMX_ERRORTYPE (*EventHandler)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_PTR pAppData, + OMX_IN OMX_EVENTTYPE eEvent, + OMX_IN OMX_U32 nData1, + OMX_IN OMX_U32 nData2, + OMX_IN OMX_PTR pEventData); + + /** The EmptyBufferDone method is used to return emptied buffers from an + input port back to the application for reuse. This is a blocking call + so the application should not attempt to refill the buffers during this + call, but should queue them and refill them in another thread. There + is no error return, so the application shall handle any errors generated + internally. + + The application should return from this call within 5 msec. + + @param hComponent + handle of the component to access. This is the component + handle returned by the call to the GetHandle function. + @param pAppData + pointer to an application defined value that was provided in the + pAppData parameter to the OMX_GetHandle method for the component. + This application defined value is provided so that the application + can have a component specific context when receiving the callback. + @param pBuffer + pointer to an OMX_BUFFERHEADERTYPE structure allocated with UseBuffer + or AllocateBuffer indicating the buffer that was emptied. + @ingroup buf + */ + OMX_ERRORTYPE (*EmptyBufferDone)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_PTR pAppData, + OMX_IN OMX_BUFFERHEADERTYPE* pBuffer); + + /** The FillBufferDone method is used to return filled buffers from an + output port back to the application for emptying and then reuse. + This is a blocking call so the application should not attempt to + empty the buffers during this call, but should queue the buffers + and empty them in another thread. There is no error return, so + the application shall handle any errors generated internally. The + application shall also update the buffer header to indicate the + number of bytes placed into the buffer. + + The application should return from this call within 5 msec. + + @param hComponent + handle of the component to access. This is the component + handle returned by the call to the GetHandle function. + @param pAppData + pointer to an application defined value that was provided in the + pAppData parameter to the OMX_GetHandle method for the component. + This application defined value is provided so that the application + can have a component specific context when receiving the callback. + @param pBuffer + pointer to an OMX_BUFFERHEADERTYPE structure allocated with UseBuffer + or AllocateBuffer indicating the buffer that was filled. + @ingroup buf + */ + OMX_ERRORTYPE (*FillBufferDone)( + OMX_OUT OMX_HANDLETYPE hComponent, + OMX_OUT OMX_PTR pAppData, + OMX_OUT OMX_BUFFERHEADERTYPE* pBuffer); + +} OMX_CALLBACKTYPE; + +/** The OMX_BUFFERSUPPLIERTYPE enumeration is used to dictate port supplier + preference when tunneling between two ports. + @ingroup tun buf +*/ +typedef enum OMX_BUFFERSUPPLIERTYPE +{ + OMX_BufferSupplyUnspecified = 0x0, /**< port supplying the buffers is unspecified, + or don't care */ + OMX_BufferSupplyInput, /**< input port supplies the buffers */ + OMX_BufferSupplyOutput, /**< output port supplies the buffers */ + OMX_BufferSupplyKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_BufferSupplyVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_BufferSupplyMax = 0x7FFFFFFF +} OMX_BUFFERSUPPLIERTYPE; + + +/** buffer supplier parameter + * @ingroup tun + */ +typedef struct OMX_PARAM_BUFFERSUPPLIERTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BUFFERSUPPLIERTYPE eBufferSupplier; /**< buffer supplier */ +} OMX_PARAM_BUFFERSUPPLIERTYPE; + + +/**< indicates that buffers received by an input port of a tunnel + may not modify the data in the buffers + @ingroup tun + */ +#define OMX_PORTTUNNELFLAG_READONLY 0x00000001 + + +/** The OMX_TUNNELSETUPTYPE structure is used to pass data from an output + port to an input port as part the two ComponentTunnelRequest calls + resulting from a OMX_SetupTunnel call from the IL Client. + @ingroup tun + */ +typedef struct OMX_TUNNELSETUPTYPE +{ + OMX_U32 nTunnelFlags; /**< bit flags for tunneling */ + OMX_BUFFERSUPPLIERTYPE eSupplier; /**< supplier preference */ +} OMX_TUNNELSETUPTYPE; + +/* OMX Component headers is included to enable the core to use + macros for functions into the component for OMX release 1.0. + Developers should not access any structures or data from within + the component header directly */ +/* TO BE REMOVED - #include */ + +/** GetComponentVersion will return information about the component. + This is a blocking call. This macro will go directly from the + application to the component (via a core macro). The + component will return from this call within 5 msec. + @param [in] hComponent + handle of component to execute the command + @param [out] pComponentName + pointer to an empty string of length 128 bytes. The component + will write its name into this string. The name will be + terminated by a single zero byte. The name of a component will + be 127 bytes or less to leave room for the trailing zero byte. + An example of a valid component name is "OMX.ABC.ChannelMixer\0". + @param [out] pComponentVersion + pointer to an OMX Version structure that the component will fill + in. The component will fill in a value that indicates the + component version. NOTE: the component version is NOT the same + as the OMX Specification version (found in all structures). The + component version is defined by the vendor of the component and + its value is entirely up to the component vendor. + @param [out] pSpecVersion + pointer to an OMX Version structure that the component will fill + in. The SpecVersion is the version of the specification that the + component was built against. Please note that this value may or + may not match the structure's version. For example, if the + component was built against the 2.0 specification, but the + application (which creates the structure is built against the + 1.0 specification the versions would be different. + @param [out] pComponentUUID + pointer to the UUID of the component which will be filled in by + the component. The UUID is a unique identifier that is set at + RUN time for the component and is unique to each instantion of + the component. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp + */ +#define OMX_GetComponentVersion( \ + hComponent, \ + pComponentName, \ + pComponentVersion, \ + pSpecVersion, \ + pComponentUUID) \ + ((OMX_COMPONENTTYPE*)hComponent)->GetComponentVersion( \ + hComponent, \ + pComponentName, \ + pComponentVersion, \ + pSpecVersion, \ + pComponentUUID) /* Macro End */ + + +/** Send a command to the component. This call is a non-blocking call. + The component should check the parameters and then queue the command + to the component thread to be executed. The component thread shall + send the EventHandler() callback at the conclusion of the command. + This macro will go directly from the application to the component (via + a core macro). The component will return from this call within 5 msec. + + When the command is "OMX_CommandStateSet" the component will queue a + state transition to the new state idenfied in nParam. + + When the command is "OMX_CommandFlush", to flush a port's buffer queues, + the command will force the component to return all buffers NOT CURRENTLY + BEING PROCESSED to the application, in the order in which the buffers + were received. + + When the command is "OMX_CommandPortDisable" or + "OMX_CommandPortEnable", the component's port (given by the value of + nParam) will be stopped or restarted. + + When the command "OMX_CommandMarkBuffer" is used to mark a buffer, the + pCmdData will point to a OMX_MARKTYPE structure containing the component + handle of the component to examine the buffer chain for the mark. nParam1 + contains the index of the port on which the buffer mark is applied. + + Specification text for more details. + + @param [in] hComponent + handle of component to execute the command + @param [in] Cmd + Command for the component to execute + @param [in] nParam + Parameter for the command to be executed. When Cmd has the value + OMX_CommandStateSet, value is a member of OMX_STATETYPE. When Cmd has + the value OMX_CommandFlush, value of nParam indicates which port(s) + to flush. -1 is used to flush all ports a single port index will + only flush that port. When Cmd has the value "OMX_CommandPortDisable" + or "OMX_CommandPortEnable", the component's port is given by + the value of nParam. When Cmd has the value "OMX_CommandMarkBuffer" + the components pot is given by the value of nParam. + @param [in] pCmdData + Parameter pointing to the OMX_MARKTYPE structure when Cmd has the value + "OMX_CommandMarkBuffer". + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp + */ +#define OMX_SendCommand( \ + hComponent, \ + Cmd, \ + nParam, \ + pCmdData) \ + ((OMX_COMPONENTTYPE*)hComponent)->SendCommand( \ + hComponent, \ + Cmd, \ + nParam, \ + pCmdData) /* Macro End */ + + +/** The OMX_GetParameter macro will get one of the current parameter + settings from the component. This macro cannot only be invoked when + the component is in the OMX_StateInvalid state. The nParamIndex + parameter is used to indicate which structure is being requested from + the component. The application shall allocate the correct structure + and shall fill in the structure size and version information before + invoking this macro. When the parameter applies to a port, the + caller shall fill in the appropriate nPortIndex value indicating the + port on which the parameter applies. If the component has not had + any settings changed, then the component should return a set of + valid DEFAULT parameters for the component. This is a blocking + call. + + The component should return from this call within 20 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [in] nParamIndex + Index of the structure to be filled. This value is from the + OMX_INDEXTYPE enumeration. + @param [in,out] pComponentParameterStructure + Pointer to application allocated structure to be filled by the + component. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp + */ +#define OMX_GetParameter( \ + hComponent, \ + nParamIndex, \ + pComponentParameterStructure) \ + ((OMX_COMPONENTTYPE*)hComponent)->GetParameter( \ + hComponent, \ + nParamIndex, \ + pComponentParameterStructure) /* Macro End */ + + +/** The OMX_SetParameter macro will send an initialization parameter + structure to a component. Each structure shall be sent one at a time, + in a separate invocation of the macro. This macro can only be + invoked when the component is in the OMX_StateLoaded state, or the + port is disabled (when the parameter applies to a port). The + nParamIndex parameter is used to indicate which structure is being + passed to the component. The application shall allocate the + correct structure and shall fill in the structure size and version + information (as well as the actual data) before invoking this macro. + The application is free to dispose of this structure after the call + as the component is required to copy any data it shall retain. This + is a blocking call. + + The component should return from this call within 20 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [in] nIndex + Index of the structure to be sent. This value is from the + OMX_INDEXTYPE enumeration. + @param [in] pComponentParameterStructure + pointer to application allocated structure to be used for + initialization by the component. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp + */ +#define OMX_SetParameter( \ + hComponent, \ + nParamIndex, \ + pComponentParameterStructure) \ + ((OMX_COMPONENTTYPE*)hComponent)->SetParameter( \ + hComponent, \ + nParamIndex, \ + pComponentParameterStructure) /* Macro End */ + + +/** The OMX_GetConfig macro will get one of the configuration structures + from a component. This macro can be invoked anytime after the + component has been loaded. The nParamIndex call parameter is used to + indicate which structure is being requested from the component. The + application shall allocate the correct structure and shall fill in the + structure size and version information before invoking this macro. + If the component has not had this configuration parameter sent before, + then the component should return a set of valid DEFAULT values for the + component. This is a blocking call. + + The component should return from this call within 5 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [in] nIndex + Index of the structure to be filled. This value is from the + OMX_INDEXTYPE enumeration. + @param [in,out] pComponentConfigStructure + pointer to application allocated structure to be filled by the + component. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp +*/ +#define OMX_GetConfig( \ + hComponent, \ + nConfigIndex, \ + pComponentConfigStructure) \ + ((OMX_COMPONENTTYPE*)hComponent)->GetConfig( \ + hComponent, \ + nConfigIndex, \ + pComponentConfigStructure) /* Macro End */ + + +/** The OMX_SetConfig macro will send one of the configuration + structures to a component. Each structure shall be sent one at a time, + each in a separate invocation of the macro. This macro can be invoked + anytime after the component has been loaded. The application shall + allocate the correct structure and shall fill in the structure size + and version information (as well as the actual data) before invoking + this macro. The application is free to dispose of this structure after + the call as the component is required to copy any data it shall retain. + This is a blocking call. + + The component should return from this call within 5 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [in] nConfigIndex + Index of the structure to be sent. This value is from the + OMX_INDEXTYPE enumeration above. + @param [in] pComponentConfigStructure + pointer to application allocated structure to be used for + initialization by the component. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp + */ +#define OMX_SetConfig( \ + hComponent, \ + nConfigIndex, \ + pComponentConfigStructure) \ + ((OMX_COMPONENTTYPE*)hComponent)->SetConfig( \ + hComponent, \ + nConfigIndex, \ + pComponentConfigStructure) /* Macro End */ + + +/** The OMX_GetExtensionIndex macro will invoke a component to translate + a vendor specific configuration or parameter string into an OMX + structure index. There is no requirement for the vendor to support + this command for the indexes already found in the OMX_INDEXTYPE + enumeration (this is done to save space in small components). The + component shall support all vendor supplied extension indexes not found + in the master OMX_INDEXTYPE enumeration. This is a blocking call. + + The component should return from this call within 5 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the GetHandle function. + @param [in] cParameterName + OMX_STRING that shall be less than 128 characters long including + the trailing null byte. This is the string that will get + translated by the component into a configuration index. + @param [out] pIndexType + a pointer to a OMX_INDEXTYPE to receive the index value. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp + */ +#define OMX_GetExtensionIndex( \ + hComponent, \ + cParameterName, \ + pIndexType) \ + ((OMX_COMPONENTTYPE*)hComponent)->GetExtensionIndex( \ + hComponent, \ + cParameterName, \ + pIndexType) /* Macro End */ + + +/** The OMX_GetState macro will invoke the component to get the current + state of the component and place the state value into the location + pointed to by pState. + + The component should return from this call within 5 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [out] pState + pointer to the location to receive the state. The value returned + is one of the OMX_STATETYPE members + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp + */ +#define OMX_GetState( \ + hComponent, \ + pState) \ + ((OMX_COMPONENTTYPE*)hComponent)->GetState( \ + hComponent, \ + pState) /* Macro End */ + + +/** The OMX_UseBuffer macro will request that the component use + a buffer (and allocate its own buffer header) already allocated + by another component, or by the IL Client. This is a blocking + call. + + The component should return from this call within 20 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [out] ppBuffer + pointer to an OMX_BUFFERHEADERTYPE structure used to receive the + pointer to the buffer header + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp buf + */ + +#define OMX_UseBuffer( \ + hComponent, \ + ppBufferHdr, \ + nPortIndex, \ + pAppPrivate, \ + nSizeBytes, \ + pBuffer) \ + ((OMX_COMPONENTTYPE*)hComponent)->UseBuffer( \ + hComponent, \ + ppBufferHdr, \ + nPortIndex, \ + pAppPrivate, \ + nSizeBytes, \ + pBuffer) + + +/** The OMX_AllocateBuffer macro will request that the component allocate + a new buffer and buffer header. The component will allocate the + buffer and the buffer header and return a pointer to the buffer + header. This is a blocking call. + + The component should return from this call within 5 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [out] ppBuffer + pointer to an OMX_BUFFERHEADERTYPE structure used to receive + the pointer to the buffer header + @param [in] nPortIndex + nPortIndex is used to select the port on the component the buffer will + be used with. The port can be found by using the nPortIndex + value as an index into the Port Definition array of the component. + @param [in] pAppPrivate + pAppPrivate is used to initialize the pAppPrivate member of the + buffer header structure. + @param [in] nSizeBytes + size of the buffer to allocate. Used when bAllocateNew is true. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp buf + */ +#define OMX_AllocateBuffer( \ + hComponent, \ + ppBuffer, \ + nPortIndex, \ + pAppPrivate, \ + nSizeBytes) \ + ((OMX_COMPONENTTYPE*)hComponent)->AllocateBuffer( \ + hComponent, \ + ppBuffer, \ + nPortIndex, \ + pAppPrivate, \ + nSizeBytes) /* Macro End */ + + +/** The OMX_FreeBuffer macro will release a buffer header from the component + which was allocated using either OMX_AllocateBuffer or OMX_UseBuffer. If + the component allocated the buffer (see the OMX_UseBuffer macro) then + the component shall free the buffer and buffer header. This is a + blocking call. + + The component should return from this call within 20 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [in] nPortIndex + nPortIndex is used to select the port on the component the buffer will + be used with. + @param [in] pBuffer + pointer to an OMX_BUFFERHEADERTYPE structure allocated with UseBuffer + or AllocateBuffer. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp buf + */ +#define OMX_FreeBuffer( \ + hComponent, \ + nPortIndex, \ + pBuffer) \ + ((OMX_COMPONENTTYPE*)hComponent)->FreeBuffer( \ + hComponent, \ + nPortIndex, \ + pBuffer) /* Macro End */ + + +/** The OMX_EmptyThisBuffer macro will send a buffer full of data to an + input port of a component. The buffer will be emptied by the component + and returned to the application via the EmptyBufferDone call back. + This is a non-blocking call in that the component will record the buffer + and return immediately and then empty the buffer, later, at the proper + time. As expected, this macro may be invoked only while the component + is in the OMX_StateExecuting. If nPortIndex does not specify an input + port, the component shall return an error. + + The component should return from this call within 5 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [in] pBuffer + pointer to an OMX_BUFFERHEADERTYPE structure allocated with UseBuffer + or AllocateBuffer. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp buf + */ +#define OMX_EmptyThisBuffer( \ + hComponent, \ + pBuffer) \ + ((OMX_COMPONENTTYPE*)hComponent)->EmptyThisBuffer( \ + hComponent, \ + pBuffer) /* Macro End */ + + +/** The OMX_FillThisBuffer macro will send an empty buffer to an + output port of a component. The buffer will be filled by the component + and returned to the application via the FillBufferDone call back. + This is a non-blocking call in that the component will record the buffer + and return immediately and then fill the buffer, later, at the proper + time. As expected, this macro may be invoked only while the component + is in the OMX_ExecutingState. If nPortIndex does not specify an output + port, the component shall return an error. + + The component should return from this call within 5 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [in] pBuffer + pointer to an OMX_BUFFERHEADERTYPE structure allocated with UseBuffer + or AllocateBuffer. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp buf + */ +#define OMX_FillThisBuffer( \ + hComponent, \ + pBuffer) \ + ((OMX_COMPONENTTYPE*)hComponent)->FillThisBuffer( \ + hComponent, \ + pBuffer) /* Macro End */ + + + +/** The OMX_UseEGLImage macro will request that the component use + a EGLImage provided by EGL (and allocate its own buffer header) + This is a blocking call. + + The component should return from this call within 20 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [out] ppBuffer + pointer to an OMX_BUFFERHEADERTYPE structure used to receive the + pointer to the buffer header. Note that the memory location used + for this buffer is NOT visible to the IL Client. + @param [in] nPortIndex + nPortIndex is used to select the port on the component the buffer will + be used with. The port can be found by using the nPortIndex + value as an index into the Port Definition array of the component. + @param [in] pAppPrivate + pAppPrivate is used to initialize the pAppPrivate member of the + buffer header structure. + @param [in] eglImage + eglImage contains the handle of the EGLImage to use as a buffer on the + specified port. The component is expected to validate properties of + the EGLImage against the configuration of the port to ensure the component + can use the EGLImage as a buffer. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp buf + */ +#define OMX_UseEGLImage( \ + hComponent, \ + ppBufferHdr, \ + nPortIndex, \ + pAppPrivate, \ + eglImage) \ + ((OMX_COMPONENTTYPE*)hComponent)->UseEGLImage( \ + hComponent, \ + ppBufferHdr, \ + nPortIndex, \ + pAppPrivate, \ + eglImage) + +/** The OMX_Init method is used to initialize the OMX core. It shall be the + first call made into OMX and it should only be executed one time without + an interviening OMX_Deinit call. + + The core should return from this call within 20 msec. + + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup core + */ +OMX_API OMX_ERRORTYPE OMX_APIENTRY OMX_Init(void); + + +/** The OMX_Deinit method is used to deinitialize the OMX core. It shall be + the last call made into OMX. In the event that the core determines that + thare are components loaded when this call is made, the core may return + with an error rather than try to unload the components. + + The core should return from this call within 20 msec. + + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup core + */ +OMX_API OMX_ERRORTYPE OMX_APIENTRY OMX_Deinit(void); + + +/** The OMX_ComponentNameEnum method will enumerate through all the names of + recognised valid components in the system. This function is provided + as a means to detect all the components in the system run-time. There is + no strict ordering to the enumeration order of component names, although + each name will only be enumerated once. If the OMX core supports run-time + installation of new components, it is only requried to detect newly + installed components when the first call to enumerate component names + is made (i.e. when nIndex is 0x0). + + The core should return from this call in 20 msec. + + @param [out] cComponentName + pointer to a null terminated string with the component name. The + names of the components are strings less than 127 bytes in length + plus the trailing null for a maximum size of 128 bytes. An example + of a valid component name is "OMX.TI.AUDIO.DSP.MIXER\0". Names are + assigned by the vendor, but shall start with "OMX." and then have + the Vendor designation next. + @param [in] nNameLength + number of characters in the cComponentName string. With all + component name strings restricted to less than 128 characters + (including the trailing null) it is recomended that the caller + provide a input string for the cComponentName of 128 characters. + @param [in] nIndex + number containing the enumeration index for the component. + Multiple calls to OMX_ComponentNameEnum with increasing values + of nIndex will enumerate through the component names in the + system until OMX_ErrorNoMore is returned. The value of nIndex + is 0 to (N-1), where N is the number of valid installed components + in the system. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. When the value of nIndex exceeds the number of + components in the system minus 1, OMX_ErrorNoMore will be + returned. Otherwise the appropriate OMX error will be returned. + @ingroup core + */ +OMX_API OMX_ERRORTYPE OMX_APIENTRY OMX_ComponentNameEnum( + OMX_OUT OMX_STRING cComponentName, + OMX_IN OMX_U32 nNameLength, + OMX_IN OMX_U32 nIndex); + + +/** The OMX_GetHandle method will locate the component specified by the + component name given, load that component into memory and then invoke + the component's methods to create an instance of the component. + + The core should return from this call within 20 msec. + + @param [out] pHandle + pointer to an OMX_HANDLETYPE pointer to be filled in by this method. + @param [in] cComponentName + pointer to a null terminated string with the component name. The + names of the components are strings less than 127 bytes in length + plus the trailing null for a maximum size of 128 bytes. An example + of a valid component name is "OMX.TI.AUDIO.DSP.MIXER\0". Names are + assigned by the vendor, but shall start with "OMX." and then have + the Vendor designation next. + @param [in] pAppData + pointer to an application defined value that will be returned + during callbacks so that the application can identify the source + of the callback. + @param [in] pCallBacks + pointer to a OMX_CALLBACKTYPE structure that will be passed to the + component to initialize it with. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup core + */ +OMX_API OMX_ERRORTYPE OMX_APIENTRY OMX_GetHandle( + OMX_OUT OMX_HANDLETYPE* pHandle, + OMX_IN OMX_STRING cComponentName, + OMX_IN OMX_PTR pAppData, + OMX_IN OMX_CALLBACKTYPE* pCallBacks); + + +/** The OMX_FreeHandle method will free a handle allocated by the OMX_GetHandle + method. If the component reference count goes to zero, the component will + be unloaded from memory. + + The core should return from this call within 20 msec when the component is + in the OMX_StateLoaded state. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the GetHandle function. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup core + */ +OMX_API OMX_ERRORTYPE OMX_APIENTRY OMX_FreeHandle( + OMX_IN OMX_HANDLETYPE hComponent); + + + +/** The OMX_SetupTunnel method will handle the necessary calls to the components + to setup the specified tunnel the two components. NOTE: This is + an actual method (not a #define macro). This method will make calls into + the component ComponentTunnelRequest method to do the actual tunnel + connection. + + The ComponentTunnelRequest method on both components will be called. + This method shall not be called unless the component is in the + OMX_StateLoaded state except when the ports used for the tunnel are + disabled. In this case, the component may be in the OMX_StateExecuting, + OMX_StatePause, or OMX_StateIdle states. + + The core should return from this call within 20 msec. + + @param [in] hOutput + Handle of the component to be accessed. Also this is the handle + of the component whose port, specified in the nPortOutput parameter + will be used the source for the tunnel. This is the component handle + returned by the call to the OMX_GetHandle function. There is a + requirement that hOutput be the source for the data when + tunelling (i.e. nPortOutput is an output port). If 0x0, the component + specified in hInput will have it's port specified in nPortInput + setup for communication with the application / IL client. + @param [in] nPortOutput + nPortOutput is used to select the source port on component to be + used in the tunnel. + @param [in] hInput + This is the component to setup the tunnel with. This is the handle + of the component whose port, specified in the nPortInput parameter + will be used the destination for the tunnel. This is the component handle + returned by the call to the OMX_GetHandle function. There is a + requirement that hInput be the destination for the data when + tunelling (i.e. nPortInut is an input port). If 0x0, the component + specified in hOutput will have it's port specified in nPortPOutput + setup for communication with the application / IL client. + @param [in] nPortInput + nPortInput is used to select the destination port on component to be + used in the tunnel. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + When OMX_ErrorNotImplemented is returned, one or both components is + a non-interop component and does not support tunneling. + + On failure, the ports of both components are setup for communication + with the application / IL Client. + @ingroup core tun + */ +OMX_API OMX_ERRORTYPE OMX_APIENTRY OMX_SetupTunnel( + OMX_IN OMX_HANDLETYPE hOutput, + OMX_IN OMX_U32 nPortOutput, + OMX_IN OMX_HANDLETYPE hInput, + OMX_IN OMX_U32 nPortInput); + +/** @ingroup cp */ +OMX_API OMX_ERRORTYPE OMX_GetContentPipe( + OMX_OUT OMX_HANDLETYPE *hPipe, + OMX_IN OMX_STRING szURI); + +/** The OMX_GetComponentsOfRole method will return the number of components that support the given + role and (if the compNames field is non-NULL) the names of those components. The call will fail if + an insufficiently sized array of names is supplied. To ensure the array is sufficiently sized the + client should: + * first call this function with the compNames field NULL to determine the number of component names + * second call this function with the compNames field pointing to an array of names allocated + according to the number returned by the first call. + + The core should return from this call within 5 msec. + + @param [in] role + This is generic standard component name consisting only of component class + name and the type within that class (e.g. 'audio_decoder.aac'). + @param [inout] pNumComps + This is used both as input and output. + + If compNames is NULL, the input is ignored and the output specifies how many components support + the given role. + + If compNames is not NULL, on input it bounds the size of the input structure and + on output, it specifies the number of components string names listed within the compNames parameter. + @param [inout] compNames + If NULL this field is ignored. If non-NULL this points to an array of 128-byte strings which accepts + a list of the names of all physical components that implement the specified standard component name. + Each name is NULL terminated. numComps indicates the number of names. + @ingroup core + */ +OMX_API OMX_ERRORTYPE OMX_GetComponentsOfRole ( + OMX_IN OMX_STRING role, + OMX_INOUT OMX_U32 *pNumComps, + OMX_INOUT OMX_U8 **compNames); + +/** The OMX_GetRolesOfComponent method will return the number of roles supported by the given + component and (if the roles field is non-NULL) the names of those roles. The call will fail if + an insufficiently sized array of names is supplied. To ensure the array is sufficiently sized the + client should: + * first call this function with the roles field NULL to determine the number of role names + * second call this function with the roles field pointing to an array of names allocated + according to the number returned by the first call. + + The core should return from this call within 5 msec. + + @param [in] compName + This is the name of the component being queried about. + @param [inout] pNumRoles + This is used both as input and output. + + If roles is NULL, the input is ignored and the output specifies how many roles the component supports. + + If compNames is not NULL, on input it bounds the size of the input structure and + on output, it specifies the number of roles string names listed within the roles parameter. + @param [out] roles + If NULL this field is ignored. If non-NULL this points to an array of 128-byte strings + which accepts a list of the names of all standard components roles implemented on the + specified component name. numComps indicates the number of names. + @ingroup core + */ +OMX_API OMX_ERRORTYPE OMX_GetRolesOfComponent ( + OMX_IN OMX_STRING compName, + OMX_INOUT OMX_U32 *pNumRoles, + OMX_OUT OMX_U8 **roles); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif +/* File EOF */ + diff --git a/phonelibs/android_frameworks_native/include/media/openmax/OMX_IVCommon.h b/phonelibs/android_frameworks_native/include/media/openmax/OMX_IVCommon.h new file mode 100644 index 0000000000..f9b6f4b0fd --- /dev/null +++ b/phonelibs/android_frameworks_native/include/media/openmax/OMX_IVCommon.h @@ -0,0 +1,958 @@ +/* ------------------------------------------------------------------ + * Copyright (C) 1998-2009 PacketVideo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. + * See the License for the specific language governing permissions + * and limitations under the License. + * ------------------------------------------------------------------- + */ +/** + * Copyright (c) 2008 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** + * @file OMX_IVCommon.h - OpenMax IL version 1.1.2 + * The structures needed by Video and Image components to exchange + * parameters and configuration data with the components. + */ +#ifndef OMX_IVCommon_h +#define OMX_IVCommon_h + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * Each OMX header must include all required header files to allow the header + * to compile without errors. The includes below are required for this header + * file to compile successfully + */ + +#include + +/** @defgroup iv OpenMAX IL Imaging and Video Domain + * Common structures for OpenMAX IL Imaging and Video domains + * @{ + */ + + +/** + * Enumeration defining possible uncompressed image/video formats. + * + * ENUMS: + * Unused : Placeholder value when format is N/A + * Monochrome : black and white + * 8bitRGB332 : Red 7:5, Green 4:2, Blue 1:0 + * 12bitRGB444 : Red 11:8, Green 7:4, Blue 3:0 + * 16bitARGB4444 : Alpha 15:12, Red 11:8, Green 7:4, Blue 3:0 + * 16bitARGB1555 : Alpha 15, Red 14:10, Green 9:5, Blue 4:0 + * 16bitRGB565 : Red 15:11, Green 10:5, Blue 4:0 + * 16bitBGR565 : Blue 15:11, Green 10:5, Red 4:0 + * 18bitRGB666 : Red 17:12, Green 11:6, Blue 5:0 + * 18bitARGB1665 : Alpha 17, Red 16:11, Green 10:5, Blue 4:0 + * 19bitARGB1666 : Alpha 18, Red 17:12, Green 11:6, Blue 5:0 + * 24bitRGB888 : Red 24:16, Green 15:8, Blue 7:0 + * 24bitBGR888 : Blue 24:16, Green 15:8, Red 7:0 + * 24bitARGB1887 : Alpha 23, Red 22:15, Green 14:7, Blue 6:0 + * 25bitARGB1888 : Alpha 24, Red 23:16, Green 15:8, Blue 7:0 + * 32bitBGRA8888 : Blue 31:24, Green 23:16, Red 15:8, Alpha 7:0 + * 32bitARGB8888 : Alpha 31:24, Red 23:16, Green 15:8, Blue 7:0 + * YUV411Planar : U,Y are subsampled by a factor of 4 horizontally + * YUV411PackedPlanar : packed per payload in planar slices + * YUV420Planar : Three arrays Y,U,V. + * YUV420PackedPlanar : packed per payload in planar slices + * YUV420SemiPlanar : Two arrays, one is all Y, the other is U and V + * YUV422Planar : Three arrays Y,U,V. + * YUV422PackedPlanar : packed per payload in planar slices + * YUV422SemiPlanar : Two arrays, one is all Y, the other is U and V + * YCbYCr : Organized as 16bit YUYV (i.e. YCbYCr) + * YCrYCb : Organized as 16bit YVYU (i.e. YCrYCb) + * CbYCrY : Organized as 16bit UYVY (i.e. CbYCrY) + * CrYCbY : Organized as 16bit VYUY (i.e. CrYCbY) + * YUV444Interleaved : Each pixel contains equal parts YUV + * RawBayer8bit : SMIA camera output format + * RawBayer10bit : SMIA camera output format + * RawBayer8bitcompressed : SMIA camera output format + */ +typedef enum OMX_COLOR_FORMATTYPE { + OMX_COLOR_FormatUnused, + OMX_COLOR_FormatMonochrome, + OMX_COLOR_Format8bitRGB332, + OMX_COLOR_Format12bitRGB444, + OMX_COLOR_Format16bitARGB4444, + OMX_COLOR_Format16bitARGB1555, + OMX_COLOR_Format16bitRGB565, + OMX_COLOR_Format16bitBGR565, + OMX_COLOR_Format18bitRGB666, + OMX_COLOR_Format18bitARGB1665, + OMX_COLOR_Format19bitARGB1666, + OMX_COLOR_Format24bitRGB888, + OMX_COLOR_Format24bitBGR888, + OMX_COLOR_Format24bitARGB1887, + OMX_COLOR_Format25bitARGB1888, + OMX_COLOR_Format32bitBGRA8888, + OMX_COLOR_Format32bitARGB8888, + OMX_COLOR_FormatYUV411Planar, + OMX_COLOR_FormatYUV411PackedPlanar, + OMX_COLOR_FormatYUV420Planar, + OMX_COLOR_FormatYUV420PackedPlanar, + OMX_COLOR_FormatYUV420SemiPlanar, + OMX_COLOR_FormatYUV422Planar, + OMX_COLOR_FormatYUV422PackedPlanar, + OMX_COLOR_FormatYUV422SemiPlanar, + OMX_COLOR_FormatYCbYCr, + OMX_COLOR_FormatYCrYCb, + OMX_COLOR_FormatCbYCrY, + OMX_COLOR_FormatCrYCbY, + OMX_COLOR_FormatYUV444Interleaved, + OMX_COLOR_FormatRawBayer8bit, + OMX_COLOR_FormatRawBayer10bit, + OMX_COLOR_FormatRawBayer8bitcompressed, + OMX_COLOR_FormatL2, + OMX_COLOR_FormatL4, + OMX_COLOR_FormatL8, + OMX_COLOR_FormatL16, + OMX_COLOR_FormatL24, + OMX_COLOR_FormatL32, + OMX_COLOR_FormatYUV420PackedSemiPlanar, + OMX_COLOR_FormatYUV422PackedSemiPlanar, + OMX_COLOR_Format18BitBGR666, + OMX_COLOR_Format24BitARGB6666, + OMX_COLOR_Format24BitABGR6666, + OMX_COLOR_FormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_COLOR_FormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + /** + +/** @defgroup imaging OpenMAX IL Imaging Domain + * @ingroup iv + * Structures for OpenMAX IL Imaging domain + * @{ + */ + +/** + * Enumeration used to define the possible image compression coding. + */ +typedef enum OMX_IMAGE_CODINGTYPE { + OMX_IMAGE_CodingUnused, /**< Value when format is N/A */ + OMX_IMAGE_CodingAutoDetect, /**< Auto detection of image format */ + OMX_IMAGE_CodingJPEG, /**< JPEG/JFIF image format */ + OMX_IMAGE_CodingJPEG2K, /**< JPEG 2000 image format */ + OMX_IMAGE_CodingEXIF, /**< EXIF image format */ + OMX_IMAGE_CodingTIFF, /**< TIFF image format */ + OMX_IMAGE_CodingGIF, /**< Graphics image format */ + OMX_IMAGE_CodingPNG, /**< PNG image format */ + OMX_IMAGE_CodingLZW, /**< LZW image format */ + OMX_IMAGE_CodingBMP, /**< Windows Bitmap format */ + OMX_IMAGE_CodingKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_IMAGE_CodingVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_IMAGE_CodingMax = 0x7FFFFFFF +} OMX_IMAGE_CODINGTYPE; + + +/** + * Data structure used to define an image path. The number of image paths + * for input and output will vary by type of the image component. + * + * Input (aka Source) : Zero Inputs, one Output, + * Splitter : One Input, 2 or more Outputs, + * Processing Element : One Input, one output, + * Mixer : 2 or more inputs, one output, + * Output (aka Sink) : One Input, zero outputs. + * + * The PortDefinition structure is used to define all of the parameters + * necessary for the compliant component to setup an input or an output + * image path. If additional vendor specific data is required, it should + * be transmitted to the component using the CustomCommand function. + * Compliant components will prepopulate this structure with optimal + * values during the OMX_GetParameter() command. + * + * STRUCT MEMBERS: + * cMIMEType : MIME type of data for the port + * pNativeRender : Platform specific reference for a display if a + * sync, otherwise this field is 0 + * nFrameWidth : Width of frame to be used on port if + * uncompressed format is used. Use 0 for + * unknown, don't care or variable + * nFrameHeight : Height of frame to be used on port if + * uncompressed format is used. Use 0 for + * unknown, don't care or variable + * nStride : Number of bytes per span of an image (i.e. + * indicates the number of bytes to get from + * span N to span N+1, where negative stride + * indicates the image is bottom up + * nSliceHeight : Height used when encoding in slices + * bFlagErrorConcealment : Turns on error concealment if it is supported by + * the OMX component + * eCompressionFormat : Compression format used in this instance of + * the component. When OMX_IMAGE_CodingUnused is + * specified, eColorFormat is valid + * eColorFormat : Decompressed format used by this component + * pNativeWindow : Platform specific reference for a window object if a + * display sink , otherwise this field is 0x0. + */ +typedef struct OMX_IMAGE_PORTDEFINITIONTYPE { + OMX_STRING cMIMEType; + OMX_NATIVE_DEVICETYPE pNativeRender; + OMX_U32 nFrameWidth; + OMX_U32 nFrameHeight; + OMX_S32 nStride; + OMX_U32 nSliceHeight; + OMX_BOOL bFlagErrorConcealment; + OMX_IMAGE_CODINGTYPE eCompressionFormat; + OMX_COLOR_FORMATTYPE eColorFormat; + OMX_NATIVE_WINDOWTYPE pNativeWindow; +} OMX_IMAGE_PORTDEFINITIONTYPE; + + +/** + * Port format parameter. This structure is used to enumerate the various + * data input/output format supported by the port. + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Indicates which port to set + * nIndex : Indicates the enumeration index for the format from + * 0x0 to N-1 + * eCompressionFormat : Compression format used in this instance of the + * component. When OMX_IMAGE_CodingUnused is specified, + * eColorFormat is valid + * eColorFormat : Decompressed format used by this component + */ +typedef struct OMX_IMAGE_PARAM_PORTFORMATTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nIndex; + OMX_IMAGE_CODINGTYPE eCompressionFormat; + OMX_COLOR_FORMATTYPE eColorFormat; +} OMX_IMAGE_PARAM_PORTFORMATTYPE; + + +/** + * Flash control type + * + * ENUMS + * Torch : Flash forced constantly on + */ +typedef enum OMX_IMAGE_FLASHCONTROLTYPE { + OMX_IMAGE_FlashControlOn = 0, + OMX_IMAGE_FlashControlOff, + OMX_IMAGE_FlashControlAuto, + OMX_IMAGE_FlashControlRedEyeReduction, + OMX_IMAGE_FlashControlFillin, + OMX_IMAGE_FlashControlTorch, + OMX_IMAGE_FlashControlKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_IMAGE_FlashControlVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_IMAGE_FlashControlMax = 0x7FFFFFFF +} OMX_IMAGE_FLASHCONTROLTYPE; + + +/** + * Flash control configuration + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * eFlashControl : Flash control type + */ +typedef struct OMX_IMAGE_PARAM_FLASHCONTROLTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_IMAGE_FLASHCONTROLTYPE eFlashControl; +} OMX_IMAGE_PARAM_FLASHCONTROLTYPE; + + +/** + * Focus control type + */ +typedef enum OMX_IMAGE_FOCUSCONTROLTYPE { + OMX_IMAGE_FocusControlOn = 0, + OMX_IMAGE_FocusControlOff, + OMX_IMAGE_FocusControlAuto, + OMX_IMAGE_FocusControlAutoLock, + OMX_IMAGE_FocusControlKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_IMAGE_FocusControlVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_IMAGE_FocusControlMax = 0x7FFFFFFF +} OMX_IMAGE_FOCUSCONTROLTYPE; + + +/** + * Focus control configuration + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * eFocusControl : Focus control + * nFocusSteps : Focus can take on values from 0 mm to infinity. + * Interest is only in number of steps over this range. + * nFocusStepIndex : Current focus step index + */ +typedef struct OMX_IMAGE_CONFIG_FOCUSCONTROLTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_IMAGE_FOCUSCONTROLTYPE eFocusControl; + OMX_U32 nFocusSteps; + OMX_U32 nFocusStepIndex; +} OMX_IMAGE_CONFIG_FOCUSCONTROLTYPE; + + +/** + * Q Factor for JPEG compression, which controls the tradeoff between image + * quality and size. Q Factor provides a more simple means of controlling + * JPEG compression quality, without directly programming Quantization + * tables for chroma and luma + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * nQFactor : JPEG Q factor value in the range of 1-100. A factor of 1 + * produces the smallest, worst quality images, and a factor + * of 100 produces the largest, best quality images. A + * typical default is 75 for small good quality images + */ +typedef struct OMX_IMAGE_PARAM_QFACTORTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nQFactor; +} OMX_IMAGE_PARAM_QFACTORTYPE; + +/** + * Quantization table type + */ + +typedef enum OMX_IMAGE_QUANTIZATIONTABLETYPE { + OMX_IMAGE_QuantizationTableLuma = 0, + OMX_IMAGE_QuantizationTableChroma, + OMX_IMAGE_QuantizationTableChromaCb, + OMX_IMAGE_QuantizationTableChromaCr, + OMX_IMAGE_QuantizationTableKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_IMAGE_QuantizationTableVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_IMAGE_QuantizationTableMax = 0x7FFFFFFF +} OMX_IMAGE_QUANTIZATIONTABLETYPE; + +/** + * JPEG quantization tables are used to determine DCT compression for + * YUV data, as an alternative to specifying Q factor, providing exact + * control of compression + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * eQuantizationTable : Quantization table type + * nQuantizationMatrix[64] : JPEG quantization table of coefficients stored + * in increasing columns then by rows of data (i.e. + * row 1, ... row 8). Quantization values are in + * the range 0-255 and stored in linear order + * (i.e. the component will zig-zag the + * quantization table data if required internally) + */ +typedef struct OMX_IMAGE_PARAM_QUANTIZATIONTABLETYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_IMAGE_QUANTIZATIONTABLETYPE eQuantizationTable; + OMX_U8 nQuantizationMatrix[64]; +} OMX_IMAGE_PARAM_QUANTIZATIONTABLETYPE; + + +/** + * Huffman table type, the same Huffman table is applied for chroma and + * luma component + */ +typedef enum OMX_IMAGE_HUFFMANTABLETYPE { + OMX_IMAGE_HuffmanTableAC = 0, + OMX_IMAGE_HuffmanTableDC, + OMX_IMAGE_HuffmanTableACLuma, + OMX_IMAGE_HuffmanTableACChroma, + OMX_IMAGE_HuffmanTableDCLuma, + OMX_IMAGE_HuffmanTableDCChroma, + OMX_IMAGE_HuffmanTableKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_IMAGE_HuffmanTableVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_IMAGE_HuffmanTableMax = 0x7FFFFFFF +} OMX_IMAGE_HUFFMANTABLETYPE; + +/** + * JPEG Huffman table + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * eHuffmanTable : Huffman table type + * nNumberOfHuffmanCodeOfLength[16] : 0-16, number of Huffman codes of each + * possible length + * nHuffmanTable[256] : 0-255, the size used for AC and DC + * HuffmanTable are 16 and 162 + */ +typedef struct OMX_IMAGE_PARAM_HUFFMANTTABLETYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_IMAGE_HUFFMANTABLETYPE eHuffmanTable; + OMX_U8 nNumberOfHuffmanCodeOfLength[16]; + OMX_U8 nHuffmanTable[256]; +}OMX_IMAGE_PARAM_HUFFMANTTABLETYPE; + +/** @} */ +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif +/* File EOF */ diff --git a/phonelibs/android_frameworks_native/include/media/openmax/OMX_Index.h b/phonelibs/android_frameworks_native/include/media/openmax/OMX_Index.h new file mode 100644 index 0000000000..1a2a548e88 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/media/openmax/OMX_Index.h @@ -0,0 +1,274 @@ +/* ------------------------------------------------------------------ + * Copyright (C) 1998-2009 PacketVideo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. + * See the License for the specific language governing permissions + * and limitations under the License. + * ------------------------------------------------------------------- + */ +/* + * Copyright (c) 2008 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** @file OMX_Index.h - OpenMax IL version 1.1.2 + * The OMX_Index header file contains the definitions for both applications + * and components . + */ + + +#ifndef OMX_Index_h +#define OMX_Index_h + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* Each OMX header must include all required header files to allow the + * header to compile without errors. The includes below are required + * for this header file to compile successfully + */ +#include + +/** The OMX_INDEXTYPE enumeration is used to select a structure when either + * getting or setting parameters and/or configuration data. Each entry in + * this enumeration maps to an OMX specified structure. When the + * OMX_GetParameter, OMX_SetParameter, OMX_GetConfig or OMX_SetConfig methods + * are used, the second parameter will always be an entry from this enumeration + * and the third entry will be the structure shown in the comments for the entry. + * For example, if the application is initializing a cropping function, the + * OMX_SetConfig command would have OMX_IndexConfigCommonInputCrop as the second parameter + * and would send a pointer to an initialized OMX_RECTTYPE structure as the + * third parameter. + * + * The enumeration entries named with the OMX_Config prefix are sent using + * the OMX_SetConfig command and the enumeration entries named with the + * OMX_PARAM_ prefix are sent using the OMX_SetParameter command. + */ +typedef enum OMX_INDEXTYPE { + + OMX_IndexComponentStartUnused = 0x01000000, + OMX_IndexParamPriorityMgmt, /**< reference: OMX_PRIORITYMGMTTYPE */ + OMX_IndexParamAudioInit, /**< reference: OMX_PORT_PARAM_TYPE */ + OMX_IndexParamImageInit, /**< reference: OMX_PORT_PARAM_TYPE */ + OMX_IndexParamVideoInit, /**< reference: OMX_PORT_PARAM_TYPE */ + OMX_IndexParamOtherInit, /**< reference: OMX_PORT_PARAM_TYPE */ + OMX_IndexParamNumAvailableStreams, /**< reference: OMX_PARAM_U32TYPE */ + OMX_IndexParamActiveStream, /**< reference: OMX_PARAM_U32TYPE */ + OMX_IndexParamSuspensionPolicy, /**< reference: OMX_PARAM_SUSPENSIONPOLICYTYPE */ + OMX_IndexParamComponentSuspended, /**< reference: OMX_PARAM_SUSPENSIONTYPE */ + OMX_IndexConfigCapturing, /**< reference: OMX_CONFIG_BOOLEANTYPE */ + OMX_IndexConfigCaptureMode, /**< reference: OMX_CONFIG_CAPTUREMODETYPE */ + OMX_IndexAutoPauseAfterCapture, /**< reference: OMX_CONFIG_BOOLEANTYPE */ + OMX_IndexParamContentURI, /**< reference: OMX_PARAM_CONTENTURITYPE */ + OMX_IndexParamCustomContentPipe, /**< reference: OMX_PARAM_CONTENTPIPETYPE */ + OMX_IndexParamDisableResourceConcealment, /**< reference: OMX_RESOURCECONCEALMENTTYPE */ + OMX_IndexConfigMetadataItemCount, /**< reference: OMX_CONFIG_METADATAITEMCOUNTTYPE */ + OMX_IndexConfigContainerNodeCount, /**< reference: OMX_CONFIG_CONTAINERNODECOUNTTYPE */ + OMX_IndexConfigMetadataItem, /**< reference: OMX_CONFIG_METADATAITEMTYPE */ + OMX_IndexConfigCounterNodeID, /**< reference: OMX_CONFIG_CONTAINERNODEIDTYPE */ + OMX_IndexParamMetadataFilterType, /**< reference: OMX_PARAM_METADATAFILTERTYPE */ + OMX_IndexParamMetadataKeyFilter, /**< reference: OMX_PARAM_METADATAFILTERTYPE */ + OMX_IndexConfigPriorityMgmt, /**< reference: OMX_PRIORITYMGMTTYPE */ + OMX_IndexParamStandardComponentRole, /**< reference: OMX_PARAM_COMPONENTROLETYPE */ + + OMX_IndexPortStartUnused = 0x02000000, + OMX_IndexParamPortDefinition, /**< reference: OMX_PARAM_PORTDEFINITIONTYPE */ + OMX_IndexParamCompBufferSupplier, /**< reference: OMX_PARAM_BUFFERSUPPLIERTYPE */ + OMX_IndexReservedStartUnused = 0x03000000, + + /* Audio parameters and configurations */ + OMX_IndexAudioStartUnused = 0x04000000, + OMX_IndexParamAudioPortFormat, /**< reference: OMX_AUDIO_PARAM_PORTFORMATTYPE */ + OMX_IndexParamAudioPcm, /**< reference: OMX_AUDIO_PARAM_PCMMODETYPE */ + OMX_IndexParamAudioAac, /**< reference: OMX_AUDIO_PARAM_AACPROFILETYPE */ + OMX_IndexParamAudioRa, /**< reference: OMX_AUDIO_PARAM_RATYPE */ + OMX_IndexParamAudioMp3, /**< reference: OMX_AUDIO_PARAM_MP3TYPE */ + OMX_IndexParamAudioAdpcm, /**< reference: OMX_AUDIO_PARAM_ADPCMTYPE */ + OMX_IndexParamAudioG723, /**< reference: OMX_AUDIO_PARAM_G723TYPE */ + OMX_IndexParamAudioG729, /**< reference: OMX_AUDIO_PARAM_G729TYPE */ + OMX_IndexParamAudioAmr, /**< reference: OMX_AUDIO_PARAM_AMRTYPE */ + OMX_IndexParamAudioWma, /**< reference: OMX_AUDIO_PARAM_WMATYPE */ + OMX_IndexParamAudioSbc, /**< reference: OMX_AUDIO_PARAM_SBCTYPE */ + OMX_IndexParamAudioMidi, /**< reference: OMX_AUDIO_PARAM_MIDITYPE */ + OMX_IndexParamAudioGsm_FR, /**< reference: OMX_AUDIO_PARAM_GSMFRTYPE */ + OMX_IndexParamAudioMidiLoadUserSound, /**< reference: OMX_AUDIO_PARAM_MIDILOADUSERSOUNDTYPE */ + OMX_IndexParamAudioG726, /**< reference: OMX_AUDIO_PARAM_G726TYPE */ + OMX_IndexParamAudioGsm_EFR, /**< reference: OMX_AUDIO_PARAM_GSMEFRTYPE */ + OMX_IndexParamAudioGsm_HR, /**< reference: OMX_AUDIO_PARAM_GSMHRTYPE */ + OMX_IndexParamAudioPdc_FR, /**< reference: OMX_AUDIO_PARAM_PDCFRTYPE */ + OMX_IndexParamAudioPdc_EFR, /**< reference: OMX_AUDIO_PARAM_PDCEFRTYPE */ + OMX_IndexParamAudioPdc_HR, /**< reference: OMX_AUDIO_PARAM_PDCHRTYPE */ + OMX_IndexParamAudioTdma_FR, /**< reference: OMX_AUDIO_PARAM_TDMAFRTYPE */ + OMX_IndexParamAudioTdma_EFR, /**< reference: OMX_AUDIO_PARAM_TDMAEFRTYPE */ + OMX_IndexParamAudioQcelp8, /**< reference: OMX_AUDIO_PARAM_QCELP8TYPE */ + OMX_IndexParamAudioQcelp13, /**< reference: OMX_AUDIO_PARAM_QCELP13TYPE */ + OMX_IndexParamAudioEvrc, /**< reference: OMX_AUDIO_PARAM_EVRCTYPE */ + OMX_IndexParamAudioSmv, /**< reference: OMX_AUDIO_PARAM_SMVTYPE */ + OMX_IndexParamAudioVorbis, /**< reference: OMX_AUDIO_PARAM_VORBISTYPE */ + OMX_IndexParamAudioFlac, /**< reference: OMX_AUDIO_PARAM_FLACTYPE */ + + OMX_IndexConfigAudioMidiImmediateEvent, /**< reference: OMX_AUDIO_CONFIG_MIDIIMMEDIATEEVENTTYPE */ + OMX_IndexConfigAudioMidiControl, /**< reference: OMX_AUDIO_CONFIG_MIDICONTROLTYPE */ + OMX_IndexConfigAudioMidiSoundBankProgram, /**< reference: OMX_AUDIO_CONFIG_MIDISOUNDBANKPROGRAMTYPE */ + OMX_IndexConfigAudioMidiStatus, /**< reference: OMX_AUDIO_CONFIG_MIDISTATUSTYPE */ + OMX_IndexConfigAudioMidiMetaEvent, /**< reference: OMX_AUDIO_CONFIG_MIDIMETAEVENTTYPE */ + OMX_IndexConfigAudioMidiMetaEventData, /**< reference: OMX_AUDIO_CONFIG_MIDIMETAEVENTDATATYPE */ + OMX_IndexConfigAudioVolume, /**< reference: OMX_AUDIO_CONFIG_VOLUMETYPE */ + OMX_IndexConfigAudioBalance, /**< reference: OMX_AUDIO_CONFIG_BALANCETYPE */ + OMX_IndexConfigAudioChannelMute, /**< reference: OMX_AUDIO_CONFIG_CHANNELMUTETYPE */ + OMX_IndexConfigAudioMute, /**< reference: OMX_AUDIO_CONFIG_MUTETYPE */ + OMX_IndexConfigAudioLoudness, /**< reference: OMX_AUDIO_CONFIG_LOUDNESSTYPE */ + OMX_IndexConfigAudioEchoCancelation, /**< reference: OMX_AUDIO_CONFIG_ECHOCANCELATIONTYPE */ + OMX_IndexConfigAudioNoiseReduction, /**< reference: OMX_AUDIO_CONFIG_NOISEREDUCTIONTYPE */ + OMX_IndexConfigAudioBass, /**< reference: OMX_AUDIO_CONFIG_BASSTYPE */ + OMX_IndexConfigAudioTreble, /**< reference: OMX_AUDIO_CONFIG_TREBLETYPE */ + OMX_IndexConfigAudioStereoWidening, /**< reference: OMX_AUDIO_CONFIG_STEREOWIDENINGTYPE */ + OMX_IndexConfigAudioChorus, /**< reference: OMX_AUDIO_CONFIG_CHORUSTYPE */ + OMX_IndexConfigAudioEqualizer, /**< reference: OMX_AUDIO_CONFIG_EQUALIZERTYPE */ + OMX_IndexConfigAudioReverberation, /**< reference: OMX_AUDIO_CONFIG_REVERBERATIONTYPE */ + OMX_IndexConfigAudioChannelVolume, /**< reference: OMX_AUDIO_CONFIG_CHANNELVOLUMETYPE */ + + /* Image specific parameters and configurations */ + OMX_IndexImageStartUnused = 0x05000000, + OMX_IndexParamImagePortFormat, /**< reference: OMX_IMAGE_PARAM_PORTFORMATTYPE */ + OMX_IndexParamFlashControl, /**< reference: OMX_IMAGE_PARAM_FLASHCONTROLTYPE */ + OMX_IndexConfigFocusControl, /**< reference: OMX_IMAGE_CONFIG_FOCUSCONTROLTYPE */ + OMX_IndexParamQFactor, /**< reference: OMX_IMAGE_PARAM_QFACTORTYPE */ + OMX_IndexParamQuantizationTable, /**< reference: OMX_IMAGE_PARAM_QUANTIZATIONTABLETYPE */ + OMX_IndexParamHuffmanTable, /**< reference: OMX_IMAGE_PARAM_HUFFMANTTABLETYPE */ + OMX_IndexConfigFlashControl, /**< reference: OMX_IMAGE_PARAM_FLASHCONTROLTYPE */ + + /* Video specific parameters and configurations */ + OMX_IndexVideoStartUnused = 0x06000000, + OMX_IndexParamVideoPortFormat, /**< reference: OMX_VIDEO_PARAM_PORTFORMATTYPE */ + OMX_IndexParamVideoQuantization, /**< reference: OMX_VIDEO_PARAM_QUANTIZATIONTYPE */ + OMX_IndexParamVideoFastUpdate, /**< reference: OMX_VIDEO_PARAM_VIDEOFASTUPDATETYPE */ + OMX_IndexParamVideoBitrate, /**< reference: OMX_VIDEO_PARAM_BITRATETYPE */ + OMX_IndexParamVideoMotionVector, /**< reference: OMX_VIDEO_PARAM_MOTIONVECTORTYPE */ + OMX_IndexParamVideoIntraRefresh, /**< reference: OMX_VIDEO_PARAM_INTRAREFRESHTYPE */ + OMX_IndexParamVideoErrorCorrection, /**< reference: OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE */ + OMX_IndexParamVideoVBSMC, /**< reference: OMX_VIDEO_PARAM_VBSMCTYPE */ + OMX_IndexParamVideoMpeg2, /**< reference: OMX_VIDEO_PARAM_MPEG2TYPE */ + OMX_IndexParamVideoMpeg4, /**< reference: OMX_VIDEO_PARAM_MPEG4TYPE */ + OMX_IndexParamVideoWmv, /**< reference: OMX_VIDEO_PARAM_WMVTYPE */ + OMX_IndexParamVideoRv, /**< reference: OMX_VIDEO_PARAM_RVTYPE */ + OMX_IndexParamVideoAvc, /**< reference: OMX_VIDEO_PARAM_AVCTYPE */ + OMX_IndexParamVideoH263, /**< reference: OMX_VIDEO_PARAM_H263TYPE */ + OMX_IndexParamVideoProfileLevelQuerySupported, /**< reference: OMX_VIDEO_PARAM_PROFILELEVELTYPE */ + OMX_IndexParamVideoProfileLevelCurrent, /**< reference: OMX_VIDEO_PARAM_PROFILELEVELTYPE */ + OMX_IndexConfigVideoBitrate, /**< reference: OMX_VIDEO_CONFIG_BITRATETYPE */ + OMX_IndexConfigVideoFramerate, /**< reference: OMX_CONFIG_FRAMERATETYPE */ + OMX_IndexConfigVideoIntraVOPRefresh, /**< reference: OMX_CONFIG_INTRAREFRESHVOPTYPE */ + OMX_IndexConfigVideoIntraMBRefresh, /**< reference: OMX_CONFIG_MACROBLOCKERRORMAPTYPE */ + OMX_IndexConfigVideoMBErrorReporting, /**< reference: OMX_CONFIG_MBERRORREPORTINGTYPE */ + OMX_IndexParamVideoMacroblocksPerFrame, /**< reference: OMX_PARAM_MACROBLOCKSTYPE */ + OMX_IndexConfigVideoMacroBlockErrorMap, /**< reference: OMX_CONFIG_MACROBLOCKERRORMAPTYPE */ + OMX_IndexParamVideoSliceFMO, /**< reference: OMX_VIDEO_PARAM_AVCSLICEFMO */ + OMX_IndexConfigVideoAVCIntraPeriod, /**< reference: OMX_VIDEO_CONFIG_AVCINTRAPERIOD */ + OMX_IndexConfigVideoNalSize, /**< reference: OMX_VIDEO_CONFIG_NALSIZE */ + + /* Image & Video common Configurations */ + OMX_IndexCommonStartUnused = 0x07000000, + OMX_IndexParamCommonDeblocking, /**< reference: OMX_PARAM_DEBLOCKINGTYPE */ + OMX_IndexParamCommonSensorMode, /**< reference: OMX_PARAM_SENSORMODETYPE */ + OMX_IndexParamCommonInterleave, /**< reference: OMX_PARAM_INTERLEAVETYPE */ + OMX_IndexConfigCommonColorFormatConversion, /**< reference: OMX_CONFIG_COLORCONVERSIONTYPE */ + OMX_IndexConfigCommonScale, /**< reference: OMX_CONFIG_SCALEFACTORTYPE */ + OMX_IndexConfigCommonImageFilter, /**< reference: OMX_CONFIG_IMAGEFILTERTYPE */ + OMX_IndexConfigCommonColorEnhancement, /**< reference: OMX_CONFIG_COLORENHANCEMENTTYPE */ + OMX_IndexConfigCommonColorKey, /**< reference: OMX_CONFIG_COLORKEYTYPE */ + OMX_IndexConfigCommonColorBlend, /**< reference: OMX_CONFIG_COLORBLENDTYPE */ + OMX_IndexConfigCommonFrameStabilisation,/**< reference: OMX_CONFIG_FRAMESTABTYPE */ + OMX_IndexConfigCommonRotate, /**< reference: OMX_CONFIG_ROTATIONTYPE */ + OMX_IndexConfigCommonMirror, /**< reference: OMX_CONFIG_MIRRORTYPE */ + OMX_IndexConfigCommonOutputPosition, /**< reference: OMX_CONFIG_POINTTYPE */ + OMX_IndexConfigCommonInputCrop, /**< reference: OMX_CONFIG_RECTTYPE */ + OMX_IndexConfigCommonOutputCrop, /**< reference: OMX_CONFIG_RECTTYPE */ + OMX_IndexConfigCommonDigitalZoom, /**< reference: OMX_CONFIG_SCALEFACTORTYPE */ + OMX_IndexConfigCommonOpticalZoom, /**< reference: OMX_CONFIG_SCALEFACTORTYPE*/ + OMX_IndexConfigCommonWhiteBalance, /**< reference: OMX_CONFIG_WHITEBALCONTROLTYPE */ + OMX_IndexConfigCommonExposure, /**< reference: OMX_CONFIG_EXPOSURECONTROLTYPE */ + OMX_IndexConfigCommonContrast, /**< reference: OMX_CONFIG_CONTRASTTYPE */ + OMX_IndexConfigCommonBrightness, /**< reference: OMX_CONFIG_BRIGHTNESSTYPE */ + OMX_IndexConfigCommonBacklight, /**< reference: OMX_CONFIG_BACKLIGHTTYPE */ + OMX_IndexConfigCommonGamma, /**< reference: OMX_CONFIG_GAMMATYPE */ + OMX_IndexConfigCommonSaturation, /**< reference: OMX_CONFIG_SATURATIONTYPE */ + OMX_IndexConfigCommonLightness, /**< reference: OMX_CONFIG_LIGHTNESSTYPE */ + OMX_IndexConfigCommonExclusionRect, /**< reference: OMX_CONFIG_RECTTYPE */ + OMX_IndexConfigCommonDithering, /**< reference: OMX_CONFIG_DITHERTYPE */ + OMX_IndexConfigCommonPlaneBlend, /**< reference: OMX_CONFIG_PLANEBLENDTYPE */ + OMX_IndexConfigCommonExposureValue, /**< reference: OMX_CONFIG_EXPOSUREVALUETYPE */ + OMX_IndexConfigCommonOutputSize, /**< reference: OMX_FRAMESIZETYPE */ + OMX_IndexParamCommonExtraQuantData, /**< reference: OMX_OTHER_EXTRADATATYPE */ + OMX_IndexConfigCommonFocusRegion, /**< reference: OMX_CONFIG_FOCUSREGIONTYPE */ + OMX_IndexConfigCommonFocusStatus, /**< reference: OMX_PARAM_FOCUSSTATUSTYPE */ + OMX_IndexConfigCommonTransitionEffect, /**< reference: OMX_CONFIG_TRANSITIONEFFECTTYPE */ + + /* Reserved Configuration range */ + OMX_IndexOtherStartUnused = 0x08000000, + OMX_IndexParamOtherPortFormat, /**< reference: OMX_OTHER_PARAM_PORTFORMATTYPE */ + OMX_IndexConfigOtherPower, /**< reference: OMX_OTHER_CONFIG_POWERTYPE */ + OMX_IndexConfigOtherStats, /**< reference: OMX_OTHER_CONFIG_STATSTYPE */ + + + /* Reserved Time range */ + OMX_IndexTimeStartUnused = 0x09000000, + OMX_IndexConfigTimeScale, /**< reference: OMX_TIME_CONFIG_SCALETYPE */ + OMX_IndexConfigTimeClockState, /**< reference: OMX_TIME_CONFIG_CLOCKSTATETYPE */ + OMX_IndexConfigTimeActiveRefClock, /**< reference: OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE */ + OMX_IndexConfigTimeCurrentMediaTime, /**< reference: OMX_TIME_CONFIG_TIMESTAMPTYPE (read only) */ + OMX_IndexConfigTimeCurrentWallTime, /**< reference: OMX_TIME_CONFIG_TIMESTAMPTYPE (read only) */ + OMX_IndexConfigTimeCurrentAudioReference, /**< reference: OMX_TIME_CONFIG_TIMESTAMPTYPE (write only) */ + OMX_IndexConfigTimeCurrentVideoReference, /**< reference: OMX_TIME_CONFIG_TIMESTAMPTYPE (write only) */ + OMX_IndexConfigTimeMediaTimeRequest, /**< reference: OMX_TIME_CONFIG_MEDIATIMEREQUESTTYPE (write only) */ + OMX_IndexConfigTimeClientStartTime, /** + + +/** Khronos standard extension indices. + +This enum lists the current Khronos extension indices to OpenMAX IL. +*/ +typedef enum OMX_INDEXEXTTYPE { + + /* Component parameters and configurations */ + OMX_IndexExtComponentStartUnused = OMX_IndexKhronosExtensions + 0x00100000, + OMX_IndexConfigCallbackRequest, /**< reference: OMX_CONFIG_CALLBACKREQUESTTYPE */ + OMX_IndexConfigCommitMode, /**< reference: OMX_CONFIG_COMMITMODETYPE */ + OMX_IndexConfigCommit, /**< reference: OMX_CONFIG_COMMITTYPE */ + + /* Port parameters and configurations */ + OMX_IndexExtPortStartUnused = OMX_IndexKhronosExtensions + 0x00200000, + + /* Audio parameters and configurations */ + OMX_IndexExtAudioStartUnused = OMX_IndexKhronosExtensions + 0x00400000, + OMX_IndexParamAudioAndroidAc3, /**< reference: OMX_AUDIO_PARAM_ANDROID_AC3TYPE */ + OMX_IndexParamAudioAndroidOpus, /**< reference: OMX_AUDIO_PARAM_ANDROID_OPUSTYPE */ + OMX_IndexParamAudioAndroidAacPresentation, /**< reference: OMX_AUDIO_PARAM_ANDROID_AACPRESENTATIONTYPE */ + OMX_IndexParamAudioAndroidEac3, /**< reference: OMX_AUDIO_PARAM_ANDROID_EAC3TYPE */ + + /* Image parameters and configurations */ + OMX_IndexExtImageStartUnused = OMX_IndexKhronosExtensions + 0x00500000, + + /* Video parameters and configurations */ + OMX_IndexExtVideoStartUnused = OMX_IndexKhronosExtensions + 0x00600000, + OMX_IndexParamNalStreamFormatSupported, /**< reference: OMX_NALSTREAMFORMATTYPE */ + OMX_IndexParamNalStreamFormat, /**< reference: OMX_NALSTREAMFORMATTYPE */ + OMX_IndexParamNalStreamFormatSelect, /**< reference: OMX_NALSTREAMFORMATTYPE */ + OMX_IndexParamVideoVp8, /**< reference: OMX_VIDEO_PARAM_VP8TYPE */ + OMX_IndexConfigVideoVp8ReferenceFrame, /**< reference: OMX_VIDEO_VP8REFERENCEFRAMETYPE */ + OMX_IndexConfigVideoVp8ReferenceFrameType, /**< reference: OMX_VIDEO_VP8REFERENCEFRAMEINFOTYPE */ + OMX_IndexParamVideoAndroidVp8Encoder, /**< reference: OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE */ + OMX_IndexParamVideoHevc, /**< reference: OMX_VIDEO_PARAM_HEVCTYPE */ + OMX_IndexParamSliceSegments, /**< reference: OMX_VIDEO_SLICESEGMENTSTYPE */ + + /* Image & Video common configurations */ + OMX_IndexExtCommonStartUnused = OMX_IndexKhronosExtensions + 0x00700000, + + /* Other configurations */ + OMX_IndexExtOtherStartUnused = OMX_IndexKhronosExtensions + 0x00800000, + OMX_IndexConfigAutoFramerateConversion, /**< reference: OMX_CONFIG_BOOLEANTYPE */ + OMX_IndexConfigPriority, /**< reference: OMX_PARAM_U32TYPE */ + OMX_IndexConfigOperatingRate, /**< reference: OMX_PARAM_U32TYPE in Q16 format for video and in Hz for audio */ + OMX_IndexParamConsumerUsageBits, /**< reference: OMX_PARAM_U32TYPE */ + + /* Time configurations */ + OMX_IndexExtTimeStartUnused = OMX_IndexKhronosExtensions + 0x00900000, + + OMX_IndexExtMax = 0x7FFFFFFF +} OMX_INDEXEXTTYPE; + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OMX_IndexExt_h */ +/* File EOF */ diff --git a/phonelibs/android_frameworks_native/include/media/openmax/OMX_Other.h b/phonelibs/android_frameworks_native/include/media/openmax/OMX_Other.h new file mode 100644 index 0000000000..6072ef62c8 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/media/openmax/OMX_Other.h @@ -0,0 +1,354 @@ +/* ------------------------------------------------------------------ + * Copyright (C) 1998-2009 PacketVideo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. + * See the License for the specific language governing permissions + * and limitations under the License. + * ------------------------------------------------------------------- + */ +/* + * Copyright (c) 2008 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** @file OMX_Other.h - OpenMax IL version 1.1.2 + * The structures needed by Other components to exchange + * parameters and configuration data with the components. + */ + +#ifndef OMX_Other_h +#define OMX_Other_h + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +/* Each OMX header must include all required header files to allow the + * header to compile without errors. The includes below are required + * for this header file to compile successfully + */ + +#include + + +/** + * Enumeration of possible data types which match to multiple domains or no + * domain at all. For types which are vendor specific, a value above + * OMX_OTHER_VENDORTSTART should be used. + */ +typedef enum OMX_OTHER_FORMATTYPE { + OMX_OTHER_FormatTime = 0, /**< Transmission of various timestamps, elapsed time, + time deltas, etc */ + OMX_OTHER_FormatPower, /**< Perhaps used for enabling/disabling power + management, setting clocks? */ + OMX_OTHER_FormatStats, /**< Could be things such as frame rate, frames + dropped, etc */ + OMX_OTHER_FormatBinary, /**< Arbitrary binary data */ + OMX_OTHER_FormatVendorReserved = 1000, /**< Starting value for vendor specific + formats */ + + OMX_OTHER_FormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_OTHER_FormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_OTHER_FormatMax = 0x7FFFFFFF +} OMX_OTHER_FORMATTYPE; + +/** + * Enumeration of seek modes. + */ +typedef enum OMX_TIME_SEEKMODETYPE { + OMX_TIME_SeekModeFast = 0, /**< Prefer seeking to an approximation + * of the requested seek position over + * the actual seek position if it + * results in a faster seek. */ + OMX_TIME_SeekModeAccurate, /**< Prefer seeking to the actual seek + * position over an approximation + * of the requested seek position even + * if it results in a slower seek. */ + OMX_TIME_SeekModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_TIME_SeekModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_TIME_SeekModeMax = 0x7FFFFFFF +} OMX_TIME_SEEKMODETYPE; + +/* Structure representing the seekmode of the component */ +typedef struct OMX_TIME_CONFIG_SEEKMODETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_TIME_SEEKMODETYPE eType; /**< The seek mode */ +} OMX_TIME_CONFIG_SEEKMODETYPE; + +/** Structure representing a time stamp used with the following configs + * on the Clock Component (CC): + * + * OMX_IndexConfigTimeCurrentWallTime: query of the CC's current wall + * time + * OMX_IndexConfigTimeCurrentMediaTime: query of the CC's current media + * time + * OMX_IndexConfigTimeCurrentAudioReference and + * OMX_IndexConfigTimeCurrentVideoReference: audio/video reference + * clock sending SC its reference time + * OMX_IndexConfigTimeClientStartTime: a Clock Component client sends + * this structure to the Clock Component via a SetConfig on its + * client port when it receives a buffer with + * OMX_BUFFERFLAG_STARTTIME set. It must use the timestamp + * specified by that buffer for nStartTimestamp. + * + * It's also used with the following config on components in general: + * + * OMX_IndexConfigTimePosition: IL client querying component position + * (GetConfig) or commanding a component to seek to the given location + * (SetConfig) + */ +typedef struct OMX_TIME_CONFIG_TIMESTAMPTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version + * information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_TICKS nTimestamp; /**< timestamp .*/ +} OMX_TIME_CONFIG_TIMESTAMPTYPE; + +/** Enumeration of possible reference clocks to the media time. */ +typedef enum OMX_TIME_UPDATETYPE { + OMX_TIME_UpdateRequestFulfillment, /**< Update is the fulfillment of a media time request. */ + OMX_TIME_UpdateScaleChanged, /**< Update was generated because the scale chagned. */ + OMX_TIME_UpdateClockStateChanged, /**< Update was generated because the clock state changed. */ + OMX_TIME_UpdateKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_TIME_UpdateVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_TIME_UpdateMax = 0x7FFFFFFF +} OMX_TIME_UPDATETYPE; + +/** Enumeration of possible reference clocks to the media time. */ +typedef enum OMX_TIME_REFCLOCKTYPE { + OMX_TIME_RefClockNone, /**< Use no references. */ + OMX_TIME_RefClockAudio, /**< Use references sent through OMX_IndexConfigTimeCurrentAudioReference */ + OMX_TIME_RefClockVideo, /**< Use references sent through OMX_IndexConfigTimeCurrentVideoReference */ + OMX_TIME_RefClockKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_TIME_RefClockVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_TIME_RefClockMax = 0x7FFFFFFF +} OMX_TIME_REFCLOCKTYPE; + +/** Enumeration of clock states. */ +typedef enum OMX_TIME_CLOCKSTATE { + OMX_TIME_ClockStateRunning, /**< Clock running. */ + OMX_TIME_ClockStateWaitingForStartTime, /**< Clock waiting until the + * prescribed clients emit their + * start time. */ + OMX_TIME_ClockStateStopped, /**< Clock stopped. */ + OMX_TIME_ClockStateKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_TIME_ClockStateVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_TIME_ClockStateMax = 0x7FFFFFFF +} OMX_TIME_CLOCKSTATE; + +/** Structure representing a media time request to the clock component. + * + * A client component sends this structure to the Clock Component via a SetConfig + * on its client port to specify a media timestamp the Clock Component + * should emit. The Clock Component should fulfill the request by sending a + * OMX_TIME_MEDIATIMETYPE when its media clock matches the requested + * timestamp. + * + * The client may require a media time request be fulfilled slightly + * earlier than the media time specified. In this case the client specifies + * an offset which is equal to the difference between wall time corresponding + * to the requested media time and the wall time when it will be + * fulfilled. + * + * A client component may uses these requests and the OMX_TIME_MEDIATIMETYPE to + * time events according to timestamps. If a client must perform an operation O at + * a time T (e.g. deliver a video frame at its corresponding timestamp), it makes a + * media time request at T (perhaps specifying an offset to ensure the request fulfillment + * is a little early). When the clock component passes the resulting OMX_TIME_MEDIATIMETYPE + * structure back to the client component, the client may perform operation O (perhaps having + * to wait a slight amount more time itself as specified by the return values). + */ + +typedef struct OMX_TIME_CONFIG_MEDIATIMEREQUESTTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_PTR pClientPrivate; /**< Client private data to disabiguate this media time + * from others (e.g. the number of the frame to deliver). + * Duplicated in the media time structure that fulfills + * this request. A value of zero is reserved for time scale + * updates. */ + OMX_TICKS nMediaTimestamp; /**< Media timestamp requested.*/ + OMX_TICKS nOffset; /**< Amount of wall clock time by which this + * request should be fulfilled early */ +} OMX_TIME_CONFIG_MEDIATIMEREQUESTTYPE; + +/**< Structure sent from the clock component client either when fulfilling + * a media time request or when the time scale has changed. + * + * In the former case the Clock Component fills this structure and times its emission + * to a client component (via the client port) according to the corresponding media + * time request sent by the client. The Clock Component should time the emission to occur + * when the requested timestamp matches the Clock Component's media time but also the + * prescribed offset early. + * + * Upon scale changes the clock component clears the nClientPrivate data, sends the current + * media time and sets the nScale to the new scale via the client port. It emits a + * OMX_TIME_MEDIATIMETYPE to all clients independent of any requests. This allows clients to + * alter processing to accomodate scaling. For instance a video component might skip inter-frames + * in the case of extreme fastforward. Likewise an audio component might add or remove samples + * from an audio frame to scale audio data. + * + * It is expected that some clock components may not be able to fulfill requests + * at exactly the prescribed time. This is acceptable so long as the request is + * fulfilled at least as early as described and not later. This structure provides + * fields the client may use to wait for the remaining time. + * + * The client may use either the nOffset or nWallTimeAtMedia fields to determine the + * wall time until the nMediaTimestamp actually occurs. In the latter case the + * client can get a more accurate value for offset by getting the current wall + * from the cloc component and subtracting it from nWallTimeAtMedia. + */ + +typedef struct OMX_TIME_MEDIATIMETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nClientPrivate; /**< Client private data to disabiguate this media time + * from others. Copied from the media time request. + * A value of zero is reserved for time scale updates. */ + OMX_TIME_UPDATETYPE eUpdateType; /**< Reason for the update */ + OMX_TICKS nMediaTimestamp; /**< Media time requested. If no media time was + * requested then this is the current media time. */ + OMX_TICKS nOffset; /**< Amount of wall clock time by which this + * request was actually fulfilled early */ + + OMX_TICKS nWallTimeAtMediaTime; /**< Wall time corresponding to nMediaTimeStamp. + * A client may compare this value to current + * media time obtained from the Clock Component to determine + * the wall time until the media timestamp is really + * current. */ + OMX_S32 xScale; /**< Current media time scale in Q16 format. */ + OMX_TIME_CLOCKSTATE eState; /* Seeking Change. Added 7/12.*/ + /**< State of the media time. */ +} OMX_TIME_MEDIATIMETYPE; + +/** Structure representing the current media time scale factor. Applicable only to clock + * component, other components see scale changes via OMX_TIME_MEDIATIMETYPE buffers sent via + * the clock component client ports. Upon recieving this config the clock component changes + * the rate by which the media time increases or decreases effectively implementing trick modes. + */ +typedef struct OMX_TIME_CONFIG_SCALETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_S32 xScale; /**< This is a value in Q16 format which is used for + * scaling the media time */ +} OMX_TIME_CONFIG_SCALETYPE; + +/** Bits used to identify a clock port. Used in OMX_TIME_CONFIG_CLOCKSTATETYPE's nWaitMask field */ +#define OMX_CLOCKPORT0 0x00000001 +#define OMX_CLOCKPORT1 0x00000002 +#define OMX_CLOCKPORT2 0x00000004 +#define OMX_CLOCKPORT3 0x00000008 +#define OMX_CLOCKPORT4 0x00000010 +#define OMX_CLOCKPORT5 0x00000020 +#define OMX_CLOCKPORT6 0x00000040 +#define OMX_CLOCKPORT7 0x00000080 + +/** Structure representing the current mode of the media clock. + * IL Client uses this config to change or query the mode of the + * media clock of the clock component. Applicable only to clock + * component. + * + * On a SetConfig if eState is OMX_TIME_ClockStateRunning media time + * starts immediately at the prescribed start time. If + * OMX_TIME_ClockStateWaitingForStartTime the Clock Component ignores + * the given nStartTime and waits for all clients specified in the + * nWaitMask to send starttimes (via + * OMX_IndexConfigTimeClientStartTime). The Clock Component then starts + * the media clock using the earliest start time supplied. */ +typedef struct OMX_TIME_CONFIG_CLOCKSTATETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version + * information */ + OMX_TIME_CLOCKSTATE eState; /**< State of the media time. */ + OMX_TICKS nStartTime; /**< Start time of the media time. */ + OMX_TICKS nOffset; /**< Time to offset the media time by + * (e.g. preroll). Media time will be + * reported to be nOffset ticks earlier. + */ + OMX_U32 nWaitMask; /**< Mask of OMX_CLOCKPORT values. */ +} OMX_TIME_CONFIG_CLOCKSTATETYPE; + +/** Structure representing the reference clock currently being used to + * compute media time. IL client uses this config to change or query the + * clock component's active reference clock */ +typedef struct OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_TIME_REFCLOCKTYPE eClock; /**< Reference clock used to compute media time */ +} OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE; + +/** Descriptor for setting specifics of power type. + * Note: this structure is listed for backwards compatibility. */ +typedef struct OMX_OTHER_CONFIG_POWERTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_BOOL bEnablePM; /**< Flag to enable Power Management */ +} OMX_OTHER_CONFIG_POWERTYPE; + + +/** Descriptor for setting specifics of stats type. + * Note: this structure is listed for backwards compatibility. */ +typedef struct OMX_OTHER_CONFIG_STATSTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + /* what goes here */ +} OMX_OTHER_CONFIG_STATSTYPE; + + +/** + * The PortDefinition structure is used to define all of the parameters + * necessary for the compliant component to setup an input or an output other + * path. + */ +typedef struct OMX_OTHER_PORTDEFINITIONTYPE { + OMX_OTHER_FORMATTYPE eFormat; /**< Type of data expected for this channel */ +} OMX_OTHER_PORTDEFINITIONTYPE; + +/** Port format parameter. This structure is used to enumerate + * the various data input/output format supported by the port. + */ +typedef struct OMX_OTHER_PARAM_PORTFORMATTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Indicates which port to set */ + OMX_U32 nIndex; /**< Indicates the enumeration index for the format from 0x0 to N-1 */ + OMX_OTHER_FORMATTYPE eFormat; /**< Type of data expected for this channel */ +} OMX_OTHER_PARAM_PORTFORMATTYPE; + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif +/* File EOF */ diff --git a/phonelibs/android_frameworks_native/include/media/openmax/OMX_Types.h b/phonelibs/android_frameworks_native/include/media/openmax/OMX_Types.h new file mode 100644 index 0000000000..5afaba057c --- /dev/null +++ b/phonelibs/android_frameworks_native/include/media/openmax/OMX_Types.h @@ -0,0 +1,387 @@ +/* ------------------------------------------------------------------ + * Copyright (C) 1998-2009 PacketVideo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. + * See the License for the specific language governing permissions + * and limitations under the License. + * ------------------------------------------------------------------- + */ +/* + * Copyright (c) 2008 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** OMX_Types.h - OpenMax IL version 1.1.2 + * The OMX_Types header file contains the primitive type definitions used by + * the core, the application and the component. This file may need to be + * modified to be used on systems that do not have "char" set to 8 bits, + * "short" set to 16 bits and "long" set to 32 bits. + */ + +#ifndef OMX_Types_h +#define OMX_Types_h + +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** The OMX_API and OMX_APIENTRY are platform specific definitions used + * to declare OMX function prototypes. They are modified to meet the + * requirements for a particular platform */ +#ifdef __SYMBIAN32__ +# ifdef __OMX_EXPORTS +# define OMX_API __declspec(dllexport) +# else +# ifdef _WIN32 +# define OMX_API __declspec(dllexport) +# else +# define OMX_API __declspec(dllimport) +# endif +# endif +#else +# ifdef _WIN32 +# ifdef __OMX_EXPORTS +# define OMX_API __declspec(dllexport) +# else +//# define OMX_API __declspec(dllimport) +#define OMX_API +# endif +# else +# ifdef __OMX_EXPORTS +# define OMX_API +# else +# define OMX_API extern +# endif +# endif +#endif + +#ifndef OMX_APIENTRY +#define OMX_APIENTRY +#endif + +/** OMX_IN is used to identify inputs to an OMX function. This designation + will also be used in the case of a pointer that points to a parameter + that is used as an output. */ +#ifndef OMX_IN +#define OMX_IN +#endif + +/** OMX_OUT is used to identify outputs from an OMX function. This + designation will also be used in the case of a pointer that points + to a parameter that is used as an input. */ +#ifndef OMX_OUT +#define OMX_OUT +#endif + + +/** OMX_INOUT is used to identify parameters that may be either inputs or + outputs from an OMX function at the same time. This designation will + also be used in the case of a pointer that points to a parameter that + is used both as an input and an output. */ +#ifndef OMX_INOUT +#define OMX_INOUT +#endif + +/** OMX_ALL is used to as a wildcard to select all entities of the same type + * when specifying the index, or referring to a object by an index. (i.e. + * use OMX_ALL to indicate all N channels). When used as a port index + * for a config or parameter this OMX_ALL denotes that the config or + * parameter applies to the entire component not just one port. */ +#define OMX_ALL 0xFFFFFFFF + +/** In the following we define groups that help building doxygen documentation */ + +/** @defgroup core OpenMAX IL core + * Functions and structure related to the OMX IL core + */ + + /** @defgroup comp OpenMAX IL component + * Functions and structure related to the OMX IL component + */ + +/** @defgroup rpm Resource and Policy Management + * Structures for resource and policy management of components + */ + +/** @defgroup buf Buffer Management + * Buffer handling functions and structures + */ + +/** @defgroup tun Tunneling + * @ingroup core comp + * Structures and functions to manage tunnels among component ports + */ + +/** @defgroup cp Content Pipes + * @ingroup core + */ + + /** @defgroup metadata Metadata handling + * + */ + +/** OMX_U8 is an 8 bit unsigned quantity that is byte aligned */ +typedef unsigned char OMX_U8; + +/** OMX_S8 is an 8 bit signed quantity that is byte aligned */ +typedef signed char OMX_S8; + +/** OMX_U16 is a 16 bit unsigned quantity that is 16 bit word aligned */ +typedef unsigned short OMX_U16; + +/** OMX_S16 is a 16 bit signed quantity that is 16 bit word aligned */ +typedef signed short OMX_S16; + +/** OMX_U32 is a 32 bit unsigned quantity that is 32 bit word aligned */ +typedef uint32_t OMX_U32; + +/** OMX_S32 is a 32 bit signed quantity that is 32 bit word aligned */ +typedef int32_t OMX_S32; + + +/* Users with compilers that cannot accept the "long long" designation should + define the OMX_SKIP64BIT macro. It should be noted that this may cause + some components to fail to compile if the component was written to require + 64 bit integral types. However, these components would NOT compile anyway + since the compiler does not support the way the component was written. +*/ +#ifndef OMX_SKIP64BIT +#ifdef __SYMBIAN32__ +/** OMX_U64 is a 64 bit unsigned quantity that is 64 bit word aligned */ +typedef unsigned long long OMX_U64; + +/** OMX_S64 is a 64 bit signed quantity that is 64 bit word aligned */ +typedef signed long long OMX_S64; + +#elif defined(WIN32) + +/** OMX_U64 is a 64 bit unsigned quantity that is 64 bit word aligned */ +typedef unsigned __int64 OMX_U64; + +/** OMX_S64 is a 64 bit signed quantity that is 64 bit word aligned */ +typedef signed __int64 OMX_S64; + +#else /* WIN32 */ + +/** OMX_U64 is a 64 bit unsigned quantity that is 64 bit word aligned */ +typedef unsigned long long OMX_U64; + +/** OMX_S64 is a 64 bit signed quantity that is 64 bit word aligned */ +typedef signed long long OMX_S64; + +#endif /* WIN32 */ +#endif + + +/** The OMX_BOOL type is intended to be used to represent a true or a false + value when passing parameters to and from the OMX core and components. The + OMX_BOOL is a 32 bit quantity and is aligned on a 32 bit word boundary. + */ +typedef enum OMX_BOOL { + OMX_FALSE = 0, + OMX_TRUE = !OMX_FALSE, + OMX_BOOL_MAX = 0x7FFFFFFF +} OMX_BOOL; + +/* + * Temporary Android 64 bit modification + * + * #define OMX_ANDROID_COMPILE_AS_32BIT_ON_64BIT_PLATFORMS + * overrides all OMX pointer types to be uint32_t. + * + * After this change, OMX codecs will work in 32 bit only, so 64 bit processes + * must communicate to a remote 32 bit process for OMX to work. + */ + +#ifdef OMX_ANDROID_COMPILE_AS_32BIT_ON_64BIT_PLATFORMS + +typedef uint32_t OMX_PTR; +typedef OMX_PTR OMX_STRING; +typedef OMX_PTR OMX_BYTE; + +#else /* OMX_ANDROID_COMPILE_AS_32BIT_ON_64BIT_PLATFORMS */ + +/** The OMX_PTR type is intended to be used to pass pointers between the OMX + applications and the OMX Core and components. This is a 32 bit pointer and + is aligned on a 32 bit boundary. + */ +typedef void* OMX_PTR; + +/** The OMX_STRING type is intended to be used to pass "C" type strings between + the application and the core and component. The OMX_STRING type is a 32 + bit pointer to a zero terminated string. The pointer is word aligned and + the string is byte aligned. + */ +typedef char* OMX_STRING; + +/** The OMX_BYTE type is intended to be used to pass arrays of bytes such as + buffers between the application and the component and core. The OMX_BYTE + type is a 32 bit pointer to a zero terminated string. The pointer is word + aligned and the string is byte aligned. + */ +typedef unsigned char* OMX_BYTE; + +#endif /* OMX_ANDROID_COMPILE_AS_32BIT_ON_64BIT_PLATFORMS */ + +/** OMX_UUIDTYPE is a very long unique identifier to uniquely identify + at runtime. This identifier should be generated by a component in a way + that guarantees that every instance of the identifier running on the system + is unique. */ +typedef unsigned char OMX_UUIDTYPE[128]; + +/** The OMX_DIRTYPE enumeration is used to indicate if a port is an input or + an output port. This enumeration is common across all component types. + */ +typedef enum OMX_DIRTYPE +{ + OMX_DirInput, /**< Port is an input port */ + OMX_DirOutput, /**< Port is an output port */ + OMX_DirMax = 0x7FFFFFFF +} OMX_DIRTYPE; + +/** The OMX_ENDIANTYPE enumeration is used to indicate the bit ordering + for numerical data (i.e. big endian, or little endian). + */ +typedef enum OMX_ENDIANTYPE +{ + OMX_EndianBig, /**< big endian */ + OMX_EndianLittle, /**< little endian */ + OMX_EndianMax = 0x7FFFFFFF +} OMX_ENDIANTYPE; + + +/** The OMX_NUMERICALDATATYPE enumeration is used to indicate if data + is signed or unsigned + */ +typedef enum OMX_NUMERICALDATATYPE +{ + OMX_NumericalDataSigned, /**< signed data */ + OMX_NumericalDataUnsigned, /**< unsigned data */ + OMX_NumercialDataMax = 0x7FFFFFFF +} OMX_NUMERICALDATATYPE; + + +/** Unsigned bounded value type */ +typedef struct OMX_BU32 { + OMX_U32 nValue; /**< actual value */ + OMX_U32 nMin; /**< minimum for value (i.e. nValue >= nMin) */ + OMX_U32 nMax; /**< maximum for value (i.e. nValue <= nMax) */ +} OMX_BU32; + + +/** Signed bounded value type */ +typedef struct OMX_BS32 { + OMX_S32 nValue; /**< actual value */ + OMX_S32 nMin; /**< minimum for value (i.e. nValue >= nMin) */ + OMX_S32 nMax; /**< maximum for value (i.e. nValue <= nMax) */ +} OMX_BS32; + + +/** Structure representing some time or duration in microseconds. This structure + * must be interpreted as a signed 64 bit value. The quantity is signed to accommodate + * negative deltas and preroll scenarios. The quantity is represented in microseconds + * to accomodate high resolution timestamps (e.g. DVD presentation timestamps based + * on a 90kHz clock) and to allow more accurate and synchronized delivery (e.g. + * individual audio samples delivered at 192 kHz). The quantity is 64 bit to + * accommodate a large dynamic range (signed 32 bit values would allow only for plus + * or minus 35 minutes). + * + * Implementations with limited precision may convert the signed 64 bit value to + * a signed 32 bit value internally but risk loss of precision. + */ +#ifndef OMX_SKIP64BIT +typedef OMX_S64 OMX_TICKS; +#else +typedef struct OMX_TICKS +{ + OMX_U32 nLowPart; /** low bits of the signed 64 bit tick value */ + OMX_U32 nHighPart; /** high bits of the signed 64 bit tick value */ +} OMX_TICKS; +#endif +#define OMX_TICKS_PER_SECOND 1000000 + +/** Define the public interface for the OMX Handle. The core will not use + this value internally, but the application should only use this value. + */ +typedef OMX_PTR OMX_HANDLETYPE; + +typedef struct OMX_MARKTYPE +{ + OMX_HANDLETYPE hMarkTargetComponent; /**< The component that will + generate a mark event upon + processing the mark. */ + OMX_PTR pMarkData; /**< Application specific data associated with + the mark sent on a mark event to disambiguate + this mark from others. */ +} OMX_MARKTYPE; + + +/** OMX_NATIVE_DEVICETYPE is used to map a OMX video port to the + * platform & operating specific object used to reference the display + * or can be used by a audio port for native audio rendering */ +typedef OMX_PTR OMX_NATIVE_DEVICETYPE; + +/** OMX_NATIVE_WINDOWTYPE is used to map a OMX video port to the + * platform & operating specific object used to reference the window */ +typedef OMX_PTR OMX_NATIVE_WINDOWTYPE; + +/** The OMX_VERSIONTYPE union is used to specify the version for + a structure or component. For a component, the version is entirely + specified by the component vendor. Components doing the same function + from different vendors may or may not have the same version. For + structures, the version shall be set by the entity that allocates the + structure. For structures specified in the OMX 1.1 specification, the + value of the version shall be set to 1.1.0.0 in all cases. Access to the + OMX_VERSIONTYPE can be by a single 32 bit access (e.g. by nVersion) or + by accessing one of the structure elements to, for example, check only + the Major revision. + */ +typedef union OMX_VERSIONTYPE +{ + struct + { + OMX_U8 nVersionMajor; /**< Major version accessor element */ + OMX_U8 nVersionMinor; /**< Minor version accessor element */ + OMX_U8 nRevision; /**< Revision version accessor element */ + OMX_U8 nStep; /**< Step version accessor element */ + } s; + OMX_U32 nVersion; /**< 32 bit value to make accessing the + version easily done in a single word + size copy/compare operation */ +} OMX_VERSIONTYPE; + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif +/* File EOF */ diff --git a/phonelibs/android_frameworks_native/include/media/openmax/OMX_Video.h b/phonelibs/android_frameworks_native/include/media/openmax/OMX_Video.h new file mode 100644 index 0000000000..decc410ba9 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/media/openmax/OMX_Video.h @@ -0,0 +1,1081 @@ +/* ------------------------------------------------------------------ + * Copyright (C) 1998-2009 PacketVideo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. + * See the License for the specific language governing permissions + * and limitations under the License. + * ------------------------------------------------------------------- + */ +/** + * Copyright (c) 2008 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** + * @file OMX_Video.h - OpenMax IL version 1.1.2 + * The structures is needed by Video components to exchange parameters + * and configuration data with OMX components. + */ +#ifndef OMX_Video_h +#define OMX_Video_h + +/** @defgroup video OpenMAX IL Video Domain + * @ingroup iv + * Structures for OpenMAX IL Video domain + * @{ + */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +/** + * Each OMX header must include all required header files to allow the + * header to compile without errors. The includes below are required + * for this header file to compile successfully + */ + +#include + + +/** + * Enumeration used to define the possible video compression codings. + * NOTE: This essentially refers to file extensions. If the coding is + * being used to specify the ENCODE type, then additional work + * must be done to configure the exact flavor of the compression + * to be used. For decode cases where the user application can + * not differentiate between MPEG-4 and H.264 bit streams, it is + * up to the codec to handle this. + */ +typedef enum OMX_VIDEO_CODINGTYPE { + OMX_VIDEO_CodingUnused, /**< Value when coding is N/A */ + OMX_VIDEO_CodingAutoDetect, /**< Autodetection of coding type */ + OMX_VIDEO_CodingMPEG2, /**< AKA: H.262 */ + OMX_VIDEO_CodingH263, /**< H.263 */ + OMX_VIDEO_CodingMPEG4, /**< MPEG-4 */ + OMX_VIDEO_CodingWMV, /**< all versions of Windows Media Video */ + OMX_VIDEO_CodingRV, /**< all versions of Real Video */ + OMX_VIDEO_CodingAVC, /**< H.264/AVC */ + OMX_VIDEO_CodingMJPEG, /**< Motion JPEG */ + OMX_VIDEO_CodingVP8, /**< Google VP8, formerly known as On2 VP8 */ + OMX_VIDEO_CodingVP9, /**< Google VP9 */ + OMX_VIDEO_CodingHEVC, /**< ITU H.265/HEVC */ + OMX_VIDEO_CodingKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_CodingVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_CodingMax = 0x7FFFFFFF +} OMX_VIDEO_CODINGTYPE; + + +/** + * Data structure used to define a video path. The number of Video paths for + * input and output will vary by type of the Video component. + * + * Input (aka Source) : zero Inputs, one Output, + * Splitter : one Input, 2 or more Outputs, + * Processing Element : one Input, one output, + * Mixer : 2 or more inputs, one output, + * Output (aka Sink) : one Input, zero outputs. + * + * The PortDefinition structure is used to define all of the parameters + * necessary for the compliant component to setup an input or an output video + * path. If additional vendor specific data is required, it should be + * transmitted to the component using the CustomCommand function. Compliant + * components will prepopulate this structure with optimal values during the + * GetDefaultInitParams command. + * + * STRUCT MEMBERS: + * cMIMEType : MIME type of data for the port + * pNativeRender : Platform specific reference for a display if a + * sync, otherwise this field is 0 + * nFrameWidth : Width of frame to be used on channel if + * uncompressed format is used. Use 0 for unknown, + * don't care or variable + * nFrameHeight : Height of frame to be used on channel if + * uncompressed format is used. Use 0 for unknown, + * don't care or variable + * nStride : Number of bytes per span of an image + * (i.e. indicates the number of bytes to get + * from span N to span N+1, where negative stride + * indicates the image is bottom up + * nSliceHeight : Height used when encoding in slices + * nBitrate : Bit rate of frame to be used on channel if + * compressed format is used. Use 0 for unknown, + * don't care or variable + * xFramerate : Frame rate to be used on channel if uncompressed + * format is used. Use 0 for unknown, don't care or + * variable. Units are Q16 frames per second. + * bFlagErrorConcealment : Turns on error concealment if it is supported by + * the OMX component + * eCompressionFormat : Compression format used in this instance of the + * component. When OMX_VIDEO_CodingUnused is + * specified, eColorFormat is used + * eColorFormat : Decompressed format used by this component + * pNativeWindow : Platform specific reference for a window object if a + * display sink , otherwise this field is 0x0. + */ +typedef struct OMX_VIDEO_PORTDEFINITIONTYPE { + OMX_STRING cMIMEType; + OMX_NATIVE_DEVICETYPE pNativeRender; + OMX_U32 nFrameWidth; + OMX_U32 nFrameHeight; + OMX_S32 nStride; + OMX_U32 nSliceHeight; + OMX_U32 nBitrate; + OMX_U32 xFramerate; + OMX_BOOL bFlagErrorConcealment; + OMX_VIDEO_CODINGTYPE eCompressionFormat; + OMX_COLOR_FORMATTYPE eColorFormat; + OMX_NATIVE_WINDOWTYPE pNativeWindow; +} OMX_VIDEO_PORTDEFINITIONTYPE; + +/** + * Port format parameter. This structure is used to enumerate the various + * data input/output format supported by the port. + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Indicates which port to set + * nIndex : Indicates the enumeration index for the format from + * 0x0 to N-1 + * eCompressionFormat : Compression format used in this instance of the + * component. When OMX_VIDEO_CodingUnused is specified, + * eColorFormat is used + * eColorFormat : Decompressed format used by this component + * xFrameRate : Indicates the video frame rate in Q16 format + */ +typedef struct OMX_VIDEO_PARAM_PORTFORMATTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nIndex; + OMX_VIDEO_CODINGTYPE eCompressionFormat; + OMX_COLOR_FORMATTYPE eColorFormat; + OMX_U32 xFramerate; +} OMX_VIDEO_PARAM_PORTFORMATTYPE; + + +/** + * This is a structure for configuring video compression quantization + * parameter values. Codecs may support different QP values for different + * frame types. + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version info + * nPortIndex : Port that this structure applies to + * nQpI : QP value to use for index frames + * nQpP : QP value to use for P frames + * nQpB : QP values to use for bidirectional frames + */ +typedef struct OMX_VIDEO_PARAM_QUANTIZATIONTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nQpI; + OMX_U32 nQpP; + OMX_U32 nQpB; +} OMX_VIDEO_PARAM_QUANTIZATIONTYPE; + + +/** + * Structure for configuration of video fast update parameters. + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version info + * nPortIndex : Port that this structure applies to + * bEnableVFU : Enable/Disable video fast update + * nFirstGOB : Specifies the number of the first macroblock row + * nFirstMB : specifies the first MB relative to the specified first GOB + * nNumMBs : Specifies the number of MBs to be refreshed from nFirstGOB + * and nFirstMB + */ +typedef struct OMX_VIDEO_PARAM_VIDEOFASTUPDATETYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bEnableVFU; + OMX_U32 nFirstGOB; + OMX_U32 nFirstMB; + OMX_U32 nNumMBs; +} OMX_VIDEO_PARAM_VIDEOFASTUPDATETYPE; + + +/** + * Enumeration of possible bitrate control types + */ +typedef enum OMX_VIDEO_CONTROLRATETYPE { + OMX_Video_ControlRateDisable, + OMX_Video_ControlRateVariable, + OMX_Video_ControlRateConstant, + OMX_Video_ControlRateVariableSkipFrames, + OMX_Video_ControlRateConstantSkipFrames, + OMX_Video_ControlRateKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_Video_ControlRateVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_Video_ControlRateMax = 0x7FFFFFFF +} OMX_VIDEO_CONTROLRATETYPE; + + +/** + * Structure for configuring bitrate mode of a codec. + * + * STRUCT MEMBERS: + * nSize : Size of the struct in bytes + * nVersion : OMX spec version info + * nPortIndex : Port that this struct applies to + * eControlRate : Control rate type enum + * nTargetBitrate : Target bitrate to encode with + */ +typedef struct OMX_VIDEO_PARAM_BITRATETYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_VIDEO_CONTROLRATETYPE eControlRate; + OMX_U32 nTargetBitrate; +} OMX_VIDEO_PARAM_BITRATETYPE; + + +/** + * Enumeration of possible motion vector (MV) types + */ +typedef enum OMX_VIDEO_MOTIONVECTORTYPE { + OMX_Video_MotionVectorPixel, + OMX_Video_MotionVectorHalfPel, + OMX_Video_MotionVectorQuarterPel, + OMX_Video_MotionVectorEighthPel, + OMX_Video_MotionVectorKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_Video_MotionVectorVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_Video_MotionVectorMax = 0x7FFFFFFF +} OMX_VIDEO_MOTIONVECTORTYPE; + + +/** + * Structure for configuring the number of motion vectors used as well + * as their accuracy. + * + * STRUCT MEMBERS: + * nSize : Size of the struct in bytes + * nVersion : OMX spec version info + * nPortIndex : port that this structure applies to + * eAccuracy : Enumerated MV accuracy + * bUnrestrictedMVs : Allow unrestricted MVs + * bFourMV : Allow use of 4 MVs + * sXSearchRange : Search range in horizontal direction for MVs + * sYSearchRange : Search range in vertical direction for MVs + */ +typedef struct OMX_VIDEO_PARAM_MOTIONVECTORTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_VIDEO_MOTIONVECTORTYPE eAccuracy; + OMX_BOOL bUnrestrictedMVs; + OMX_BOOL bFourMV; + OMX_S32 sXSearchRange; + OMX_S32 sYSearchRange; +} OMX_VIDEO_PARAM_MOTIONVECTORTYPE; + + +/** + * Enumeration of possible methods to use for Intra Refresh + */ +typedef enum OMX_VIDEO_INTRAREFRESHTYPE { + OMX_VIDEO_IntraRefreshCyclic, + OMX_VIDEO_IntraRefreshAdaptive, + OMX_VIDEO_IntraRefreshBoth, + OMX_VIDEO_IntraRefreshKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_IntraRefreshVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_IntraRefreshMax = 0x7FFFFFFF +} OMX_VIDEO_INTRAREFRESHTYPE; + + +/** + * Structure for configuring intra refresh mode + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * eRefreshMode : Cyclic, Adaptive, or Both + * nAirMBs : Number of intra macroblocks to refresh in a frame when + * AIR is enabled + * nAirRef : Number of times a motion marked macroblock has to be + * intra coded + * nCirMBs : Number of consecutive macroblocks to be coded as "intra" + * when CIR is enabled + */ +typedef struct OMX_VIDEO_PARAM_INTRAREFRESHTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_VIDEO_INTRAREFRESHTYPE eRefreshMode; + OMX_U32 nAirMBs; + OMX_U32 nAirRef; + OMX_U32 nCirMBs; +} OMX_VIDEO_PARAM_INTRAREFRESHTYPE; + + +/** + * Structure for enabling various error correction methods for video + * compression. + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * bEnableHEC : Enable/disable header extension codes (HEC) + * bEnableResync : Enable/disable resynchronization markers + * nResynchMarkerSpacing : Resynch markers interval (in bits) to be + * applied in the stream + * bEnableDataPartitioning : Enable/disable data partitioning + * bEnableRVLC : Enable/disable reversible variable length + * coding + */ +typedef struct OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bEnableHEC; + OMX_BOOL bEnableResync; + OMX_U32 nResynchMarkerSpacing; + OMX_BOOL bEnableDataPartitioning; + OMX_BOOL bEnableRVLC; +} OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE; + + +/** + * Configuration of variable block-size motion compensation (VBSMC) + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * b16x16 : Enable inter block search 16x16 + * b16x8 : Enable inter block search 16x8 + * b8x16 : Enable inter block search 8x16 + * b8x8 : Enable inter block search 8x8 + * b8x4 : Enable inter block search 8x4 + * b4x8 : Enable inter block search 4x8 + * b4x4 : Enable inter block search 4x4 + */ +typedef struct OMX_VIDEO_PARAM_VBSMCTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL b16x16; + OMX_BOOL b16x8; + OMX_BOOL b8x16; + OMX_BOOL b8x8; + OMX_BOOL b8x4; + OMX_BOOL b4x8; + OMX_BOOL b4x4; +} OMX_VIDEO_PARAM_VBSMCTYPE; + + +/** + * H.263 profile types, each profile indicates support for various + * performance bounds and different annexes. + * + * ENUMS: + * Baseline : Baseline Profile: H.263 (V1), no optional modes + * H320 Coding : H.320 Coding Efficiency Backward Compatibility + * Profile: H.263+ (V2), includes annexes I, J, L.4 + * and T + * BackwardCompatible : Backward Compatibility Profile: H.263 (V1), + * includes annex F + * ISWV2 : Interactive Streaming Wireless Profile: H.263+ + * (V2), includes annexes I, J, K and T + * ISWV3 : Interactive Streaming Wireless Profile: H.263++ + * (V3), includes profile 3 and annexes V and W.6.3.8 + * HighCompression : Conversational High Compression Profile: H.263++ + * (V3), includes profiles 1 & 2 and annexes D and U + * Internet : Conversational Internet Profile: H.263++ (V3), + * includes profile 5 and annex K + * Interlace : Conversational Interlace Profile: H.263++ (V3), + * includes profile 5 and annex W.6.3.11 + * HighLatency : High Latency Profile: H.263++ (V3), includes + * profile 6 and annexes O.1 and P.5 + */ +typedef enum OMX_VIDEO_H263PROFILETYPE { + OMX_VIDEO_H263ProfileBaseline = 0x01, + OMX_VIDEO_H263ProfileH320Coding = 0x02, + OMX_VIDEO_H263ProfileBackwardCompatible = 0x04, + OMX_VIDEO_H263ProfileISWV2 = 0x08, + OMX_VIDEO_H263ProfileISWV3 = 0x10, + OMX_VIDEO_H263ProfileHighCompression = 0x20, + OMX_VIDEO_H263ProfileInternet = 0x40, + OMX_VIDEO_H263ProfileInterlace = 0x80, + OMX_VIDEO_H263ProfileHighLatency = 0x100, + OMX_VIDEO_H263ProfileKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_H263ProfileVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_H263ProfileMax = 0x7FFFFFFF +} OMX_VIDEO_H263PROFILETYPE; + + +/** + * H.263 level types, each level indicates support for various frame sizes, + * bit rates, decoder frame rates. + */ +typedef enum OMX_VIDEO_H263LEVELTYPE { + OMX_VIDEO_H263Level10 = 0x01, + OMX_VIDEO_H263Level20 = 0x02, + OMX_VIDEO_H263Level30 = 0x04, + OMX_VIDEO_H263Level40 = 0x08, + OMX_VIDEO_H263Level45 = 0x10, + OMX_VIDEO_H263Level50 = 0x20, + OMX_VIDEO_H263Level60 = 0x40, + OMX_VIDEO_H263Level70 = 0x80, + OMX_VIDEO_H263LevelKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_H263LevelVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_H263LevelMax = 0x7FFFFFFF +} OMX_VIDEO_H263LEVELTYPE; + + +/** + * Specifies the picture type. These values should be OR'd to signal all + * pictures types which are allowed. + * + * ENUMS: + * Generic Picture Types: I, P and B + * H.263 Specific Picture Types: SI and SP + * H.264 Specific Picture Types: EI and EP + * MPEG-4 Specific Picture Types: S + */ +typedef enum OMX_VIDEO_PICTURETYPE { + OMX_VIDEO_PictureTypeI = 0x01, + OMX_VIDEO_PictureTypeP = 0x02, + OMX_VIDEO_PictureTypeB = 0x04, + OMX_VIDEO_PictureTypeSI = 0x08, + OMX_VIDEO_PictureTypeSP = 0x10, + OMX_VIDEO_PictureTypeEI = 0x11, + OMX_VIDEO_PictureTypeEP = 0x12, + OMX_VIDEO_PictureTypeS = 0x14, + OMX_VIDEO_PictureTypeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_PictureTypeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_PictureTypeMax = 0x7FFFFFFF +} OMX_VIDEO_PICTURETYPE; + + +/** + * H.263 Params + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * nPFrames : Number of P frames between each I frame + * nBFrames : Number of B frames between each I frame + * eProfile : H.263 profile(s) to use + * eLevel : H.263 level(s) to use + * bPLUSPTYPEAllowed : Indicating that it is allowed to use PLUSPTYPE + * (specified in the 1998 version of H.263) to + * indicate custom picture sizes or clock + * frequencies + * nAllowedPictureTypes : Specifies the picture types allowed in the + * bitstream + * bForceRoundingTypeToZero : value of the RTYPE bit (bit 6 of MPPTYPE) is + * not constrained. It is recommended to change + * the value of the RTYPE bit for each reference + * picture in error-free communication + * nPictureHeaderRepetition : Specifies the frequency of picture header + * repetition + * nGOBHeaderInterval : Specifies the interval of non-empty GOB + * headers in units of GOBs + */ +typedef struct OMX_VIDEO_PARAM_H263TYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nPFrames; + OMX_U32 nBFrames; + OMX_VIDEO_H263PROFILETYPE eProfile; + OMX_VIDEO_H263LEVELTYPE eLevel; + OMX_BOOL bPLUSPTYPEAllowed; + OMX_U32 nAllowedPictureTypes; + OMX_BOOL bForceRoundingTypeToZero; + OMX_U32 nPictureHeaderRepetition; + OMX_U32 nGOBHeaderInterval; +} OMX_VIDEO_PARAM_H263TYPE; + + +/** + * MPEG-2 profile types, each profile indicates support for various + * performance bounds and different annexes. + */ +typedef enum OMX_VIDEO_MPEG2PROFILETYPE { + OMX_VIDEO_MPEG2ProfileSimple = 0, /**< Simple Profile */ + OMX_VIDEO_MPEG2ProfileMain, /**< Main Profile */ + OMX_VIDEO_MPEG2Profile422, /**< 4:2:2 Profile */ + OMX_VIDEO_MPEG2ProfileSNR, /**< SNR Profile */ + OMX_VIDEO_MPEG2ProfileSpatial, /**< Spatial Profile */ + OMX_VIDEO_MPEG2ProfileHigh, /**< High Profile */ + OMX_VIDEO_MPEG2ProfileKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_MPEG2ProfileVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_MPEG2ProfileMax = 0x7FFFFFFF +} OMX_VIDEO_MPEG2PROFILETYPE; + + +/** + * MPEG-2 level types, each level indicates support for various frame + * sizes, bit rates, decoder frame rates. No need + */ +typedef enum OMX_VIDEO_MPEG2LEVELTYPE { + OMX_VIDEO_MPEG2LevelLL = 0, /**< Low Level */ + OMX_VIDEO_MPEG2LevelML, /**< Main Level */ + OMX_VIDEO_MPEG2LevelH14, /**< High 1440 */ + OMX_VIDEO_MPEG2LevelHL, /**< High Level */ + OMX_VIDEO_MPEG2LevelKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_MPEG2LevelVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_MPEG2LevelMax = 0x7FFFFFFF +} OMX_VIDEO_MPEG2LEVELTYPE; + + +/** + * MPEG-2 params + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * nPFrames : Number of P frames between each I frame + * nBFrames : Number of B frames between each I frame + * eProfile : MPEG-2 profile(s) to use + * eLevel : MPEG-2 levels(s) to use + */ +typedef struct OMX_VIDEO_PARAM_MPEG2TYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nPFrames; + OMX_U32 nBFrames; + OMX_VIDEO_MPEG2PROFILETYPE eProfile; + OMX_VIDEO_MPEG2LEVELTYPE eLevel; +} OMX_VIDEO_PARAM_MPEG2TYPE; + + +/** + * MPEG-4 profile types, each profile indicates support for various + * performance bounds and different annexes. + * + * ENUMS: + * - Simple Profile, Levels 1-3 + * - Simple Scalable Profile, Levels 1-2 + * - Core Profile, Levels 1-2 + * - Main Profile, Levels 2-4 + * - N-bit Profile, Level 2 + * - Scalable Texture Profile, Level 1 + * - Simple Face Animation Profile, Levels 1-2 + * - Simple Face and Body Animation (FBA) Profile, Levels 1-2 + * - Basic Animated Texture Profile, Levels 1-2 + * - Hybrid Profile, Levels 1-2 + * - Advanced Real Time Simple Profiles, Levels 1-4 + * - Core Scalable Profile, Levels 1-3 + * - Advanced Coding Efficiency Profile, Levels 1-4 + * - Advanced Core Profile, Levels 1-2 + * - Advanced Scalable Texture, Levels 2-3 + */ +typedef enum OMX_VIDEO_MPEG4PROFILETYPE { + OMX_VIDEO_MPEG4ProfileSimple = 0x01, + OMX_VIDEO_MPEG4ProfileSimpleScalable = 0x02, + OMX_VIDEO_MPEG4ProfileCore = 0x04, + OMX_VIDEO_MPEG4ProfileMain = 0x08, + OMX_VIDEO_MPEG4ProfileNbit = 0x10, + OMX_VIDEO_MPEG4ProfileScalableTexture = 0x20, + OMX_VIDEO_MPEG4ProfileSimpleFace = 0x40, + OMX_VIDEO_MPEG4ProfileSimpleFBA = 0x80, + OMX_VIDEO_MPEG4ProfileBasicAnimated = 0x100, + OMX_VIDEO_MPEG4ProfileHybrid = 0x200, + OMX_VIDEO_MPEG4ProfileAdvancedRealTime = 0x400, + OMX_VIDEO_MPEG4ProfileCoreScalable = 0x800, + OMX_VIDEO_MPEG4ProfileAdvancedCoding = 0x1000, + OMX_VIDEO_MPEG4ProfileAdvancedCore = 0x2000, + OMX_VIDEO_MPEG4ProfileAdvancedScalable = 0x4000, + OMX_VIDEO_MPEG4ProfileAdvancedSimple = 0x8000, + OMX_VIDEO_MPEG4ProfileKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_MPEG4ProfileVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_MPEG4ProfileMax = 0x7FFFFFFF +} OMX_VIDEO_MPEG4PROFILETYPE; + + +/** + * MPEG-4 level types, each level indicates support for various frame + * sizes, bit rates, decoder frame rates. No need + */ +typedef enum OMX_VIDEO_MPEG4LEVELTYPE { + OMX_VIDEO_MPEG4Level0 = 0x01, /**< Level 0 */ + OMX_VIDEO_MPEG4Level0b = 0x02, /**< Level 0b */ + OMX_VIDEO_MPEG4Level1 = 0x04, /**< Level 1 */ + OMX_VIDEO_MPEG4Level2 = 0x08, /**< Level 2 */ + OMX_VIDEO_MPEG4Level3 = 0x10, /**< Level 3 */ + OMX_VIDEO_MPEG4Level4 = 0x20, /**< Level 4 */ + OMX_VIDEO_MPEG4Level4a = 0x40, /**< Level 4a */ + OMX_VIDEO_MPEG4Level5 = 0x80, /**< Level 5 */ + OMX_VIDEO_MPEG4LevelKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_MPEG4LevelVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_MPEG4LevelMax = 0x7FFFFFFF +} OMX_VIDEO_MPEG4LEVELTYPE; + + +/** + * MPEG-4 configuration. This structure handles configuration options + * which are specific to MPEG4 algorithms + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * nSliceHeaderSpacing : Number of macroblocks between slice header (H263+ + * Annex K). Put zero if not used + * bSVH : Enable Short Video Header mode + * bGov : Flag to enable GOV + * nPFrames : Number of P frames between each I frame (also called + * GOV period) + * nBFrames : Number of B frames between each I frame + * nIDCVLCThreshold : Value of intra DC VLC threshold + * bACPred : Flag to use ac prediction + * nMaxPacketSize : Maximum size of packet in bytes. + * nTimeIncRes : Used to pass VOP time increment resolution for MPEG4. + * Interpreted as described in MPEG4 standard. + * eProfile : MPEG-4 profile(s) to use. + * eLevel : MPEG-4 level(s) to use. + * nAllowedPictureTypes : Specifies the picture types allowed in the bitstream + * nHeaderExtension : Specifies the number of consecutive video packet + * headers within a VOP + * bReversibleVLC : Specifies whether reversible variable length coding + * is in use + */ +typedef struct OMX_VIDEO_PARAM_MPEG4TYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nSliceHeaderSpacing; + OMX_BOOL bSVH; + OMX_BOOL bGov; + OMX_U32 nPFrames; + OMX_U32 nBFrames; + OMX_U32 nIDCVLCThreshold; + OMX_BOOL bACPred; + OMX_U32 nMaxPacketSize; + OMX_U32 nTimeIncRes; + OMX_VIDEO_MPEG4PROFILETYPE eProfile; + OMX_VIDEO_MPEG4LEVELTYPE eLevel; + OMX_U32 nAllowedPictureTypes; + OMX_U32 nHeaderExtension; + OMX_BOOL bReversibleVLC; +} OMX_VIDEO_PARAM_MPEG4TYPE; + + +/** + * WMV Versions + */ +typedef enum OMX_VIDEO_WMVFORMATTYPE { + OMX_VIDEO_WMVFormatUnused = 0x01, /**< Format unused or unknown */ + OMX_VIDEO_WMVFormat7 = 0x02, /**< Windows Media Video format 7 */ + OMX_VIDEO_WMVFormat8 = 0x04, /**< Windows Media Video format 8 */ + OMX_VIDEO_WMVFormat9 = 0x08, /**< Windows Media Video format 9 */ + OMX_VIDEO_WMFFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_WMFFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_WMVFormatMax = 0x7FFFFFFF +} OMX_VIDEO_WMVFORMATTYPE; + + +/** + * WMV Params + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * eFormat : Version of WMV stream / data + */ +typedef struct OMX_VIDEO_PARAM_WMVTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_VIDEO_WMVFORMATTYPE eFormat; +} OMX_VIDEO_PARAM_WMVTYPE; + + +/** + * Real Video Version + */ +typedef enum OMX_VIDEO_RVFORMATTYPE { + OMX_VIDEO_RVFormatUnused = 0, /**< Format unused or unknown */ + OMX_VIDEO_RVFormat8, /**< Real Video format 8 */ + OMX_VIDEO_RVFormat9, /**< Real Video format 9 */ + OMX_VIDEO_RVFormatG2, /**< Real Video Format G2 */ + OMX_VIDEO_RVFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_RVFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_RVFormatMax = 0x7FFFFFFF +} OMX_VIDEO_RVFORMATTYPE; + + +/** + * Real Video Params + * + * STUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * eFormat : Version of RV stream / data + * nBitsPerPixel : Bits per pixel coded in the frame + * nPaddedWidth : Padded width in pixel of a video frame + * nPaddedHeight : Padded Height in pixels of a video frame + * nFrameRate : Rate of video in frames per second + * nBitstreamFlags : Flags which internal information about the bitstream + * nBitstreamVersion : Bitstream version + * nMaxEncodeFrameSize: Max encoded frame size + * bEnablePostFilter : Turn on/off post filter + * bEnableTemporalInterpolation : Turn on/off temporal interpolation + * bEnableLatencyMode : When enabled, the decoder does not display a decoded + * frame until it has detected that no enhancement layer + * frames or dependent B frames will be coming. This + * detection usually occurs when a subsequent non-B + * frame is encountered + */ +typedef struct OMX_VIDEO_PARAM_RVTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_VIDEO_RVFORMATTYPE eFormat; + OMX_U16 nBitsPerPixel; + OMX_U16 nPaddedWidth; + OMX_U16 nPaddedHeight; + OMX_U32 nFrameRate; + OMX_U32 nBitstreamFlags; + OMX_U32 nBitstreamVersion; + OMX_U32 nMaxEncodeFrameSize; + OMX_BOOL bEnablePostFilter; + OMX_BOOL bEnableTemporalInterpolation; + OMX_BOOL bEnableLatencyMode; +} OMX_VIDEO_PARAM_RVTYPE; + + +/** + * AVC profile types, each profile indicates support for various + * performance bounds and different annexes. + */ +typedef enum OMX_VIDEO_AVCPROFILETYPE { + OMX_VIDEO_AVCProfileBaseline = 0x01, /**< Baseline profile */ + OMX_VIDEO_AVCProfileMain = 0x02, /**< Main profile */ + OMX_VIDEO_AVCProfileExtended = 0x04, /**< Extended profile */ + OMX_VIDEO_AVCProfileHigh = 0x08, /**< High profile */ + OMX_VIDEO_AVCProfileHigh10 = 0x10, /**< High 10 profile */ + OMX_VIDEO_AVCProfileHigh422 = 0x20, /**< High 4:2:2 profile */ + OMX_VIDEO_AVCProfileHigh444 = 0x40, /**< High 4:4:4 profile */ + OMX_VIDEO_AVCProfileKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_AVCProfileVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_AVCProfileMax = 0x7FFFFFFF +} OMX_VIDEO_AVCPROFILETYPE; + + +/** + * AVC level types, each level indicates support for various frame sizes, + * bit rates, decoder frame rates. No need + */ +typedef enum OMX_VIDEO_AVCLEVELTYPE { + OMX_VIDEO_AVCLevel1 = 0x01, /**< Level 1 */ + OMX_VIDEO_AVCLevel1b = 0x02, /**< Level 1b */ + OMX_VIDEO_AVCLevel11 = 0x04, /**< Level 1.1 */ + OMX_VIDEO_AVCLevel12 = 0x08, /**< Level 1.2 */ + OMX_VIDEO_AVCLevel13 = 0x10, /**< Level 1.3 */ + OMX_VIDEO_AVCLevel2 = 0x20, /**< Level 2 */ + OMX_VIDEO_AVCLevel21 = 0x40, /**< Level 2.1 */ + OMX_VIDEO_AVCLevel22 = 0x80, /**< Level 2.2 */ + OMX_VIDEO_AVCLevel3 = 0x100, /**< Level 3 */ + OMX_VIDEO_AVCLevel31 = 0x200, /**< Level 3.1 */ + OMX_VIDEO_AVCLevel32 = 0x400, /**< Level 3.2 */ + OMX_VIDEO_AVCLevel4 = 0x800, /**< Level 4 */ + OMX_VIDEO_AVCLevel41 = 0x1000, /**< Level 4.1 */ + OMX_VIDEO_AVCLevel42 = 0x2000, /**< Level 4.2 */ + OMX_VIDEO_AVCLevel5 = 0x4000, /**< Level 5 */ + OMX_VIDEO_AVCLevel51 = 0x8000, /**< Level 5.1 */ + OMX_VIDEO_AVCLevel52 = 0x10000, /**< Level 5.2 */ + OMX_VIDEO_AVCLevelKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_AVCLevelVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_AVCLevelMax = 0x7FFFFFFF +} OMX_VIDEO_AVCLEVELTYPE; + + +/** + * AVC loop filter modes + * + * OMX_VIDEO_AVCLoopFilterEnable : Enable + * OMX_VIDEO_AVCLoopFilterDisable : Disable + * OMX_VIDEO_AVCLoopFilterDisableSliceBoundary : Disabled on slice boundaries + */ +typedef enum OMX_VIDEO_AVCLOOPFILTERTYPE { + OMX_VIDEO_AVCLoopFilterEnable = 0, + OMX_VIDEO_AVCLoopFilterDisable, + OMX_VIDEO_AVCLoopFilterDisableSliceBoundary, + OMX_VIDEO_AVCLoopFilterKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_AVCLoopFilterVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_AVCLoopFilterMax = 0x7FFFFFFF +} OMX_VIDEO_AVCLOOPFILTERTYPE; + + +/** + * AVC params + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * nSliceHeaderSpacing : Number of macroblocks between slice header, put + * zero if not used + * nPFrames : Number of P frames between each I frame + * nBFrames : Number of B frames between each I frame + * bUseHadamard : Enable/disable Hadamard transform + * nRefFrames : Max number of reference frames to use for inter + * motion search (1-16) + * nRefIdxTrailing : Pic param set ref frame index (index into ref + * frame buffer of trailing frames list), B frame + * support + * nRefIdxForward : Pic param set ref frame index (index into ref + * frame buffer of forward frames list), B frame + * support + * bEnableUEP : Enable/disable unequal error protection. This + * is only valid of data partitioning is enabled. + * bEnableFMO : Enable/disable flexible macroblock ordering + * bEnableASO : Enable/disable arbitrary slice ordering + * bEnableRS : Enable/disable sending of redundant slices + * eProfile : AVC profile(s) to use + * eLevel : AVC level(s) to use + * nAllowedPictureTypes : Specifies the picture types allowed in the + * bitstream + * bFrameMBsOnly : specifies that every coded picture of the + * coded video sequence is a coded frame + * containing only frame macroblocks + * bMBAFF : Enable/disable switching between frame and + * field macroblocks within a picture + * bEntropyCodingCABAC : Entropy decoding method to be applied for the + * syntax elements for which two descriptors appear + * in the syntax tables + * bWeightedPPrediction : Enable/disable weighted prediction shall not + * be applied to P and SP slices + * nWeightedBipredicitonMode : Default weighted prediction is applied to B + * slices + * bconstIpred : Enable/disable intra prediction + * bDirect8x8Inference : Specifies the method used in the derivation + * process for luma motion vectors for B_Skip, + * B_Direct_16x16 and B_Direct_8x8 as specified + * in subclause 8.4.1.2 of the AVC spec + * bDirectSpatialTemporal : Flag indicating spatial or temporal direct + * mode used in B slice coding (related to + * bDirect8x8Inference) . Spatial direct mode is + * more common and should be the default. + * nCabacInitIdx : Index used to init CABAC contexts + * eLoopFilterMode : Enable/disable loop filter + */ +typedef struct OMX_VIDEO_PARAM_AVCTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nSliceHeaderSpacing; + OMX_U32 nPFrames; + OMX_U32 nBFrames; + OMX_BOOL bUseHadamard; + OMX_U32 nRefFrames; + OMX_U32 nRefIdx10ActiveMinus1; + OMX_U32 nRefIdx11ActiveMinus1; + OMX_BOOL bEnableUEP; + OMX_BOOL bEnableFMO; + OMX_BOOL bEnableASO; + OMX_BOOL bEnableRS; + OMX_VIDEO_AVCPROFILETYPE eProfile; + OMX_VIDEO_AVCLEVELTYPE eLevel; + OMX_U32 nAllowedPictureTypes; + OMX_BOOL bFrameMBsOnly; + OMX_BOOL bMBAFF; + OMX_BOOL bEntropyCodingCABAC; + OMX_BOOL bWeightedPPrediction; + OMX_U32 nWeightedBipredicitonMode; + OMX_BOOL bconstIpred ; + OMX_BOOL bDirect8x8Inference; + OMX_BOOL bDirectSpatialTemporal; + OMX_U32 nCabacInitIdc; + OMX_VIDEO_AVCLOOPFILTERTYPE eLoopFilterMode; +} OMX_VIDEO_PARAM_AVCTYPE; + +typedef struct OMX_VIDEO_PARAM_PROFILELEVELTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 eProfile; /**< type is OMX_VIDEO_AVCPROFILETYPE, OMX_VIDEO_H263PROFILETYPE, + or OMX_VIDEO_MPEG4PROFILETYPE depending on context */ + OMX_U32 eLevel; /**< type is OMX_VIDEO_AVCLEVELTYPE, OMX_VIDEO_H263LEVELTYPE, + or OMX_VIDEO_MPEG4PROFILETYPE depending on context */ + OMX_U32 nProfileIndex; /**< Used to query for individual profile support information, + This parameter is valid only for + OMX_IndexParamVideoProfileLevelQuerySupported index, + For all other indices this parameter is to be ignored. */ +} OMX_VIDEO_PARAM_PROFILELEVELTYPE; + +/** + * Structure for dynamically configuring bitrate mode of a codec. + * + * STRUCT MEMBERS: + * nSize : Size of the struct in bytes + * nVersion : OMX spec version info + * nPortIndex : Port that this struct applies to + * nEncodeBitrate : Target average bitrate to be generated in bps + */ +typedef struct OMX_VIDEO_CONFIG_BITRATETYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nEncodeBitrate; +} OMX_VIDEO_CONFIG_BITRATETYPE; + +/** + * Defines Encoder Frame Rate setting + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * xEncodeFramerate : Encoding framerate represented in Q16 format + */ +typedef struct OMX_CONFIG_FRAMERATETYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 xEncodeFramerate; /* Q16 format */ +} OMX_CONFIG_FRAMERATETYPE; + +typedef struct OMX_CONFIG_INTRAREFRESHVOPTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL IntraRefreshVOP; +} OMX_CONFIG_INTRAREFRESHVOPTYPE; + +typedef struct OMX_CONFIG_MACROBLOCKERRORMAPTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nErrMapSize; /* Size of the Error Map in bytes */ + OMX_U8 ErrMap[1]; /* Error map hint */ +} OMX_CONFIG_MACROBLOCKERRORMAPTYPE; + +typedef struct OMX_CONFIG_MBERRORREPORTINGTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bEnabled; +} OMX_CONFIG_MBERRORREPORTINGTYPE; + +typedef struct OMX_PARAM_MACROBLOCKSTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nMacroblocks; +} OMX_PARAM_MACROBLOCKSTYPE; + +/** + * AVC Slice Mode modes + * + * OMX_VIDEO_SLICEMODE_AVCDefault : Normal frame encoding, one slice per frame + * OMX_VIDEO_SLICEMODE_AVCMBSlice : NAL mode, number of MBs per frame + * OMX_VIDEO_SLICEMODE_AVCByteSlice : NAL mode, number of bytes per frame + */ +typedef enum OMX_VIDEO_AVCSLICEMODETYPE { + OMX_VIDEO_SLICEMODE_AVCDefault = 0, + OMX_VIDEO_SLICEMODE_AVCMBSlice, + OMX_VIDEO_SLICEMODE_AVCByteSlice, + OMX_VIDEO_SLICEMODE_AVCKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_SLICEMODE_AVCVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_SLICEMODE_AVCLevelMax = 0x7FFFFFFF +} OMX_VIDEO_AVCSLICEMODETYPE; + +/** + * AVC FMO Slice Mode Params + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * nNumSliceGroups : Specifies the number of slice groups + * nSliceGroupMapType : Specifies the type of slice groups + * eSliceMode : Specifies the type of slice + */ +typedef struct OMX_VIDEO_PARAM_AVCSLICEFMO { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U8 nNumSliceGroups; + OMX_U8 nSliceGroupMapType; + OMX_VIDEO_AVCSLICEMODETYPE eSliceMode; +} OMX_VIDEO_PARAM_AVCSLICEFMO; + +/** + * AVC IDR Period Configs + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * nIDRPeriod : Specifies periodicity of IDR frames + * nPFrames : Specifies internal of coding Intra frames + */ +typedef struct OMX_VIDEO_CONFIG_AVCINTRAPERIOD { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nIDRPeriod; + OMX_U32 nPFrames; +} OMX_VIDEO_CONFIG_AVCINTRAPERIOD; + +/** + * AVC NAL Size Configs + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * nNaluBytes : Specifies the NAL unit size + */ +typedef struct OMX_VIDEO_CONFIG_NALSIZE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nNaluBytes; +} OMX_VIDEO_CONFIG_NALSIZE; + +/** @} */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif +/* File EOF */ + diff --git a/phonelibs/android_frameworks_native/include/media/openmax/OMX_VideoExt.h b/phonelibs/android_frameworks_native/include/media/openmax/OMX_VideoExt.h new file mode 100644 index 0000000000..3971bc5cc3 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/media/openmax/OMX_VideoExt.h @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2010 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** OMX_VideoExt.h - OpenMax IL version 1.1.2 + * The OMX_VideoExt header file contains extensions to the + * definitions used by both the application and the component to + * access video items. + */ + +#ifndef OMX_VideoExt_h +#define OMX_VideoExt_h + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* Each OMX header shall include all required header files to allow the + * header to compile without errors. The includes below are required + * for this header file to compile successfully + */ +#include + +/** NALU Formats */ +typedef enum OMX_NALUFORMATSTYPE { + OMX_NaluFormatStartCodes = 1, + OMX_NaluFormatOneNaluPerBuffer = 2, + OMX_NaluFormatOneByteInterleaveLength = 4, + OMX_NaluFormatTwoByteInterleaveLength = 8, + OMX_NaluFormatFourByteInterleaveLength = 16, + OMX_NaluFormatCodingMax = 0x7FFFFFFF +} OMX_NALUFORMATSTYPE; + +/** NAL Stream Format */ +typedef struct OMX_NALSTREAMFORMATTYPE{ + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_NALUFORMATSTYPE eNaluFormat; +} OMX_NALSTREAMFORMATTYPE; + +/** VP8 profiles */ +typedef enum OMX_VIDEO_VP8PROFILETYPE { + OMX_VIDEO_VP8ProfileMain = 0x01, + OMX_VIDEO_VP8ProfileUnknown = 0x6EFFFFFF, + OMX_VIDEO_VP8ProfileMax = 0x7FFFFFFF +} OMX_VIDEO_VP8PROFILETYPE; + +/** VP8 levels */ +typedef enum OMX_VIDEO_VP8LEVELTYPE { + OMX_VIDEO_VP8Level_Version0 = 0x01, + OMX_VIDEO_VP8Level_Version1 = 0x02, + OMX_VIDEO_VP8Level_Version2 = 0x04, + OMX_VIDEO_VP8Level_Version3 = 0x08, + OMX_VIDEO_VP8LevelUnknown = 0x6EFFFFFF, + OMX_VIDEO_VP8LevelMax = 0x7FFFFFFF +} OMX_VIDEO_VP8LEVELTYPE; + +/** VP8 Param */ +typedef struct OMX_VIDEO_PARAM_VP8TYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_VIDEO_VP8PROFILETYPE eProfile; + OMX_VIDEO_VP8LEVELTYPE eLevel; + OMX_U32 nDCTPartitions; + OMX_BOOL bErrorResilientMode; +} OMX_VIDEO_PARAM_VP8TYPE; + +/** Structure for configuring VP8 reference frames */ +typedef struct OMX_VIDEO_VP8REFERENCEFRAMETYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bPreviousFrameRefresh; + OMX_BOOL bGoldenFrameRefresh; + OMX_BOOL bAlternateFrameRefresh; + OMX_BOOL bUsePreviousFrame; + OMX_BOOL bUseGoldenFrame; + OMX_BOOL bUseAlternateFrame; +} OMX_VIDEO_VP8REFERENCEFRAMETYPE; + +/** Structure for querying VP8 reference frame type */ +typedef struct OMX_VIDEO_VP8REFERENCEFRAMEINFOTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bIsIntraFrame; + OMX_BOOL bIsGoldenOrAlternateFrame; +} OMX_VIDEO_VP8REFERENCEFRAMEINFOTYPE; + +/** Maximum number of VP8 temporal layers */ +#define OMX_VIDEO_ANDROID_MAXVP8TEMPORALLAYERS 3 + +/** VP8 temporal layer patterns */ +typedef enum OMX_VIDEO_ANDROID_VPXTEMPORALLAYERPATTERNTYPE { + OMX_VIDEO_VPXTemporalLayerPatternNone = 0, + OMX_VIDEO_VPXTemporalLayerPatternWebRTC = 1, + OMX_VIDEO_VPXTemporalLayerPatternMax = 0x7FFFFFFF +} OMX_VIDEO_ANDROID_VPXTEMPORALLAYERPATTERNTYPE; + +/** + * Android specific VP8 encoder params + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * nKeyFrameInterval : Key frame interval in frames + * eTemporalPattern : Type of temporal layer pattern + * nTemporalLayerCount : Number of temporal coding layers + * nTemporalLayerBitrateRatio : Bitrate ratio allocation between temporal + * streams in percentage + * nMinQuantizer : Minimum (best quality) quantizer + * nMaxQuantizer : Maximum (worst quality) quantizer + */ +typedef struct OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nKeyFrameInterval; + OMX_VIDEO_ANDROID_VPXTEMPORALLAYERPATTERNTYPE eTemporalPattern; + OMX_U32 nTemporalLayerCount; + OMX_U32 nTemporalLayerBitrateRatio[OMX_VIDEO_ANDROID_MAXVP8TEMPORALLAYERS]; + OMX_U32 nMinQuantizer; + OMX_U32 nMaxQuantizer; +} OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE; + +/** HEVC Profile enum type */ +typedef enum OMX_VIDEO_HEVCPROFILETYPE { + OMX_VIDEO_HEVCProfileUnknown = 0x0, + OMX_VIDEO_HEVCProfileMain = 0x1, + OMX_VIDEO_HEVCProfileMain10 = 0x2, + OMX_VIDEO_HEVCProfileMax = 0x7FFFFFFF +} OMX_VIDEO_HEVCPROFILETYPE; + +/** HEVC Level enum type */ +typedef enum OMX_VIDEO_HEVCLEVELTYPE { + OMX_VIDEO_HEVCLevelUnknown = 0x0, + OMX_VIDEO_HEVCMainTierLevel1 = 0x1, + OMX_VIDEO_HEVCHighTierLevel1 = 0x2, + OMX_VIDEO_HEVCMainTierLevel2 = 0x4, + OMX_VIDEO_HEVCHighTierLevel2 = 0x8, + OMX_VIDEO_HEVCMainTierLevel21 = 0x10, + OMX_VIDEO_HEVCHighTierLevel21 = 0x20, + OMX_VIDEO_HEVCMainTierLevel3 = 0x40, + OMX_VIDEO_HEVCHighTierLevel3 = 0x80, + OMX_VIDEO_HEVCMainTierLevel31 = 0x100, + OMX_VIDEO_HEVCHighTierLevel31 = 0x200, + OMX_VIDEO_HEVCMainTierLevel4 = 0x400, + OMX_VIDEO_HEVCHighTierLevel4 = 0x800, + OMX_VIDEO_HEVCMainTierLevel41 = 0x1000, + OMX_VIDEO_HEVCHighTierLevel41 = 0x2000, + OMX_VIDEO_HEVCMainTierLevel5 = 0x4000, + OMX_VIDEO_HEVCHighTierLevel5 = 0x8000, + OMX_VIDEO_HEVCMainTierLevel51 = 0x10000, + OMX_VIDEO_HEVCHighTierLevel51 = 0x20000, + OMX_VIDEO_HEVCMainTierLevel52 = 0x40000, + OMX_VIDEO_HEVCHighTierLevel52 = 0x80000, + OMX_VIDEO_HEVCMainTierLevel6 = 0x100000, + OMX_VIDEO_HEVCHighTierLevel6 = 0x200000, + OMX_VIDEO_HEVCMainTierLevel61 = 0x400000, + OMX_VIDEO_HEVCHighTierLevel61 = 0x800000, + OMX_VIDEO_HEVCMainTierLevel62 = 0x1000000, + OMX_VIDEO_HEVCHighTierLevel62 = 0x2000000, + OMX_VIDEO_HEVCHighTiermax = 0x7FFFFFFF +} OMX_VIDEO_HEVCLEVELTYPE; + +/** Structure for controlling HEVC video encoding and decoding */ +typedef struct OMX_VIDEO_PARAM_HEVCTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_VIDEO_HEVCPROFILETYPE eProfile; + OMX_VIDEO_HEVCLEVELTYPE eLevel; +} OMX_VIDEO_PARAM_HEVCTYPE; + +/** Structure to define if dependent slice segments should be used */ +typedef struct OMX_VIDEO_SLICESEGMENTSTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bDepedentSegments; + OMX_BOOL bEnableLoopFilterAcrossSlices; +} OMX_VIDEO_SLICESEGMENTSTYPE; + +/** Structure to return timestamps of rendered output frames as well as EOS + * for tunneled components. + */ +typedef struct OMX_VIDEO_RENDEREVENTTYPE { + OMX_S64 nMediaTimeUs; // timestamp of rendered video frame + OMX_S64 nSystemTimeNs; // system monotonic time at the time frame was rendered + // Use INT64_MAX for nMediaTimeUs to signal that the EOS + // has been reached. In this case, nSystemTimeNs MUST be + // the system time when the last frame was rendered. + // This MUST be done in addition to returning (and + // following) the render information for the last frame. +} OMX_VIDEO_RENDEREVENTTYPE; + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OMX_VideoExt_h */ +/* File EOF */ diff --git a/phonelibs/android_frameworks_native/include/powermanager/IPowerManager.h b/phonelibs/android_frameworks_native/include/powermanager/IPowerManager.h new file mode 100644 index 0000000000..91ecc5aa31 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/powermanager/IPowerManager.h @@ -0,0 +1,50 @@ +/* + * 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_IPOWERMANAGER_H +#define ANDROID_IPOWERMANAGER_H + +#include +#include +#include + +namespace android { + +// ---------------------------------------------------------------------------- + +// must be kept in sync with interface defined in IPowerManager.aidl +class IPowerManager : public IInterface +{ +public: + DECLARE_META_INTERFACE(PowerManager); + + // FIXME remove the bool isOneWay parameters as they are not oneway in the .aidl + virtual status_t acquireWakeLock(int flags, const sp& lock, const String16& tag, + const String16& packageName, bool isOneWay = false) = 0; + virtual status_t acquireWakeLockWithUid(int flags, const sp& lock, const String16& tag, + const String16& packageName, int uid, bool isOneWay = false) = 0; + virtual status_t releaseWakeLock(const sp& lock, int flags, bool isOneWay = false) = 0; + virtual status_t updateWakeLockUids(const sp& lock, int len, const int *uids, + bool isOneWay = false) = 0; + // oneway in the .aidl + virtual status_t powerHint(int hintId, int data) = 0; +}; + +// ---------------------------------------------------------------------------- + +}; // namespace android + +#endif // ANDROID_IPOWERMANAGER_H diff --git a/phonelibs/android_frameworks_native/include/powermanager/PowerManager.h b/phonelibs/android_frameworks_native/include/powermanager/PowerManager.h new file mode 100644 index 0000000000..cbddc11536 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/powermanager/PowerManager.h @@ -0,0 +1,37 @@ +/* + * 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_POWERMANAGER_H +#define ANDROID_POWERMANAGER_H + +namespace android { + +// must be kept in sync with definitions in PowerManager.java +enum { + POWERMANAGER_PARTIAL_WAKE_LOCK = 1, // equals PowerManager.PARTIAL_WAKE_LOCK constant +}; + +enum { + USER_ACTIVITY_EVENT_OTHER = 0, + USER_ACTIVITY_EVENT_BUTTON = 1, + USER_ACTIVITY_EVENT_TOUCH = 2, + + USER_ACTIVITY_EVENT_LAST = USER_ACTIVITY_EVENT_TOUCH, // Last valid event code. +}; + +}; // namespace android + +#endif // ANDROID_POWERMANAGER_H diff --git a/phonelibs/android_frameworks_native/include/private/binder/Static.h b/phonelibs/android_frameworks_native/include/private/binder/Static.h new file mode 100644 index 0000000000..d104646804 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/private/binder/Static.h @@ -0,0 +1,42 @@ +/* + * 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. + */ + +// All static variables go here, to control initialization and +// destruction order in the library. + +#include + +#include +#include +#include +#include +#include + +namespace android { + +// For TextStream.cpp +extern Vector gTextBuffers; + +// For ProcessState.cpp +extern Mutex gProcessMutex; +extern sp gProcess; + +// For IServiceManager.cpp +extern Mutex gDefaultServiceManagerLock; +extern sp gDefaultServiceManager; +extern sp gPermissionController; + +} // namespace android diff --git a/phonelibs/android_frameworks_native/include/private/binder/binder_module.h b/phonelibs/android_frameworks_native/include/private/binder/binder_module.h new file mode 100644 index 0000000000..a8dd64f235 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/private/binder/binder_module.h @@ -0,0 +1,33 @@ +/* + * 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 _BINDER_MODULE_H_ +#define _BINDER_MODULE_H_ + +#ifdef __cplusplus +namespace android { +#endif + +/* obtain structures and constants from the kernel header */ + +#include +#include + +#ifdef __cplusplus +} // namespace android +#endif + +#endif // _BINDER_MODULE_H_ diff --git a/phonelibs/android_frameworks_native/include/private/gui/ComposerService.h b/phonelibs/android_frameworks_native/include/private/gui/ComposerService.h new file mode 100644 index 0000000000..ff2f9bf0f7 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/private/gui/ComposerService.h @@ -0,0 +1,62 @@ +/* + * 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_PRIVATE_GUI_COMPOSER_SERVICE_H +#define ANDROID_PRIVATE_GUI_COMPOSER_SERVICE_H + +#include +#include + +#include +#include + + +namespace android { + +// --------------------------------------------------------------------------- + +class IMemoryHeap; +class ISurfaceComposer; + +// --------------------------------------------------------------------------- + +// This holds our connection to the composer service (i.e. SurfaceFlinger). +// If the remote side goes away, we will re-establish the connection. +// Users of this class should not retain the value from +// getComposerService() for an extended period. +// +// (It's not clear that using Singleton is useful here anymore.) +class ComposerService : public Singleton +{ + sp mComposerService; + sp mDeathObserver; + Mutex mLock; + + ComposerService(); + void connectLocked(); + void composerServiceDied(); + friend class Singleton; +public: + + // Get a connection to the Composer Service. This will block until + // a connection is established. + static sp getComposerService(); +}; + +// --------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_PRIVATE_GUI_COMPOSER_SERVICE_H diff --git a/phonelibs/android_frameworks_native/include/private/gui/LayerState.h b/phonelibs/android_frameworks_native/include/private/gui/LayerState.h new file mode 100644 index 0000000000..9ff840991f --- /dev/null +++ b/phonelibs/android_frameworks_native/include/private/gui/LayerState.h @@ -0,0 +1,143 @@ +/* + * 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_SF_LAYER_STATE_H +#define ANDROID_SF_LAYER_STATE_H + +#include +#include + +#include + +#include +#include + +namespace android { + +class Parcel; +class ISurfaceComposerClient; + +/* + * Used to communicate layer information between SurfaceFlinger and its clients. + */ +struct layer_state_t { + + + enum { + eLayerHidden = 0x01, // SURFACE_HIDDEN in SurfaceControl.java + eLayerOpaque = 0x02, // SURFACE_OPAQUE + eLayerSecure = 0x80, // SECURE + }; + + enum { + ePositionChanged = 0x00000001, + eLayerChanged = 0x00000002, + eSizeChanged = 0x00000004, + eAlphaChanged = 0x00000008, + eMatrixChanged = 0x00000010, + eTransparentRegionChanged = 0x00000020, + eFlagsChanged = 0x00000040, + eLayerStackChanged = 0x00000080, + eCropChanged = 0x00000100, + eBlurChanged = 0x00400000, + eBlurMaskSurfaceChanged = 0x00800000, + eBlurMaskSamplingChanged = 0x01000000, + eBlurMaskAlphaThresholdChanged = 0x02000000, + }; + + layer_state_t() + : what(0), + x(0), y(0), z(0), w(0), h(0), layerStack(0), blur(0), + blurMaskSampling(0), blurMaskAlphaThreshold(0), alpha(0), flags(0), mask(0), + reserved(0) + { + matrix.dsdx = matrix.dtdy = 1.0f; + matrix.dsdy = matrix.dtdx = 0.0f; + crop.makeInvalid(); + } + + status_t write(Parcel& output) const; + status_t read(const Parcel& input); + + struct matrix22_t { + float dsdx; + float dtdx; + float dsdy; + float dtdy; + }; + sp surface; + uint32_t what; + float x; + float y; + uint32_t z; + uint32_t w; + uint32_t h; + uint32_t layerStack; + float blur; + sp blurMaskSurface; + uint32_t blurMaskSampling; + float blurMaskAlphaThreshold; + float alpha; + uint8_t flags; + uint8_t mask; + uint8_t reserved; + matrix22_t matrix; + Rect crop; + // non POD must be last. see write/read + Region transparentRegion; +}; + +struct ComposerState { + sp client; + layer_state_t state; + status_t write(Parcel& output) const; + status_t read(const Parcel& input); +}; + +struct DisplayState { + + enum { + eOrientationDefault = 0, + eOrientation90 = 1, + eOrientation180 = 2, + eOrientation270 = 3, + eOrientationUnchanged = 4, + eOrientationSwapMask = 0x01 + }; + + enum { + eSurfaceChanged = 0x01, + eLayerStackChanged = 0x02, + eDisplayProjectionChanged = 0x04, + eDisplaySizeChanged = 0x08 + }; + + uint32_t what; + sp token; + sp surface; + uint32_t layerStack; + uint32_t orientation; + Rect viewport; + Rect frame; + uint32_t width, height; + status_t write(Parcel& output) const; + status_t read(const Parcel& input); +}; + +}; // namespace android + +#endif // ANDROID_SF_LAYER_STATE_H + diff --git a/phonelibs/android_frameworks_native/include/private/gui/SyncFeatures.h b/phonelibs/android_frameworks_native/include/private/gui/SyncFeatures.h new file mode 100644 index 0000000000..79fb75bcbe --- /dev/null +++ b/phonelibs/android_frameworks_native/include/private/gui/SyncFeatures.h @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GUI_SYNC_FEATURES_H +#define ANDROID_GUI_SYNC_FEATURES_H + +#include +#include + + +namespace android { +// ---------------------------------------------------------------------------- + +class SyncFeatures : public Singleton { + friend class Singleton; + bool mHasNativeFenceSync; + bool mHasFenceSync; + bool mHasWaitSync; + String8 mString; + SyncFeatures(); + +public: + bool useNativeFenceSync() const; + bool useFenceSync() const; + bool useWaitSync() const; + String8 toString() const; +}; + +// ---------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_GUI_SYNC_FEATURES_H diff --git a/phonelibs/android_frameworks_native/include/private/ui/RegionHelper.h b/phonelibs/android_frameworks_native/include/private/ui/RegionHelper.h new file mode 100644 index 0000000000..8c190dd40b --- /dev/null +++ b/phonelibs/android_frameworks_native/include/private/ui/RegionHelper.h @@ -0,0 +1,301 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_UI_PRIVATE_REGION_HELPER_H +#define ANDROID_UI_PRIVATE_REGION_HELPER_H + +#include +#include + +namespace android { +// ---------------------------------------------------------------------------- + +template +class region_operator +{ +public: + typedef typename RECT::value_type TYPE; + static const TYPE max_value = 0x7FFFFFF; + + /* + * Common boolean operations: + * value is computed as 0b101 op 0b110 + * other boolean operation are possible, simply compute + * their corresponding value with the above formulae and use + * it when instantiating a region_operator. + */ + static const uint32_t LHS = 0x5; // 0b101 + static const uint32_t RHS = 0x6; // 0b110 + enum { + op_nand = LHS & ~RHS, + op_and = LHS & RHS, + op_or = LHS | RHS, + op_xor = LHS ^ RHS + }; + + struct region { + RECT const* rects; + size_t count; + TYPE dx; + TYPE dy; + inline region(const region& rhs) + : rects(rhs.rects), count(rhs.count), dx(rhs.dx), dy(rhs.dy) { } + inline region(RECT const* r, size_t c) + : rects(r), count(c), dx(), dy() { } + inline region(RECT const* r, size_t c, TYPE dx, TYPE dy) + : rects(r), count(c), dx(dx), dy(dy) { } + }; + + class region_rasterizer { + friend class region_operator; + virtual void operator()(const RECT& rect) = 0; + public: + virtual ~region_rasterizer() { }; + }; + + inline region_operator(int op, const region& lhs, const region& rhs) + : op_mask(op), spanner(lhs, rhs) + { + } + + void operator()(region_rasterizer& rasterizer) { + RECT current; + do { + SpannerInner spannerInner(spanner.lhs, spanner.rhs); + int inside = spanner.next(current.top, current.bottom); + spannerInner.prepare(inside); + do { + TYPE left, right; + int inside = spannerInner.next(current.left, current.right); + if ((op_mask >> inside) & 1) { + if (current.left < current.right && + current.top < current.bottom) { + rasterizer(current); + } + } + } while(!spannerInner.isDone()); + } while(!spanner.isDone()); + } + +private: + uint32_t op_mask; + + class SpannerBase + { + public: + SpannerBase() + : lhs_head(max_value), lhs_tail(max_value), + rhs_head(max_value), rhs_tail(max_value) { + } + + enum { + lhs_before_rhs = 0, + lhs_after_rhs = 1, + lhs_coincide_rhs = 2 + }; + + protected: + TYPE lhs_head; + TYPE lhs_tail; + TYPE rhs_head; + TYPE rhs_tail; + + inline int next(TYPE& head, TYPE& tail, + bool& more_lhs, bool& more_rhs) + { + int inside; + more_lhs = false; + more_rhs = false; + if (lhs_head < rhs_head) { + inside = lhs_before_rhs; + head = lhs_head; + if (lhs_tail <= rhs_head) { + tail = lhs_tail; + more_lhs = true; + } else { + lhs_head = rhs_head; + tail = rhs_head; + } + } else if (rhs_head < lhs_head) { + inside = lhs_after_rhs; + head = rhs_head; + if (rhs_tail <= lhs_head) { + tail = rhs_tail; + more_rhs = true; + } else { + rhs_head = lhs_head; + tail = lhs_head; + } + } else { + inside = lhs_coincide_rhs; + head = lhs_head; + if (lhs_tail <= rhs_tail) { + tail = rhs_head = lhs_tail; + more_lhs = true; + } + if (rhs_tail <= lhs_tail) { + tail = lhs_head = rhs_tail; + more_rhs = true; + } + } + return inside; + } + }; + + class Spanner : protected SpannerBase + { + friend class region_operator; + region lhs; + region rhs; + + public: + inline Spanner(const region& lhs, const region& rhs) + : lhs(lhs), rhs(rhs) + { + if (lhs.count) { + SpannerBase::lhs_head = lhs.rects->top + lhs.dy; + SpannerBase::lhs_tail = lhs.rects->bottom + lhs.dy; + } + if (rhs.count) { + SpannerBase::rhs_head = rhs.rects->top + rhs.dy; + SpannerBase::rhs_tail = rhs.rects->bottom + rhs.dy; + } + } + + inline bool isDone() const { + return !rhs.count && !lhs.count; + } + + inline int next(TYPE& top, TYPE& bottom) + { + bool more_lhs = false; + bool more_rhs = false; + int inside = SpannerBase::next(top, bottom, more_lhs, more_rhs); + if (more_lhs) { + advance(lhs, SpannerBase::lhs_head, SpannerBase::lhs_tail); + } + if (more_rhs) { + advance(rhs, SpannerBase::rhs_head, SpannerBase::rhs_tail); + } + return inside; + } + + private: + static inline + void advance(region& reg, TYPE& aTop, TYPE& aBottom) { + // got to next span + size_t count = reg.count; + RECT const * rects = reg.rects; + RECT const * const end = rects + count; + const int top = rects->top; + while (rects != end && rects->top == top) { + rects++; + count--; + } + if (rects != end) { + aTop = rects->top + reg.dy; + aBottom = rects->bottom + reg.dy; + } else { + aTop = max_value; + aBottom = max_value; + } + reg.rects = rects; + reg.count = count; + } + }; + + class SpannerInner : protected SpannerBase + { + region lhs; + region rhs; + + public: + inline SpannerInner(const region& lhs, const region& rhs) + : lhs(lhs), rhs(rhs) + { + } + + inline void prepare(int inside) { + if (inside == SpannerBase::lhs_before_rhs) { + if (lhs.count) { + SpannerBase::lhs_head = lhs.rects->left + lhs.dx; + SpannerBase::lhs_tail = lhs.rects->right + lhs.dx; + } + SpannerBase::rhs_head = max_value; + SpannerBase::rhs_tail = max_value; + } else if (inside == SpannerBase::lhs_after_rhs) { + SpannerBase::lhs_head = max_value; + SpannerBase::lhs_tail = max_value; + if (rhs.count) { + SpannerBase::rhs_head = rhs.rects->left + rhs.dx; + SpannerBase::rhs_tail = rhs.rects->right + rhs.dx; + } + } else { + if (lhs.count) { + SpannerBase::lhs_head = lhs.rects->left + lhs.dx; + SpannerBase::lhs_tail = lhs.rects->right + lhs.dx; + } + if (rhs.count) { + SpannerBase::rhs_head = rhs.rects->left + rhs.dx; + SpannerBase::rhs_tail = rhs.rects->right + rhs.dx; + } + } + } + + inline bool isDone() const { + return SpannerBase::lhs_head == max_value && + SpannerBase::rhs_head == max_value; + } + + inline int next(TYPE& left, TYPE& right) + { + bool more_lhs = false; + bool more_rhs = false; + int inside = SpannerBase::next(left, right, more_lhs, more_rhs); + if (more_lhs) { + advance(lhs, SpannerBase::lhs_head, SpannerBase::lhs_tail); + } + if (more_rhs) { + advance(rhs, SpannerBase::rhs_head, SpannerBase::rhs_tail); + } + return inside; + } + + private: + static inline + void advance(region& reg, TYPE& left, TYPE& right) { + if (reg.rects && reg.count) { + const int cur_span_top = reg.rects->top; + reg.rects++; + reg.count--; + if (!reg.count || reg.rects->top != cur_span_top) { + left = max_value; + right = max_value; + } else { + left = reg.rects->left + reg.dx; + right = reg.rects->right + reg.dx; + } + } + } + }; + + Spanner spanner; +}; + +// ---------------------------------------------------------------------------- +}; + +#endif /* ANDROID_UI_PRIVATE_REGION_HELPER_H */ diff --git a/phonelibs/android_frameworks_native/include/ui/ANativeObjectBase.h b/phonelibs/android_frameworks_native/include/ui/ANativeObjectBase.h new file mode 100644 index 0000000000..76e850fa27 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/ui/ANativeObjectBase.h @@ -0,0 +1,102 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_ANDROID_NATIVES_H +#define ANDROID_ANDROID_NATIVES_H + +#include +#include + +#include +#include + +// --------------------------------------------------------------------------- + +/* FIXME: this is legacy for pixmaps */ +typedef struct egl_native_pixmap_t +{ + int32_t version; /* must be 32 */ + int32_t width; + int32_t height; + int32_t stride; + uint8_t* data; + uint8_t format; + uint8_t rfu[3]; + union { + uint32_t compressedFormat; + int32_t vstride; + }; + int32_t reserved; +} egl_native_pixmap_t; + +/*****************************************************************************/ + +#ifdef __cplusplus + +#include + +namespace android { + +/* + * This helper class turns a ANativeXXX object type into a C++ + * reference-counted object; with proper type conversions. + */ +template +class ANativeObjectBase : public NATIVE_TYPE, public REF +{ +public: + // Disambiguate between the incStrong in REF and NATIVE_TYPE + void incStrong(const void* id) const { + REF::incStrong(id); + } + void decStrong(const void* id) const { + REF::decStrong(id); + } + +protected: + typedef ANativeObjectBase BASE; + ANativeObjectBase() : NATIVE_TYPE(), REF() { + NATIVE_TYPE::common.incRef = incRef; + NATIVE_TYPE::common.decRef = decRef; + } + static inline TYPE* getSelf(NATIVE_TYPE* self) { + return static_cast(self); + } + static inline TYPE const* getSelf(NATIVE_TYPE const* self) { + return static_cast(self); + } + static inline TYPE* getSelf(android_native_base_t* base) { + return getSelf(reinterpret_cast(base)); + } + static inline TYPE const * getSelf(android_native_base_t const* base) { + return getSelf(reinterpret_cast(base)); + } + static void incRef(android_native_base_t* base) { + ANativeObjectBase* self = getSelf(base); + self->incStrong(self); + } + static void decRef(android_native_base_t* base) { + ANativeObjectBase* self = getSelf(base); + self->decStrong(self); + } +}; + +} // namespace android +#endif // __cplusplus + +/*****************************************************************************/ + +#endif /* ANDROID_ANDROID_NATIVES_H */ diff --git a/phonelibs/android_frameworks_native/include/ui/DisplayInfo.h b/phonelibs/android_frameworks_native/include/ui/DisplayInfo.h new file mode 100644 index 0000000000..ad73ee72f9 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/ui/DisplayInfo.h @@ -0,0 +1,52 @@ +/* + * 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_UI_DISPLAY_INFO_H +#define ANDROID_UI_DISPLAY_INFO_H + +#include +#include +#include + +#include + +namespace android { + +struct DisplayInfo { + uint32_t w; + uint32_t h; + float xdpi; + float ydpi; + float fps; + float density; + uint8_t orientation; + bool secure; + nsecs_t appVsyncOffset; + nsecs_t presentationDeadline; + int colorTransform; +}; + +/* Display orientations as defined in Surface.java and ISurfaceComposer.h. */ +enum { + DISPLAY_ORIENTATION_0 = 0, + DISPLAY_ORIENTATION_90 = 1, + DISPLAY_ORIENTATION_180 = 2, + DISPLAY_ORIENTATION_270 = 3 +}; + +}; // namespace android + +#endif // ANDROID_COMPOSER_DISPLAY_INFO_H diff --git a/phonelibs/android_frameworks_native/include/ui/DisplayStatInfo.h b/phonelibs/android_frameworks_native/include/ui/DisplayStatInfo.h new file mode 100644 index 0000000000..0549a832b5 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/ui/DisplayStatInfo.h @@ -0,0 +1,31 @@ +/* + * 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_UI_DISPLAY_STAT_INFO_H +#define ANDROID_UI_DISPLAY_STAT_INFO_H + +#include + +namespace android { + +struct DisplayStatInfo { + nsecs_t vsyncTime; + nsecs_t vsyncPeriod; +}; + +}; // namespace android + +#endif // ANDROID_COMPOSER_DISPLAY_STAT_INFO_H diff --git a/phonelibs/android_frameworks_native/include/ui/Fence.h b/phonelibs/android_frameworks_native/include/ui/Fence.h new file mode 100644 index 0000000000..b431bd52aa --- /dev/null +++ b/phonelibs/android_frameworks_native/include/ui/Fence.h @@ -0,0 +1,117 @@ +/* + * 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_FENCE_H +#define ANDROID_FENCE_H + +#include +#include + +#include +#include +#include +#include +#include +#include + +struct ANativeWindowBuffer; + +namespace android { + +// =========================================================================== +// Fence +// =========================================================================== + +class Fence + : public LightRefBase, public Flattenable +{ +public: + static const sp NO_FENCE; + + // TIMEOUT_NEVER may be passed to the wait method to indicate that it + // should wait indefinitely for the fence to signal. + enum { TIMEOUT_NEVER = -1 }; + + // Construct a new Fence object with an invalid file descriptor. This + // should be done when the Fence object will be set up by unflattening + // serialized data. + Fence(); + + // Construct a new Fence object to manage a given fence file descriptor. + // When the new Fence object is destructed the file descriptor will be + // closed. + Fence(int fenceFd); + + // Check whether the Fence has an open fence file descriptor. Most Fence + // methods treat an invalid file descriptor just like a valid fence that + // is already signalled, so using this is usually not necessary. + bool isValid() const { return mFenceFd != -1; } + + // wait waits for up to timeout milliseconds for the fence to signal. If + // the fence signals then NO_ERROR is returned. If the timeout expires + // before the fence signals then -ETIME is returned. A timeout of + // TIMEOUT_NEVER may be used to indicate that the call should wait + // indefinitely for the fence to signal. + status_t wait(int timeout); + + // waitForever is a convenience function for waiting forever for a fence to + // signal (just like wait(TIMEOUT_NEVER)), but issuing an error to the + // system log and fence state to the kernel log if the wait lasts longer + // than a warning timeout. + // The logname argument should be a string identifying + // the caller and will be included in the log message. + status_t waitForever(const char* logname); + + // merge combines two Fence objects, creating a new Fence object that + // becomes signaled when both f1 and f2 are signaled (even if f1 or f2 is + // destroyed before it becomes signaled). The name argument specifies the + // human-readable name to associated with the new Fence object. + static sp merge(const String8& name, const sp& f1, + const sp& f2); + + // Return a duplicate of the fence file descriptor. The caller is + // responsible for closing the returned file descriptor. On error, -1 will + // be returned and errno will indicate the problem. + int dup() const; + + // getSignalTime returns the system monotonic clock time at which the + // fence transitioned to the signaled state. If the fence is not signaled + // then INT64_MAX is returned. If the fence is invalid or if an error + // occurs then -1 is returned. + nsecs_t getSignalTime() const; + + // Flattenable interface + 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); + +private: + // Only allow instantiation using ref counting. + friend class LightRefBase; + ~Fence(); + + // Disallow copying + Fence(const Fence& rhs); + Fence& operator = (const Fence& rhs); + const Fence& operator = (const Fence& rhs) const; + + int mFenceFd; +}; + +}; // namespace android + +#endif // ANDROID_FENCE_H diff --git a/phonelibs/android_frameworks_native/include/ui/FrameStats.h b/phonelibs/android_frameworks_native/include/ui/FrameStats.h new file mode 100644 index 0000000000..6bfe635c72 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/ui/FrameStats.h @@ -0,0 +1,64 @@ +/* + * Copyright (C) 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_UI_FRAME_STATS_H +#define ANDROID_UI_FRAME_STATS_H + +#include +#include +#include + +namespace android { + +class FrameStats : public LightFlattenable { +public: + FrameStats() : refreshPeriodNano(0) {}; + + /* + * Approximate refresh time, in nanoseconds. + */ + nsecs_t refreshPeriodNano; + + /* + * The times in nanoseconds for when the frame contents were posted by the producer (e.g. + * the application). They are either explicitly set or defaulted to the time when + * Surface::queueBuffer() was called. + */ + Vector desiredPresentTimesNano; + + /* + * The times in milliseconds for when the frame contents were presented on the screen. + */ + Vector actualPresentTimesNano; + + /* + * The times in nanoseconds for when the frame contents were ready to be presented. Note that + * a frame can be posted and still it contents being rendered asynchronously in GL. In such a + * case these are the times when the frame contents were completely rendered (i.e. their fences + * signaled). + */ + Vector frameReadyTimesNano; + + // LightFlattenable + bool isFixedSize() const; + size_t getFlattenedSize() const; + status_t flatten(void* buffer, size_t size) const; + status_t unflatten(void const* buffer, size_t size); +}; + +}; // namespace android + +#endif // ANDROID_UI_FRAME_STATS_H diff --git a/phonelibs/android_frameworks_native/include/ui/FramebufferNativeWindow.h b/phonelibs/android_frameworks_native/include/ui/FramebufferNativeWindow.h new file mode 100644 index 0000000000..6b66d5f66b --- /dev/null +++ b/phonelibs/android_frameworks_native/include/ui/FramebufferNativeWindow.h @@ -0,0 +1,102 @@ +/* + * 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 INCLUDED_FROM_FRAMEBUFFER_NATIVE_WINDOW_CPP +#warning "FramebufferNativeWindow is deprecated" +#endif + +#ifndef ANDROID_FRAMEBUFFER_NATIVE_WINDOW_H +#define ANDROID_FRAMEBUFFER_NATIVE_WINDOW_H + +#include +#include + +#include + +#include +#include + +#include +#include + +#define MIN_NUM_FRAME_BUFFERS 2 +#define MAX_NUM_FRAME_BUFFERS 3 + +extern "C" EGLNativeWindowType android_createDisplaySurface(void); + +// --------------------------------------------------------------------------- +namespace android { +// --------------------------------------------------------------------------- + +class Surface; +class NativeBuffer; + +// --------------------------------------------------------------------------- + +class FramebufferNativeWindow + : public ANativeObjectBase< + ANativeWindow, + FramebufferNativeWindow, + LightRefBase > +{ +public: + FramebufferNativeWindow(); + + framebuffer_device_t const * getDevice() const { return fbDev; } + + bool isUpdateOnDemand() const { return mUpdateOnDemand; } + status_t setUpdateRectangle(const Rect& updateRect); + status_t compositionComplete(); + + void dump(String8& result); + + // for debugging only + int getCurrentBufferIndex() const; + +private: + friend class LightRefBase; + ~FramebufferNativeWindow(); // this class cannot be overloaded + static int setSwapInterval(ANativeWindow* window, int interval); + static int dequeueBuffer(ANativeWindow* window, ANativeWindowBuffer** buffer, int* fenceFd); + static int queueBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd); + static int query(const ANativeWindow* window, int what, int* value); + static int perform(ANativeWindow* window, int operation, ...); + + static int dequeueBuffer_DEPRECATED(ANativeWindow* window, ANativeWindowBuffer** buffer); + static int queueBuffer_DEPRECATED(ANativeWindow* window, ANativeWindowBuffer* buffer); + static int lockBuffer_DEPRECATED(ANativeWindow* window, ANativeWindowBuffer* buffer); + + framebuffer_device_t* fbDev; + alloc_device_t* grDev; + + sp buffers[MAX_NUM_FRAME_BUFFERS]; + sp front; + + mutable Mutex mutex; + Condition mCondition; + int32_t mNumBuffers; + int32_t mNumFreeBuffers; + int32_t mBufferHead; + int32_t mCurrentBufferIndex; + bool mUpdateOnDemand; +}; + +// --------------------------------------------------------------------------- +}; // namespace android +// --------------------------------------------------------------------------- + +#endif // ANDROID_FRAMEBUFFER_NATIVE_WINDOW_H + diff --git a/phonelibs/android_frameworks_native/include/ui/GraphicBuffer.h b/phonelibs/android_frameworks_native/include/ui/GraphicBuffer.h new file mode 100644 index 0000000000..3da720ff37 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/ui/GraphicBuffer.h @@ -0,0 +1,183 @@ +/* + * 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_GRAPHIC_BUFFER_H +#define ANDROID_GRAPHIC_BUFFER_H + +#include +#include + +#include +#include +#include +#include +#include + + +struct ANativeWindowBuffer; + +namespace android { + +class GraphicBufferMapper; + +// =========================================================================== +// GraphicBuffer +// =========================================================================== + +class GraphicBuffer + : public ANativeObjectBase< ANativeWindowBuffer, GraphicBuffer, RefBase >, + public Flattenable +{ + friend class Flattenable; +public: + + enum { + USAGE_SW_READ_NEVER = GRALLOC_USAGE_SW_READ_NEVER, + USAGE_SW_READ_RARELY = GRALLOC_USAGE_SW_READ_RARELY, + USAGE_SW_READ_OFTEN = GRALLOC_USAGE_SW_READ_OFTEN, + USAGE_SW_READ_MASK = GRALLOC_USAGE_SW_READ_MASK, + + USAGE_SW_WRITE_NEVER = GRALLOC_USAGE_SW_WRITE_NEVER, + USAGE_SW_WRITE_RARELY = GRALLOC_USAGE_SW_WRITE_RARELY, + USAGE_SW_WRITE_OFTEN = GRALLOC_USAGE_SW_WRITE_OFTEN, + USAGE_SW_WRITE_MASK = GRALLOC_USAGE_SW_WRITE_MASK, + + USAGE_SOFTWARE_MASK = USAGE_SW_READ_MASK|USAGE_SW_WRITE_MASK, + + USAGE_PROTECTED = GRALLOC_USAGE_PROTECTED, + + USAGE_HW_TEXTURE = GRALLOC_USAGE_HW_TEXTURE, + USAGE_HW_RENDER = GRALLOC_USAGE_HW_RENDER, + USAGE_HW_2D = GRALLOC_USAGE_HW_2D, + USAGE_HW_COMPOSER = GRALLOC_USAGE_HW_COMPOSER, + USAGE_HW_VIDEO_ENCODER = GRALLOC_USAGE_HW_VIDEO_ENCODER, + USAGE_HW_MASK = GRALLOC_USAGE_HW_MASK, + + USAGE_CURSOR = GRALLOC_USAGE_CURSOR, + }; + + GraphicBuffer(); + + // creates w * h buffer + GraphicBuffer(uint32_t inWidth, uint32_t inHeight, PixelFormat inFormat, + uint32_t inUsage); + + // create a buffer from an existing handle + GraphicBuffer(uint32_t inWidth, uint32_t inHeight, PixelFormat inFormat, + uint32_t inUsage, uint32_t inStride, native_handle_t* inHandle, + bool keepOwnership); + + // create a buffer from an existing ANativeWindowBuffer + GraphicBuffer(ANativeWindowBuffer* buffer, bool keepOwnership); + + // return status + status_t initCheck() const; + + uint32_t getWidth() const { return static_cast(width); } + uint32_t getHeight() const { return static_cast(height); } + uint32_t getStride() const { return static_cast(stride); } + uint32_t getUsage() const { return static_cast(usage); } + PixelFormat getPixelFormat() const { return format; } + Rect getBounds() const { return Rect(width, height); } + uint64_t getId() const { return mId; } + + uint32_t getGenerationNumber() const { return mGenerationNumber; } + void setGenerationNumber(uint32_t generation) { + mGenerationNumber = generation; + } + + status_t reallocate(uint32_t inWidth, uint32_t inHeight, + PixelFormat inFormat, uint32_t inUsage); + + bool needsReallocation(uint32_t inWidth, uint32_t inHeight, + PixelFormat inFormat, uint32_t inUsage); + + status_t lock(uint32_t inUsage, void** vaddr); + status_t lock(uint32_t inUsage, const Rect& rect, void** vaddr); + // For HAL_PIXEL_FORMAT_YCbCr_420_888 + status_t lockYCbCr(uint32_t inUsage, android_ycbcr *ycbcr); + status_t lockYCbCr(uint32_t inUsage, const Rect& rect, + android_ycbcr *ycbcr); + status_t unlock(); + status_t lockAsync(uint32_t inUsage, void** vaddr, int fenceFd); + status_t lockAsync(uint32_t inUsage, const Rect& rect, void** vaddr, + int fenceFd); + status_t lockAsyncYCbCr(uint32_t inUsage, android_ycbcr *ycbcr, + int fenceFd); + status_t lockAsyncYCbCr(uint32_t inUsage, const Rect& rect, + android_ycbcr *ycbcr, int fenceFd); + status_t unlockAsync(int *fenceFd); + + ANativeWindowBuffer* getNativeBuffer() const; + + // for debugging + static void dumpAllocationsToSystemLog(); + + // 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); + +private: + ~GraphicBuffer(); + + enum { + ownNone = 0, + ownHandle = 1, + ownData = 2, + }; + + inline const GraphicBufferMapper& getBufferMapper() const { + return mBufferMapper; + } + inline GraphicBufferMapper& getBufferMapper() { + return mBufferMapper; + } + uint8_t mOwner; + +private: + friend class Surface; + friend class BpSurface; + friend class BnSurface; + friend class LightRefBase; + GraphicBuffer(const GraphicBuffer& rhs); + GraphicBuffer& operator = (const GraphicBuffer& rhs); + const GraphicBuffer& operator = (const GraphicBuffer& rhs) const; + + status_t initSize(uint32_t inWidth, uint32_t inHeight, PixelFormat inFormat, + uint32_t inUsage); + + void free_handle(); + + GraphicBufferMapper& mBufferMapper; + ssize_t mInitCheck; + + // If we're wrapping another buffer then this reference will make sure it + // doesn't get freed. + sp mWrappedBuffer; + + uint64_t mId; + + // Stores the generation number of this buffer. If this number does not + // match the BufferQueue's internal generation number (set through + // IGBP::setGenerationNumber), attempts to attach the buffer will fail. + uint32_t mGenerationNumber; +}; + +}; // namespace android + +#endif // ANDROID_GRAPHIC_BUFFER_H diff --git a/phonelibs/android_frameworks_native/include/ui/GraphicBufferAllocator.h b/phonelibs/android_frameworks_native/include/ui/GraphicBufferAllocator.h new file mode 100644 index 0000000000..5443f09a10 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/ui/GraphicBufferAllocator.h @@ -0,0 +1,95 @@ +/* +** +** Copyright 2009, The Android Open Source Project +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +*/ + +#ifndef ANDROID_BUFFER_ALLOCATOR_H +#define ANDROID_BUFFER_ALLOCATOR_H + +#include + +#include + +#include +#include +#include +#include + +#include + +#include + + +namespace android { +// --------------------------------------------------------------------------- + +class String8; + +class GraphicBufferAllocator : public Singleton +{ +public: + enum { + USAGE_SW_READ_NEVER = GRALLOC_USAGE_SW_READ_NEVER, + USAGE_SW_READ_RARELY = GRALLOC_USAGE_SW_READ_RARELY, + USAGE_SW_READ_OFTEN = GRALLOC_USAGE_SW_READ_OFTEN, + USAGE_SW_READ_MASK = GRALLOC_USAGE_SW_READ_MASK, + + USAGE_SW_WRITE_NEVER = GRALLOC_USAGE_SW_WRITE_NEVER, + USAGE_SW_WRITE_RARELY = GRALLOC_USAGE_SW_WRITE_RARELY, + USAGE_SW_WRITE_OFTEN = GRALLOC_USAGE_SW_WRITE_OFTEN, + USAGE_SW_WRITE_MASK = GRALLOC_USAGE_SW_WRITE_MASK, + + USAGE_SOFTWARE_MASK = USAGE_SW_READ_MASK|USAGE_SW_WRITE_MASK, + + USAGE_HW_TEXTURE = GRALLOC_USAGE_HW_TEXTURE, + USAGE_HW_RENDER = GRALLOC_USAGE_HW_RENDER, + USAGE_HW_2D = GRALLOC_USAGE_HW_2D, + USAGE_HW_MASK = GRALLOC_USAGE_HW_MASK + }; + + static inline GraphicBufferAllocator& get() { return getInstance(); } + + status_t alloc(uint32_t w, uint32_t h, PixelFormat format, uint32_t usage, + buffer_handle_t* handle, uint32_t* stride); + + status_t free(buffer_handle_t handle); + + void dump(String8& res) const; + static void dumpToSystemLog(); + +private: + struct alloc_rec_t { + uint32_t width; + uint32_t height; + uint32_t stride; + PixelFormat format; + uint32_t usage; + size_t size; + }; + + static Mutex sLock; + static KeyedVector sAllocList; + + friend class Singleton; + GraphicBufferAllocator(); + ~GraphicBufferAllocator(); + + alloc_device_t *mAllocDev; +}; + +// --------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_BUFFER_ALLOCATOR_H diff --git a/phonelibs/android_frameworks_native/include/ui/GraphicBufferMapper.h b/phonelibs/android_frameworks_native/include/ui/GraphicBufferMapper.h new file mode 100644 index 0000000000..9900624827 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/ui/GraphicBufferMapper.h @@ -0,0 +1,80 @@ +/* + * 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_UI_BUFFER_MAPPER_H +#define ANDROID_UI_BUFFER_MAPPER_H + +#include +#include + +#include + +#include + + +struct gralloc_module_t; + +namespace android { + +// --------------------------------------------------------------------------- + +class Rect; + +class GraphicBufferMapper : public Singleton +{ +public: + static inline GraphicBufferMapper& get() { return getInstance(); } + + status_t registerBuffer(buffer_handle_t handle); + + status_t unregisterBuffer(buffer_handle_t handle); + + status_t lock(buffer_handle_t handle, + uint32_t usage, const Rect& bounds, void** vaddr); + + status_t lockYCbCr(buffer_handle_t handle, + uint32_t usage, const Rect& bounds, android_ycbcr *ycbcr); + + status_t unlock(buffer_handle_t handle); + + status_t lockAsync(buffer_handle_t handle, + uint32_t usage, const Rect& bounds, void** vaddr, int fenceFd); + + status_t lockAsyncYCbCr(buffer_handle_t handle, + uint32_t usage, const Rect& bounds, android_ycbcr *ycbcr, + int fenceFd); + + status_t unlockAsync(buffer_handle_t handle, int *fenceFd); + +#ifdef EXYNOS4_ENHANCEMENTS + status_t getphys(buffer_handle_t handle, void** paddr); +#endif + + // dumps information about the mapping of this handle + void dump(buffer_handle_t handle); + +private: + friend class Singleton; + GraphicBufferMapper(); + gralloc_module_t const *mAllocMod; +}; + +// --------------------------------------------------------------------------- + +}; // namespace android + +#endif // ANDROID_UI_BUFFER_MAPPER_H + diff --git a/phonelibs/android_frameworks_native/include/ui/PixelFormat.h b/phonelibs/android_frameworks_native/include/ui/PixelFormat.h new file mode 100644 index 0000000000..f26fecb8b1 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/ui/PixelFormat.h @@ -0,0 +1,72 @@ +/* + * 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. + */ + +// + +// Pixel formats used across the system. +// These formats might not all be supported by all renderers, for instance +// skia or SurfaceFlinger are not required to support all of these formats +// (either as source or destination) + + +#ifndef UI_PIXELFORMAT_H +#define UI_PIXELFORMAT_H + +#include + +namespace android { + +enum { + // + // these constants need to match those + // in graphics/PixelFormat.java & pixelflinger/format.h + // + PIXEL_FORMAT_UNKNOWN = 0, + PIXEL_FORMAT_NONE = 0, + + // logical pixel formats used by the SurfaceFlinger ----------------------- + PIXEL_FORMAT_CUSTOM = -4, + // Custom pixel-format described by a PixelFormatInfo structure + + PIXEL_FORMAT_TRANSLUCENT = -3, + // System chooses a format that supports translucency (many alpha bits) + + PIXEL_FORMAT_TRANSPARENT = -2, + // System chooses a format that supports transparency + // (at least 1 alpha bit) + + PIXEL_FORMAT_OPAQUE = -1, + // System chooses an opaque format (no alpha bits required) + + // real pixel formats supported for rendering ----------------------------- + + PIXEL_FORMAT_RGBA_8888 = HAL_PIXEL_FORMAT_RGBA_8888, // 4x8-bit RGBA + PIXEL_FORMAT_RGBX_8888 = HAL_PIXEL_FORMAT_RGBX_8888, // 4x8-bit RGB0 + PIXEL_FORMAT_RGB_888 = HAL_PIXEL_FORMAT_RGB_888, // 3x8-bit RGB + PIXEL_FORMAT_RGB_565 = HAL_PIXEL_FORMAT_RGB_565, // 16-bit RGB + PIXEL_FORMAT_BGRA_8888 = HAL_PIXEL_FORMAT_BGRA_8888, // 4x8-bit BGRA + PIXEL_FORMAT_RGBA_5551 = 6, // 16-bit ARGB + PIXEL_FORMAT_RGBA_4444 = 7, // 16-bit ARGB +}; + +typedef int32_t PixelFormat; + +uint32_t bytesPerPixel(PixelFormat format); +uint32_t bitsPerPixel(PixelFormat format); + +}; // namespace android + +#endif // UI_PIXELFORMAT_H diff --git a/phonelibs/android_frameworks_native/include/ui/Point.h b/phonelibs/android_frameworks_native/include/ui/Point.h new file mode 100644 index 0000000000..1d7f64d307 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/ui/Point.h @@ -0,0 +1,88 @@ +/* + * 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_UI_POINT +#define ANDROID_UI_POINT + +#include +#include + +namespace android { + +class Point : public LightFlattenablePod +{ +public: + int x; + int y; + + // we don't provide copy-ctor and operator= on purpose + // because we want the compiler generated versions + + // Default constructor doesn't initialize the Point + inline Point() { + } + inline Point(int x, int y) : x(x), y(y) { + } + + inline bool operator == (const Point& rhs) const { + return (x == rhs.x) && (y == rhs.y); + } + inline bool operator != (const Point& rhs) const { + return !operator == (rhs); + } + + inline bool isOrigin() const { + return !(x|y); + } + + // operator < defines an order which allows to use points in sorted + // vectors. + bool operator < (const Point& rhs) const { + return y +#include +#include +#include + +#include + +namespace android { + +class Rect : public ARect, public LightFlattenablePod +{ +public: + typedef ARect::value_type value_type; + + static const Rect INVALID_RECT; + + // we don't provide copy-ctor and operator= on purpose + // because we want the compiler generated versions + + inline Rect() { + left = right = top = bottom = 0; + } + + inline Rect(int32_t w, int32_t h) { + left = top = 0; + right = w; + bottom = h; + } + + inline Rect(uint32_t w, uint32_t h) { + if (w > INT32_MAX) { + ALOG(LOG_WARN, "Rect", + "Width %u too large for Rect class, clamping", w); + w = INT32_MAX; + } + if (h > INT32_MAX) { + ALOG(LOG_WARN, "Rect", + "Height %u too large for Rect class, clamping", h); + h = INT32_MAX; + } + left = top = 0; + right = w; + bottom = h; + } + + inline Rect(int32_t l, int32_t t, int32_t r, int32_t b) { + left = l; + top = t; + right = r; + bottom = b; + } + + inline Rect(const Point& lt, const Point& rb) { + left = lt.x; + top = lt.y; + right = rb.x; + bottom = rb.y; + } + + void makeInvalid(); + + inline void clear() { + left = top = right = bottom = 0; + } + + // a valid rectangle has a non negative width and height + inline bool isValid() const { + return (getWidth() >= 0) && (getHeight() >= 0); + } + + // an empty rect has a zero width or height, or is invalid + inline bool isEmpty() const { + return (getWidth() <= 0) || (getHeight() <= 0); + } + + // rectangle's width + inline int32_t getWidth() const { + return right - left; + } + + // rectangle's height + inline int32_t getHeight() const { + return bottom - top; + } + + inline Rect getBounds() const { + return Rect(right - left, bottom - top); + } + + void setLeftTop(const Point& lt) { + left = lt.x; + top = lt.y; + } + + void setRightBottom(const Point& rb) { + right = rb.x; + bottom = rb.y; + } + + // the following 4 functions return the 4 corners of the rect as Point + Point leftTop() const { + return Point(left, top); + } + Point rightBottom() const { + return Point(right, bottom); + } + Point rightTop() const { + return Point(right, top); + } + Point leftBottom() const { + return Point(left, bottom); + } + + // comparisons + inline bool operator == (const Rect& rhs) const { + return (left == rhs.left) && (top == rhs.top) && + (right == rhs.right) && (bottom == rhs.bottom); + } + + inline bool operator != (const Rect& rhs) const { + return !operator == (rhs); + } + + // operator < defines an order which allows to use rectangles in sorted + // vectors. + bool operator < (const Rect& rhs) const; + + const Rect operator + (const Point& rhs) const; + const Rect operator - (const Point& rhs) const; + + Rect& operator += (const Point& rhs) { + return offsetBy(rhs.x, rhs.y); + } + Rect& operator -= (const Point& rhs) { + return offsetBy(-rhs.x, -rhs.y); + } + + Rect& offsetToOrigin() { + right -= left; + bottom -= top; + left = top = 0; + return *this; + } + Rect& offsetTo(const Point& p) { + return offsetTo(p.x, p.y); + } + Rect& offsetBy(const Point& dp) { + return offsetBy(dp.x, dp.y); + } + + Rect& offsetTo(int32_t x, int32_t y); + Rect& offsetBy(int32_t x, int32_t y); + + bool intersect(const Rect& with, Rect* result) const; + + // Create a new Rect by transforming this one using a graphics HAL + // transform. This rectangle is defined in a coordinate space starting at + // the origin and extending to (width, height). If the transform includes + // a ROT90 then the output rectangle is defined in a space extending to + // (height, width). Otherwise the output rectangle is in the same space as + // the input. + Rect transform(uint32_t xform, int32_t width, int32_t height) const; + + // this calculates (Region(*this) - exclude).bounds() efficiently + Rect reduce(const Rect& exclude) const; + + + // for backward compatibility + inline int32_t width() const { return getWidth(); } + inline int32_t height() const { return getHeight(); } + inline void set(const Rect& rhs) { operator = (rhs); } +}; + +ANDROID_BASIC_TYPES_TRAITS(Rect) + +}; // namespace android + +#endif // ANDROID_UI_RECT diff --git a/phonelibs/android_frameworks_native/include/ui/Region.h b/phonelibs/android_frameworks_native/include/ui/Region.h new file mode 100644 index 0000000000..2a1491837d --- /dev/null +++ b/phonelibs/android_frameworks_native/include/ui/Region.h @@ -0,0 +1,223 @@ +/* + * 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_UI_REGION_H +#define ANDROID_UI_REGION_H + +#include +#include + +#include + +#include +#include + +namespace android { +// --------------------------------------------------------------------------- + +class SharedBuffer; +class String8; + +// --------------------------------------------------------------------------- +class Region : public LightFlattenable +{ +public: + static const Region INVALID_REGION; + + Region(); + Region(const Region& rhs); + explicit Region(const Rect& rhs); + ~Region(); + + static Region createTJunctionFreeRegion(const Region& r); + + Region& operator = (const Region& rhs); + + inline bool isEmpty() const { return getBounds().isEmpty(); } + inline bool isRect() const { return mStorage.size() == 1; } + + inline Rect getBounds() const { return mStorage[mStorage.size() - 1]; } + inline Rect bounds() const { return getBounds(); } + + bool contains(const Point& point) const; + bool contains(int x, int y) const; + + // the region becomes its bounds + Region& makeBoundsSelf(); + + void clear(); + void set(const Rect& r); + void set(int32_t w, int32_t h); + void set(uint32_t w, uint32_t h); + + Region& orSelf(const Rect& rhs); + Region& xorSelf(const Rect& rhs); + Region& andSelf(const Rect& rhs); + Region& subtractSelf(const Rect& rhs); + + // boolean operators, applied on this + Region& orSelf(const Region& rhs); + Region& xorSelf(const Region& rhs); + Region& andSelf(const Region& rhs); + Region& subtractSelf(const Region& rhs); + + // boolean operators + const Region merge(const Rect& rhs) const; + const Region mergeExclusive(const Rect& rhs) const; + const Region intersect(const Rect& rhs) const; + const Region subtract(const Rect& rhs) const; + + // boolean operators + const Region merge(const Region& rhs) const; + const Region mergeExclusive(const Region& rhs) const; + const Region intersect(const Region& rhs) const; + const Region subtract(const Region& rhs) const; + + // these translate rhs first + Region& translateSelf(int dx, int dy); + Region& orSelf(const Region& rhs, int dx, int dy); + Region& xorSelf(const Region& rhs, int dx, int dy); + Region& andSelf(const Region& rhs, int dx, int dy); + Region& subtractSelf(const Region& rhs, int dx, int dy); + + // these translate rhs first + const Region translate(int dx, int dy) const; + const Region merge(const Region& rhs, int dx, int dy) const; + const Region mergeExclusive(const Region& rhs, int dx, int dy) const; + const Region intersect(const Region& rhs, int dx, int dy) const; + const Region subtract(const Region& rhs, int dx, int dy) const; + + // convenience operators overloads + inline const Region operator | (const Region& rhs) const; + inline const Region operator ^ (const Region& rhs) const; + inline const Region operator & (const Region& rhs) const; + inline const Region operator - (const Region& rhs) const; + inline const Region operator + (const Point& pt) const; + + inline Region& operator |= (const Region& rhs); + inline Region& operator ^= (const Region& rhs); + inline Region& operator &= (const Region& rhs); + inline Region& operator -= (const Region& rhs); + inline Region& operator += (const Point& pt); + + + // returns true if the regions share the same underlying storage + bool isTriviallyEqual(const Region& region) const; + + + /* various ways to access the rectangle list */ + + + // STL-like iterators + typedef Rect const* const_iterator; + const_iterator begin() const; + const_iterator end() const; + + // returns an array of rect which has the same life-time has this + // Region object. + Rect const* getArray(size_t* count) const; + + // returns a SharedBuffer as well as the number of rects. + // ownership is transfered to the caller. + // the caller must call SharedBuffer::release() to free the memory. + SharedBuffer const* getSharedBuffer(size_t* count) const; + + /* no user serviceable parts here... */ + + // add a rectangle to the internal list. This rectangle must + // be sorted in Y and X and must not make the region invalid. + void addRectUnchecked(int l, int t, int r, int b); + + 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); + + void dump(String8& out, const char* what, uint32_t flags=0) const; + void dump(const char* what, uint32_t flags=0) const; + +private: + class rasterizer; + friend class rasterizer; + + Region& operationSelf(const Rect& r, int op); + Region& operationSelf(const Region& r, int op); + Region& operationSelf(const Region& r, int dx, int dy, int op); + const Region operation(const Rect& rhs, int op) const; + const Region operation(const Region& rhs, int op) const; + const Region operation(const Region& rhs, int dx, int dy, int op) const; + + static void boolean_operation(int op, Region& dst, + const Region& lhs, const Region& rhs, int dx, int dy); + static void boolean_operation(int op, Region& dst, + const Region& lhs, const Rect& rhs, int dx, int dy); + + static void boolean_operation(int op, Region& dst, + const Region& lhs, const Region& rhs); + static void boolean_operation(int op, Region& dst, + const Region& lhs, const Rect& rhs); + + static void translate(Region& reg, int dx, int dy); + static void translate(Region& dst, const Region& reg, int dx, int dy); + + static bool validate(const Region& reg, + const char* name, bool silent = false); + + // mStorage is a (manually) sorted array of Rects describing the region + // with an extra Rect as the last element which is set to the + // bounds of the region. However, if the region is + // a simple Rect then mStorage contains only that rect. + Vector mStorage; +}; + + +const Region Region::operator | (const Region& rhs) const { + return merge(rhs); +} +const Region Region::operator ^ (const Region& rhs) const { + return mergeExclusive(rhs); +} +const Region Region::operator & (const Region& rhs) const { + return intersect(rhs); +} +const Region Region::operator - (const Region& rhs) const { + return subtract(rhs); +} +const Region Region::operator + (const Point& pt) const { + return translate(pt.x, pt.y); +} + + +Region& Region::operator |= (const Region& rhs) { + return orSelf(rhs); +} +Region& Region::operator ^= (const Region& rhs) { + return xorSelf(rhs); +} +Region& Region::operator &= (const Region& rhs) { + return andSelf(rhs); +} +Region& Region::operator -= (const Region& rhs) { + return subtractSelf(rhs); +} +Region& Region::operator += (const Point& pt) { + return translateSelf(pt.x, pt.y); +} +// --------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_UI_REGION_H + diff --git a/phonelibs/android_frameworks_native/include/ui/TMatHelpers.h b/phonelibs/android_frameworks_native/include/ui/TMatHelpers.h new file mode 100644 index 0000000000..a6aadcad40 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/ui/TMatHelpers.h @@ -0,0 +1,257 @@ +/* + * Copyright 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 TMAT_IMPLEMENTATION +#error "Don't include TMatHelpers.h directly. use ui/mat*.h instead" +#else +#undef TMAT_IMPLEMENTATION +#endif + + +#ifndef UI_TMAT_HELPERS_H +#define UI_TMAT_HELPERS_H + +#include +#include +#include +#include +#include + +#define PURE __attribute__((pure)) + +namespace android { +// ------------------------------------------------------------------------------------- + +/* + * No user serviceable parts here. + * + * Don't use this file directly, instead include ui/mat*.h + */ + + +/* + * Matrix utilities + */ + +namespace matrix { + +inline int PURE transpose(int v) { return v; } +inline float PURE transpose(float v) { return v; } +inline double PURE transpose(double v) { return v; } + +inline int PURE trace(int v) { return v; } +inline float PURE trace(float v) { return v; } +inline double PURE trace(double v) { return v; } + +template +MATRIX PURE inverse(const MATRIX& src) { + + COMPILE_TIME_ASSERT_FUNCTION_SCOPE( MATRIX::COL_SIZE == MATRIX::ROW_SIZE ); + + typename MATRIX::value_type t; + const size_t N = MATRIX::col_size(); + size_t swap; + MATRIX tmp(src); + MATRIX inverse(1); + + for (size_t i=0 ; i fabs(tmp[i][i])) { + swap = j; + } + } + + if (swap != i) { + /* swap rows. */ + for (size_t k=0 ; k +MATRIX_R PURE multiply(const MATRIX_A& lhs, const MATRIX_B& rhs) { + // pre-requisite: + // lhs : D columns, R rows + // rhs : C columns, D rows + // res : C columns, R rows + + COMPILE_TIME_ASSERT_FUNCTION_SCOPE( MATRIX_A::ROW_SIZE == MATRIX_B::COL_SIZE ); + COMPILE_TIME_ASSERT_FUNCTION_SCOPE( MATRIX_R::ROW_SIZE == MATRIX_B::ROW_SIZE ); + COMPILE_TIME_ASSERT_FUNCTION_SCOPE( MATRIX_R::COL_SIZE == MATRIX_A::COL_SIZE ); + + MATRIX_R res(MATRIX_R::NO_INIT); + for (size_t r=0 ; r +MATRIX PURE transpose(const MATRIX& m) { + // for now we only handle square matrix transpose + COMPILE_TIME_ASSERT_FUNCTION_SCOPE( MATRIX::ROW_SIZE == MATRIX::COL_SIZE ); + MATRIX result(MATRIX::NO_INIT); + for (size_t r=0 ; r +typename MATRIX::value_type PURE trace(const MATRIX& m) { + COMPILE_TIME_ASSERT_FUNCTION_SCOPE( MATRIX::ROW_SIZE == MATRIX::COL_SIZE ); + typename MATRIX::value_type result(0); + for (size_t r=0 ; r +typename MATRIX::col_type PURE diag(const MATRIX& m) { + COMPILE_TIME_ASSERT_FUNCTION_SCOPE( MATRIX::ROW_SIZE == MATRIX::COL_SIZE ); + typename MATRIX::col_type result(MATRIX::col_type::NO_INIT); + for (size_t r=0 ; r +String8 asString(const MATRIX& m) { + String8 s; + for (size_t c=0 ; c. + * + * BASE only needs to implement operator[] and size(). + * By simply inheriting from TMatProductOperators BASE will automatically + * get all the functionality here. + */ + +template class BASE, typename T> +class TMatProductOperators { +public: + // multiply by a scalar + BASE& operator *= (T v) { + BASE& lhs(static_cast< BASE& >(*this)); + for (size_t r=0 ; r& operator /= (T v) { + BASE& lhs(static_cast< BASE& >(*this)); + for (size_t r=0 ; r + friend BASE PURE operator *(const BASE& lhs, const BASE& rhs) { + return matrix::multiply >(lhs, rhs); + } +}; + + +/* + * TMatSquareFunctions implements functions on a matrix of type BASE. + * + * BASE only needs to implement: + * - operator[] + * - col_type + * - row_type + * - COL_SIZE + * - ROW_SIZE + * + * By simply inheriting from TMatSquareFunctions BASE will automatically + * get all the functionality here. + */ + +template class BASE, typename T> +class TMatSquareFunctions { +public: + /* + * NOTE: the functions below ARE NOT member methods. They are friend functions + * with they definition inlined with their declaration. This makes these + * template functions available to the compiler when (and only when) this class + * is instantiated, at which point they're only templated on the 2nd parameter + * (the first one, BASE being known). + */ + friend BASE PURE inverse(const BASE& m) { return matrix::inverse(m); } + friend BASE PURE transpose(const BASE& m) { return matrix::transpose(m); } + friend T PURE trace(const BASE& m) { return matrix::trace(m); } +}; + +template class BASE, typename T> +class TMatDebug { +public: + String8 asString() const { + return matrix::asString( static_cast< const BASE& >(*this) ); + } +}; + +// ------------------------------------------------------------------------------------- +}; // namespace android + +#undef PURE + +#endif /* UI_TMAT_HELPERS_H */ diff --git a/phonelibs/android_frameworks_native/include/ui/TVecHelpers.h b/phonelibs/android_frameworks_native/include/ui/TVecHelpers.h new file mode 100644 index 0000000000..bb7dbfc2b8 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/ui/TVecHelpers.h @@ -0,0 +1,381 @@ +/* + * Copyright 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 TVEC_IMPLEMENTATION +#error "Don't include TVecHelpers.h directly. use ui/vec*.h instead" +#else +#undef TVEC_IMPLEMENTATION +#endif + + +#ifndef UI_TVEC_HELPERS_H +#define UI_TVEC_HELPERS_H + +#include +#include + +#define PURE __attribute__((pure)) + +namespace android { +// ------------------------------------------------------------------------------------- + +/* + * No user serviceable parts here. + * + * Don't use this file directly, instead include ui/vec{2|3|4}.h + */ + +/* + * This class casts itself into anything and assign itself from anything! + * Use with caution! + */ +template +struct Impersonator { + Impersonator& operator = (const TYPE& rhs) { + reinterpret_cast(*this) = rhs; + return *this; + } + operator TYPE& () { + return reinterpret_cast(*this); + } + operator TYPE const& () const { + return reinterpret_cast(*this); + } +}; + +/* + * TVec{Add|Product}Operators implements basic arithmetic and basic compound assignments + * operators on a vector of type BASE. + * + * BASE only needs to implement operator[] and size(). + * By simply inheriting from TVec{Add|Product}Operators BASE will automatically + * get all the functionality here. + */ + +template class BASE, typename T> +class TVecAddOperators { +public: + /* compound assignment from a another vector of the same size but different + * element type. + */ + template + BASE& operator += (const BASE& v) { + BASE& rhs = static_cast&>(*this); + for (size_t i=0 ; i::size() ; i++) { + rhs[i] += v[i]; + } + return rhs; + } + template + BASE& operator -= (const BASE& v) { + BASE& rhs = static_cast&>(*this); + for (size_t i=0 ; i::size() ; i++) { + rhs[i] -= v[i]; + } + return rhs; + } + + /* compound assignment from a another vector of the same type. + * These operators can be used for implicit conversion and handle operations + * like "vector *= scalar" by letting the compiler implicitly convert a scalar + * to a vector (assuming the BASE allows it). + */ + BASE& operator += (const BASE& v) { + BASE& rhs = static_cast&>(*this); + for (size_t i=0 ; i::size() ; i++) { + rhs[i] += v[i]; + } + return rhs; + } + BASE& operator -= (const BASE& v) { + BASE& rhs = static_cast&>(*this); + for (size_t i=0 ; i::size() ; i++) { + rhs[i] -= v[i]; + } + return rhs; + } + + /* + * NOTE: the functions below ARE NOT member methods. They are friend functions + * with they definition inlined with their declaration. This makes these + * template functions available to the compiler when (and only when) this class + * is instantiated, at which point they're only templated on the 2nd parameter + * (the first one, BASE being known). + */ + + /* The operators below handle operation between vectors of the same side + * but of a different element type. + */ + template + friend inline + BASE PURE operator +(const BASE& lv, const BASE& rv) { + return BASE(lv) += rv; + } + template + friend inline + BASE PURE operator -(const BASE& lv, const BASE& rv) { + return BASE(lv) -= rv; + } + + /* The operators below (which are not templates once this class is instanced, + * i.e.: BASE is known) can be used for implicit conversion on both sides. + * These handle operations like "vector * scalar" and "scalar * vector" by + * letting the compiler implicitly convert a scalar to a vector (assuming + * the BASE allows it). + */ + friend inline + BASE PURE operator +(const BASE& lv, const BASE& rv) { + return BASE(lv) += rv; + } + friend inline + BASE PURE operator -(const BASE& lv, const BASE& rv) { + return BASE(lv) -= rv; + } +}; + +template class BASE, typename T> +class TVecProductOperators { +public: + /* compound assignment from a another vector of the same size but different + * element type. + */ + template + BASE& operator *= (const BASE& v) { + BASE& rhs = static_cast&>(*this); + for (size_t i=0 ; i::size() ; i++) { + rhs[i] *= v[i]; + } + return rhs; + } + template + BASE& operator /= (const BASE& v) { + BASE& rhs = static_cast&>(*this); + for (size_t i=0 ; i::size() ; i++) { + rhs[i] /= v[i]; + } + return rhs; + } + + /* compound assignment from a another vector of the same type. + * These operators can be used for implicit conversion and handle operations + * like "vector *= scalar" by letting the compiler implicitly convert a scalar + * to a vector (assuming the BASE allows it). + */ + BASE& operator *= (const BASE& v) { + BASE& rhs = static_cast&>(*this); + for (size_t i=0 ; i::size() ; i++) { + rhs[i] *= v[i]; + } + return rhs; + } + BASE& operator /= (const BASE& v) { + BASE& rhs = static_cast&>(*this); + for (size_t i=0 ; i::size() ; i++) { + rhs[i] /= v[i]; + } + return rhs; + } + + /* + * NOTE: the functions below ARE NOT member methods. They are friend functions + * with they definition inlined with their declaration. This makes these + * template functions available to the compiler when (and only when) this class + * is instantiated, at which point they're only templated on the 2nd parameter + * (the first one, BASE being known). + */ + + /* The operators below handle operation between vectors of the same side + * but of a different element type. + */ + template + friend inline + BASE PURE operator *(const BASE& lv, const BASE& rv) { + return BASE(lv) *= rv; + } + template + friend inline + BASE PURE operator /(const BASE& lv, const BASE& rv) { + return BASE(lv) /= rv; + } + + /* The operators below (which are not templates once this class is instanced, + * i.e.: BASE is known) can be used for implicit conversion on both sides. + * These handle operations like "vector * scalar" and "scalar * vector" by + * letting the compiler implicitly convert a scalar to a vector (assuming + * the BASE allows it). + */ + friend inline + BASE PURE operator *(const BASE& lv, const BASE& rv) { + return BASE(lv) *= rv; + } + friend inline + BASE PURE operator /(const BASE& lv, const BASE& rv) { + return BASE(lv) /= rv; + } +}; + +/* + * TVecUnaryOperators implements unary operators on a vector of type BASE. + * + * BASE only needs to implement operator[] and size(). + * By simply inheriting from TVecUnaryOperators BASE will automatically + * get all the functionality here. + * + * These operators are implemented as friend functions of TVecUnaryOperators + */ +template class BASE, typename T> +class TVecUnaryOperators { +public: + BASE& operator ++ () { + BASE& rhs = static_cast&>(*this); + for (size_t i=0 ; i::size() ; i++) { + ++rhs[i]; + } + return rhs; + } + BASE& operator -- () { + BASE& rhs = static_cast&>(*this); + for (size_t i=0 ; i::size() ; i++) { + --rhs[i]; + } + return rhs; + } + BASE operator - () const { + BASE r(BASE::NO_INIT); + BASE const& rv(static_cast const&>(*this)); + for (size_t i=0 ; i::size() ; i++) { + r[i] = -rv[i]; + } + return r; + } +}; + + +/* + * TVecComparisonOperators implements relational/comparison operators + * on a vector of type BASE. + * + * BASE only needs to implement operator[] and size(). + * By simply inheriting from TVecComparisonOperators BASE will automatically + * get all the functionality here. + */ +template class BASE, typename T> +class TVecComparisonOperators { +public: + /* + * NOTE: the functions below ARE NOT member methods. They are friend functions + * with they definition inlined with their declaration. This makes these + * template functions available to the compiler when (and only when) this class + * is instantiated, at which point they're only templated on the 2nd parameter + * (the first one, BASE being known). + */ + template + friend inline + bool PURE operator ==(const BASE& lv, const BASE& rv) { + for (size_t i = 0; i < BASE::size(); i++) + if (lv[i] != rv[i]) + return false; + return true; + } + + template + friend inline + bool PURE operator !=(const BASE& lv, const BASE& rv) { + return !operator ==(lv, rv); + } + + template + friend inline + bool PURE operator >(const BASE& lv, const BASE& rv) { + for (size_t i = 0; i < BASE::size(); i++) + if (lv[i] <= rv[i]) + return false; + return true; + } + + template + friend inline + bool PURE operator <=(const BASE& lv, const BASE& rv) { + return !(lv > rv); + } + + template + friend inline + bool PURE operator <(const BASE& lv, const BASE& rv) { + for (size_t i = 0; i < BASE::size(); i++) + if (lv[i] >= rv[i]) + return false; + return true; + } + + template + friend inline + bool PURE operator >=(const BASE& lv, const BASE& rv) { + return !(lv < rv); + } +}; + + +/* + * TVecFunctions implements functions on a vector of type BASE. + * + * BASE only needs to implement operator[] and size(). + * By simply inheriting from TVecFunctions BASE will automatically + * get all the functionality here. + */ +template class BASE, typename T> +class TVecFunctions { +public: + /* + * NOTE: the functions below ARE NOT member methods. They are friend functions + * with they definition inlined with their declaration. This makes these + * template functions available to the compiler when (and only when) this class + * is instantiated, at which point they're only templated on the 2nd parameter + * (the first one, BASE being known). + */ + template + friend inline + T PURE dot(const BASE& lv, const BASE& rv) { + T r(0); + for (size_t i = 0; i < BASE::size(); i++) + r += lv[i]*rv[i]; + return r; + } + + friend inline + T PURE length(const BASE& lv) { + return sqrt( dot(lv, lv) ); + } + + template + friend inline + T PURE distance(const BASE& lv, const BASE& rv) { + return length(rv - lv); + } + + friend inline + BASE PURE normalize(const BASE& lv) { + return lv * (1 / length(lv)); + } +}; + +#undef PURE + +// ------------------------------------------------------------------------------------- +}; // namespace android + + +#endif /* UI_TVEC_HELPERS_H */ diff --git a/phonelibs/android_frameworks_native/include/ui/UiConfig.h b/phonelibs/android_frameworks_native/include/ui/UiConfig.h new file mode 100644 index 0000000000..fcf8ed5d6b --- /dev/null +++ b/phonelibs/android_frameworks_native/include/ui/UiConfig.h @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_UI_CONFIG_H +#define ANDROID_UI_CONFIG_H + +#include + +namespace android { + +// Append the libui configuration details to configStr. +void appendUiConfigString(String8& configStr); + +}; // namespace android + +#endif /*ANDROID_UI_CONFIG_H*/ diff --git a/phonelibs/android_frameworks_native/include/ui/mat4.h b/phonelibs/android_frameworks_native/include/ui/mat4.h new file mode 100644 index 0000000000..4fd1effd71 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/ui/mat4.h @@ -0,0 +1,395 @@ +/* + * Copyright 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 UI_MAT4_H +#define UI_MAT4_H + +#include +#include + +#include +#include + +#define TMAT_IMPLEMENTATION +#include + +#define PURE __attribute__((pure)) + +namespace android { +// ------------------------------------------------------------------------------------- + +template +class tmat44 : public TVecUnaryOperators, + public TVecComparisonOperators, + public TVecAddOperators, + public TMatProductOperators, + public TMatSquareFunctions, + public TMatDebug +{ +public: + enum no_init { NO_INIT }; + typedef T value_type; + typedef T& reference; + typedef T const& const_reference; + typedef size_t size_type; + typedef tvec4 col_type; + typedef tvec4 row_type; + + // size of a column (i.e.: number of rows) + enum { COL_SIZE = col_type::SIZE }; + static inline size_t col_size() { return COL_SIZE; } + + // size of a row (i.e.: number of columns) + enum { ROW_SIZE = row_type::SIZE }; + static inline size_t row_size() { return ROW_SIZE; } + static inline size_t size() { return row_size(); } // for TVec*<> + +private: + + /* + * <-- N columns --> + * + * a00 a10 a20 ... aN0 ^ + * a01 a11 a21 ... aN1 | + * a02 a12 a22 ... aN2 M rows + * ... | + * a0M a1M a2M ... aNM v + * + * COL_SIZE = M + * ROW_SIZE = N + * m[0] = [a00 a01 a02 ... a01M] + */ + + col_type mValue[ROW_SIZE]; + +public: + // array access + inline col_type const& operator [] (size_t i) const { return mValue[i]; } + inline col_type& operator [] (size_t i) { return mValue[i]; } + + T const* asArray() const { return &mValue[0][0]; } + + // ----------------------------------------------------------------------- + // we don't provide copy-ctor and operator= on purpose + // because we want the compiler generated versions + + /* + * constructors + */ + + // leaves object uninitialized. use with caution. + explicit tmat44(no_init) { } + + // initialize to identity + tmat44(); + + // initialize to Identity*scalar. + template + explicit tmat44(U v); + + // sets the diagonal to the passed vector + template + explicit tmat44(const tvec4& rhs); + + // construct from another matrix of the same size + template + explicit tmat44(const tmat44& rhs); + + // construct from 4 column vectors + template + tmat44(const tvec4& v0, const tvec4& v1, const tvec4& v2, const tvec4& v3); + + // construct from 16 scalars + template < + typename A, typename B, typename C, typename D, + typename E, typename F, typename G, typename H, + typename I, typename J, typename K, typename L, + typename M, typename N, typename O, typename P> + tmat44( A m00, B m01, C m02, D m03, + E m10, F m11, G m12, H m13, + I m20, J m21, K m22, L m23, + M m30, N m31, O m32, P m33); + + // construct from a C array + template + explicit tmat44(U const* rawArray); + + /* + * helpers + */ + + static tmat44 ortho(T left, T right, T bottom, T top, T near, T far); + + static tmat44 frustum(T left, T right, T bottom, T top, T near, T far); + + template + static tmat44 lookAt(const tvec3& eye, const tvec3& center, const tvec3& up); + + template + static tmat44 translate(const tvec4& t); + + template + static tmat44 scale(const tvec4& s); + + template + static tmat44 rotate(A radian, const tvec3& about); +}; + +// ---------------------------------------------------------------------------------------- +// Constructors +// ---------------------------------------------------------------------------------------- + +/* + * Since the matrix code could become pretty big quickly, we don't inline most + * operations. + */ + +template +tmat44::tmat44() { + mValue[0] = col_type(1,0,0,0); + mValue[1] = col_type(0,1,0,0); + mValue[2] = col_type(0,0,1,0); + mValue[3] = col_type(0,0,0,1); +} + +template +template +tmat44::tmat44(U v) { + mValue[0] = col_type(v,0,0,0); + mValue[1] = col_type(0,v,0,0); + mValue[2] = col_type(0,0,v,0); + mValue[3] = col_type(0,0,0,v); +} + +template +template +tmat44::tmat44(const tvec4& v) { + mValue[0] = col_type(v.x,0,0,0); + mValue[1] = col_type(0,v.y,0,0); + mValue[2] = col_type(0,0,v.z,0); + mValue[3] = col_type(0,0,0,v.w); +} + +// construct from 16 scalars +template +template < + typename A, typename B, typename C, typename D, + typename E, typename F, typename G, typename H, + typename I, typename J, typename K, typename L, + typename M, typename N, typename O, typename P> +tmat44::tmat44( A m00, B m01, C m02, D m03, + E m10, F m11, G m12, H m13, + I m20, J m21, K m22, L m23, + M m30, N m31, O m32, P m33) { + mValue[0] = col_type(m00, m01, m02, m03); + mValue[1] = col_type(m10, m11, m12, m13); + mValue[2] = col_type(m20, m21, m22, m23); + mValue[3] = col_type(m30, m31, m32, m33); +} + +template +template +tmat44::tmat44(const tmat44& rhs) { + for (size_t r=0 ; r +template +tmat44::tmat44(const tvec4& v0, const tvec4& v1, const tvec4& v2, const tvec4& v3) { + mValue[0] = v0; + mValue[1] = v1; + mValue[2] = v2; + mValue[3] = v3; +} + +template +template +tmat44::tmat44(U const* rawArray) { + for (size_t r=0 ; r +tmat44 tmat44::ortho(T left, T right, T bottom, T top, T near, T far) { + tmat44 m; + m[0][0] = 2 / (right - left); + m[1][1] = 2 / (top - bottom); + m[2][2] = -2 / (far - near); + m[3][0] = -(right + left) / (right - left); + m[3][1] = -(top + bottom) / (top - bottom); + m[3][2] = -(far + near) / (far - near); + return m; +} + +template +tmat44 tmat44::frustum(T left, T right, T bottom, T top, T near, T far) { + tmat44 m; + T A = (right + left) / (right - left); + T B = (top + bottom) / (top - bottom); + T C = (far + near) / (far - near); + T D = (2 * far * near) / (far - near); + m[0][0] = (2 * near) / (right - left); + m[1][1] = (2 * near) / (top - bottom); + m[2][0] = A; + m[2][1] = B; + m[2][2] = C; + m[2][3] =-1; + m[3][2] = D; + m[3][3] = 0; + return m; +} + +template +template +tmat44 tmat44::lookAt(const tvec3& eye, const tvec3& center, const tvec3& up) { + tvec3 L(normalize(center - eye)); + tvec3 S(normalize( cross(L, up) )); + tvec3 U(cross(S, L)); + return tmat44( + tvec4( S, 0), + tvec4( U, 0), + tvec4(-L, 0), + tvec4(-eye, 1)); +} + +template +template +tmat44 tmat44::translate(const tvec4& t) { + tmat44 r; + r[3] = t; + return r; +} + +template +template +tmat44 tmat44::scale(const tvec4& s) { + tmat44 r; + r[0][0] = s[0]; + r[1][1] = s[1]; + r[2][2] = s[2]; + r[3][3] = s[3]; + return r; +} + +template +template +tmat44 tmat44::rotate(A radian, const tvec3& about) { + tmat44 rotation; + T* r = const_cast(rotation.asArray()); + T c = cos(radian); + T s = sin(radian); + if (about.x==1 && about.y==0 && about.z==0) { + r[5] = c; r[10]= c; + r[6] = s; r[9] = -s; + } else if (about.x==0 && about.y==1 && about.z==0) { + r[0] = c; r[10]= c; + r[8] = s; r[2] = -s; + } else if (about.x==0 && about.y==0 && about.z==1) { + r[0] = c; r[5] = c; + r[1] = s; r[4] = -s; + } else { + tvec3 nabout = normalize(about); + B x = nabout.x; + B y = nabout.y; + B z = nabout.z; + T nc = 1 - c; + T xy = x * y; + T yz = y * z; + T zx = z * x; + T xs = x * s; + T ys = y * s; + T zs = z * s; + r[ 0] = x*x*nc + c; r[ 4] = xy*nc - zs; r[ 8] = zx*nc + ys; + r[ 1] = xy*nc + zs; r[ 5] = y*y*nc + c; r[ 9] = yz*nc - xs; + r[ 2] = zx*nc - ys; r[ 6] = yz*nc + xs; r[10] = z*z*nc + c; + } + return rotation; +} + +// ---------------------------------------------------------------------------------------- +// Arithmetic operators outside of class +// ---------------------------------------------------------------------------------------- + +/* We use non-friend functions here to prevent the compiler from using + * implicit conversions, for instance of a scalar to a vector. The result would + * not be what the caller expects. + * + * Also note that the order of the arguments in the inner loop is important since + * it determines the output type (only relevant when T != U). + */ + +// matrix * vector, result is a vector of the same type than the input vector +template +typename tmat44::col_type PURE operator *(const tmat44& lv, const tvec4& rv) { + typename tmat44::col_type result; + for (size_t r=0 ; r::row_size() ; r++) + result += rv[r]*lv[r]; + return result; +} + +// vector * matrix, result is a vector of the same type than the input vector +template +typename tmat44::row_type PURE operator *(const tvec4& rv, const tmat44& lv) { + typename tmat44::row_type result(tmat44::row_type::NO_INIT); + for (size_t r=0 ; r::row_size() ; r++) + result[r] = dot(rv, lv[r]); + return result; +} + +// matrix * scalar, result is a matrix of the same type than the input matrix +template +tmat44 PURE operator *(const tmat44& lv, U rv) { + tmat44 result(tmat44::NO_INIT); + for (size_t r=0 ; r::row_size() ; r++) + result[r] = lv[r]*rv; + return result; +} + +// scalar * matrix, result is a matrix of the same type than the input matrix +template +tmat44 PURE operator *(U rv, const tmat44& lv) { + tmat44 result(tmat44::NO_INIT); + for (size_t r=0 ; r::row_size() ; r++) + result[r] = lv[r]*rv; + return result; +} + +// ---------------------------------------------------------------------------------------- + +/* FIXME: this should go into TMatSquareFunctions<> but for some reason + * BASE::col_type is not accessible from there (???) + */ +template +typename tmat44::col_type PURE diag(const tmat44& m) { + return matrix::diag(m); +} + +// ---------------------------------------------------------------------------------------- + +typedef tmat44 mat4; + +// ---------------------------------------------------------------------------------------- +}; // namespace android + +#undef PURE + +#endif /* UI_MAT4_H */ diff --git a/phonelibs/android_frameworks_native/include/ui/vec2.h b/phonelibs/android_frameworks_native/include/ui/vec2.h new file mode 100644 index 0000000000..c31d0e43e3 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/ui/vec2.h @@ -0,0 +1,91 @@ +/* + * Copyright 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 UI_VEC2_H +#define UI_VEC2_H + +#include +#include + +#define TVEC_IMPLEMENTATION +#include + +namespace android { +// ------------------------------------------------------------------------------------- + +template +class tvec2 : public TVecProductOperators, + public TVecAddOperators, + public TVecUnaryOperators, + public TVecComparisonOperators, + public TVecFunctions +{ +public: + enum no_init { NO_INIT }; + typedef T value_type; + typedef T& reference; + typedef T const& const_reference; + typedef size_t size_type; + + union { + struct { T x, y; }; + struct { T s, t; }; + struct { T r, g; }; + }; + + enum { SIZE = 2 }; + inline static size_type size() { return SIZE; } + + // array access + inline T const& operator [] (size_t i) const { return (&x)[i]; } + inline T& operator [] (size_t i) { return (&x)[i]; } + + // ----------------------------------------------------------------------- + // we don't provide copy-ctor and operator= on purpose + // because we want the compiler generated versions + + // constructors + + // leaves object uninitialized. use with caution. + explicit tvec2(no_init) { } + + // default constructor + tvec2() : x(0), y(0) { } + + // handles implicit conversion to a tvec4. must not be explicit. + template + tvec2(A v) : x(v), y(v) { } + + template + tvec2(A x, B y) : x(x), y(y) { } + + template + explicit tvec2(const tvec2& v) : x(v.x), y(v.y) { } + + template + tvec2(const Impersonator< tvec2 >& v) + : x(((const tvec2&)v).x), + y(((const tvec2&)v).y) { } +}; + +// ---------------------------------------------------------------------------------------- + +typedef tvec2 vec2; + +// ---------------------------------------------------------------------------------------- +}; // namespace android + +#endif /* UI_VEC4_H */ diff --git a/phonelibs/android_frameworks_native/include/ui/vec3.h b/phonelibs/android_frameworks_native/include/ui/vec3.h new file mode 100644 index 0000000000..dde59a96fb --- /dev/null +++ b/phonelibs/android_frameworks_native/include/ui/vec3.h @@ -0,0 +1,113 @@ +/* + * Copyright 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 UI_VEC3_H +#define UI_VEC3_H + +#include +#include + +#include + +namespace android { +// ------------------------------------------------------------------------------------- + +template +class tvec3 : public TVecProductOperators, + public TVecAddOperators, + public TVecUnaryOperators, + public TVecComparisonOperators, + public TVecFunctions +{ +public: + enum no_init { NO_INIT }; + typedef T value_type; + typedef T& reference; + typedef T const& const_reference; + typedef size_t size_type; + + union { + struct { T x, y, z; }; + struct { T s, t, p; }; + struct { T r, g, b; }; + Impersonator< tvec2 > xy; + Impersonator< tvec2 > st; + Impersonator< tvec2 > rg; + }; + + enum { SIZE = 3 }; + inline static size_type size() { return SIZE; } + + // array access + inline T const& operator [] (size_t i) const { return (&x)[i]; } + inline T& operator [] (size_t i) { return (&x)[i]; } + + // ----------------------------------------------------------------------- + // we don't provide copy-ctor and operator= on purpose + // because we want the compiler generated versions + + // constructors + // leaves object uninitialized. use with caution. + explicit tvec3(no_init) { } + + // default constructor + tvec3() : x(0), y(0), z(0) { } + + // handles implicit conversion to a tvec4. must not be explicit. + template + tvec3(A v) : x(v), y(v), z(v) { } + + template + tvec3(A x, B y, C z) : x(x), y(y), z(z) { } + + template + tvec3(const tvec2& v, B z) : x(v.x), y(v.y), z(z) { } + + template + explicit tvec3(const tvec3& v) : x(v.x), y(v.y), z(v.z) { } + + template + tvec3(const Impersonator< tvec3 >& v) + : x(((const tvec3&)v).x), + y(((const tvec3&)v).y), + z(((const tvec3&)v).z) { } + + template + tvec3(const Impersonator< tvec2 >& v, B z) + : x(((const tvec2&)v).x), + y(((const tvec2&)v).y), + z(z) { } + + // cross product works only on vectors of size 3 + template + friend inline + tvec3 __attribute__((pure)) cross(const tvec3& u, const tvec3& v) { + return tvec3( + u.y*v.z - u.z*v.y, + u.z*v.x - u.x*v.z, + u.x*v.y - u.y*v.x); + } +}; + + +// ---------------------------------------------------------------------------------------- + +typedef tvec3 vec3; + +// ---------------------------------------------------------------------------------------- +}; // namespace android + +#endif /* UI_VEC4_H */ diff --git a/phonelibs/android_frameworks_native/include/ui/vec4.h b/phonelibs/android_frameworks_native/include/ui/vec4.h new file mode 100644 index 0000000000..e03d331fb3 --- /dev/null +++ b/phonelibs/android_frameworks_native/include/ui/vec4.h @@ -0,0 +1,118 @@ +/* + * Copyright 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 UI_VEC4_H +#define UI_VEC4_H + +#include +#include + +#include + +namespace android { +// ------------------------------------------------------------------------------------- + +template +class tvec4 : public TVecProductOperators, + public TVecAddOperators, + public TVecUnaryOperators, + public TVecComparisonOperators, + public TVecFunctions +{ +public: + enum no_init { NO_INIT }; + typedef T value_type; + typedef T& reference; + typedef T const& const_reference; + typedef size_t size_type; + + union { + struct { T x, y, z, w; }; + struct { T s, t, p, q; }; + struct { T r, g, b, a; }; + Impersonator< tvec2 > xy; + Impersonator< tvec2 > st; + Impersonator< tvec2 > rg; + Impersonator< tvec3 > xyz; + Impersonator< tvec3 > stp; + Impersonator< tvec3 > rgb; + }; + + enum { SIZE = 4 }; + inline static size_type size() { return SIZE; } + + // array access + inline T const& operator [] (size_t i) const { return (&x)[i]; } + inline T& operator [] (size_t i) { return (&x)[i]; } + + // ----------------------------------------------------------------------- + // we don't provide copy-ctor and operator= on purpose + // because we want the compiler generated versions + + // constructors + + // leaves object uninitialized. use with caution. + explicit tvec4(no_init) { } + + // default constructor + tvec4() : x(0), y(0), z(0), w(0) { } + + // handles implicit conversion to a tvec4. must not be explicit. + template + tvec4(A v) : x(v), y(v), z(v), w(v) { } + + template + tvec4(A x, B y, C z, D w) : x(x), y(y), z(z), w(w) { } + + template + tvec4(const tvec2& v, B z, C w) : x(v.x), y(v.y), z(z), w(w) { } + + template + tvec4(const tvec3& v, B w) : x(v.x), y(v.y), z(v.z), w(w) { } + + template + explicit tvec4(const tvec4& v) : x(v.x), y(v.y), z(v.z), w(v.w) { } + + template + tvec4(const Impersonator< tvec4 >& v) + : x(((const tvec4&)v).x), + y(((const tvec4&)v).y), + z(((const tvec4&)v).z), + w(((const tvec4&)v).w) { } + + template + tvec4(const Impersonator< tvec3 >& v, B w) + : x(((const tvec3&)v).x), + y(((const tvec3&)v).y), + z(((const tvec3&)v).z), + w(w) { } + + template + tvec4(const Impersonator< tvec2 >& v, B z, C w) + : x(((const tvec2&)v).x), + y(((const tvec2&)v).y), + z(z), + w(w) { } +}; + +// ---------------------------------------------------------------------------------------- + +typedef tvec4 vec4; + +// ---------------------------------------------------------------------------------------- +}; // namespace android + +#endif /* UI_VEC4_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/activity_recognition.h b/phonelibs/android_hardware_libhardware/include/hardware/activity_recognition.h new file mode 100644 index 0000000000..8f9945982d --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/activity_recognition.h @@ -0,0 +1,223 @@ +/* + * Copyright (C) 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. + */ + +/* + * Activity Recognition HAL. The goal is to provide low power, low latency, always-on activity + * recognition implemented in hardware (i.e. these activity recognition algorithms/classifers + * should NOT be run on the AP). By low power we mean that this may be activated 24/7 without + * impacting the battery drain speed (goal in order of 1mW including the power for sensors). + * This HAL does not specify the input sources that are used towards detecting these activities. + * It has one monitor interface which can be used to batch activities for always-on + * activity_recognition and if the latency is zero, the same interface can be used for low latency + * detection. + */ + +#ifndef ANDROID_ACTIVITY_RECOGNITION_INTERFACE_H +#define ANDROID_ACTIVITY_RECOGNITION_INTERFACE_H + +#include + +__BEGIN_DECLS + +#define ACTIVITY_RECOGNITION_HEADER_VERSION 1 +#define ACTIVITY_RECOGNITION_API_VERSION_0_1 HARDWARE_DEVICE_API_VERSION_2(0, 1, ACTIVITY_RECOGNITION_HEADER_VERSION) + +#define ACTIVITY_RECOGNITION_HARDWARE_MODULE_ID "activity_recognition" +#define ACTIVITY_RECOGNITION_HARDWARE_INTERFACE "activity_recognition_hw_if" + +/* + * Define types for various activities. Multiple activities may be active at the same time and + * sometimes none of these activities may be active. + * + * Each activity has a corresponding type. Only activities that are defined here should use + * android.activity_recognition.* prefix. OEM defined activities should not use this prefix. + * Activity type of OEM-defined activities should start with the reverse domain name of the entity + * defining the activity. + * + * When android introduces a new activity type that can potentially replace an OEM-defined activity + * type, the OEM must use the official activity type on versions of the HAL that support this new + * official activity type. + * + * Example (made up): Suppose Google's Glass team wants to detect nodding activity. + * - Such an activity is not officially supported in android L + * - Glass devices launching on L can implement a custom activity with + * type = "com.google.glass.nodding" + * - In M android release, if android decides to define ACITIVITY_TYPE_NODDING, those types + * should replace the Glass-team-specific types in all future launches. + * - When launching glass on the M release, Google should now use the official activity type + * - This way, other applications can use this activity. + */ + +#define ACTIVITY_TYPE_IN_VEHICLE "android.activity_recognition.in_vehicle" + +#define ACTIVITY_TYPE_ON_BICYCLE "android.activity_recognition.on_bicycle" + +#define ACTIVITY_TYPE_WALKING "android.activity_recognition.walking" + +#define ACTIVITY_TYPE_RUNNING "android.activity_recognition.running" + +#define ACTIVITY_TYPE_STILL "android.activity_recognition.still" + +#define ACTIVITY_TYPE_TILTING "android.activity_recognition.tilting" + +/* Values for activity_event.event_types. */ +enum { + /* + * A flush_complete event which indicates that a flush() has been successfully completed. This + * does not correspond to any activity/event. An event of this type should be added to the end + * of a batch FIFO and it indicates that all the events in the batch FIFO have been successfully + * reported to the framework. An event of this type should be generated only if flush() has been + * explicitly called and if the FIFO is empty at the time flush() is called it should trivially + * return a flush_complete_event to indicate that the FIFO is empty. + * + * A flush complete event should have the following parameters set. + * activity_event_t.event_type = ACTIVITY_EVENT_FLUSH_COMPLETE + * activity_event_t.activity = 0 + * activity_event_t.timestamp = 0 + * activity_event_t.reserved = 0 + * See (*flush)() for more details. + */ + ACTIVITY_EVENT_FLUSH_COMPLETE = 0, + + /* Signifies entering an activity. */ + ACTIVITY_EVENT_ENTER = 1, + + /* Signifies exiting an activity. */ + ACTIVITY_EVENT_EXIT = 2 +}; + +/* + * Each event is a separate activity with event_type indicating whether this activity has started + * or ended. Eg event: (event_type="enter", activity="ON_FOOT", timestamp) + */ +typedef struct activity_event { + /* One of the ACTIVITY_EVENT_* constants defined above. */ + uint32_t event_type; + + /* + * Index of the activity in the list returned by get_supported_activities_list. If this event + * is a flush complete event, this should be set to zero. + */ + uint32_t activity; + + /* Time at which the transition/event has occurred in nanoseconds using elapsedRealTimeNano. */ + int64_t timestamp; + + /* Set to zero. */ + int32_t reserved[4]; +} activity_event_t; + +typedef struct activity_recognition_module { + /** + * Common methods of the activity recognition module. This *must* be the first member of + * activity_recognition_module as users of this structure will cast a hw_module_t to + * activity_recognition_module pointer in contexts where it's known the hw_module_t + * references an activity_recognition_module. + */ + hw_module_t common; + + /* + * List of all activities supported by this module including OEM defined activities. Each + * activity is represented using a string defined above. Each string should be null terminated. + * The index of the activity in this array is used as a "handle" for enabling/disabling and + * event delivery. + * Return value is the size of this list. + */ + int (*get_supported_activities_list)(struct activity_recognition_module* module, + char const* const* *activity_list); +} activity_recognition_module_t; + +struct activity_recognition_device; + +typedef struct activity_recognition_callback_procs { + // Callback for activity_data. This is guaranteed to not invoke any HAL methods. + // Memory allocated for the events can be reused after this method returns. + // events - Array of activity_event_t s that are reported. + // count - size of the array. + void (*activity_callback)(const struct activity_recognition_callback_procs* procs, + const activity_event_t* events, int count); +} activity_recognition_callback_procs_t; + +typedef struct activity_recognition_device { + /** + * Common methods of the activity recognition device. This *must* be the first member of + * activity_recognition_device as users of this structure will cast a hw_device_t to + * activity_recognition_device pointer in contexts where it's known the hw_device_t + * references an activity_recognition_device. + */ + hw_device_t common; + + /* + * Sets the callback to invoke when there are events to report. This call overwrites the + * previously registered callback (if any). + */ + void (*register_activity_callback)(const struct activity_recognition_device* dev, + const activity_recognition_callback_procs_t* callback); + + /* + * Activates monitoring of activity transitions. Activities need not be reported as soon as they + * are detected. The detected activities are stored in a FIFO and reported in batches when the + * "max_batch_report_latency" expires or when the batch FIFO is full. The implementation should + * allow the AP to go into suspend mode while the activities are detected and stored in the + * batch FIFO. Whenever events need to be reported (like when the FIFO is full or when the + * max_batch_report_latency has expired for an activity, event pair), it should wake_up the AP + * so that no events are lost. Activities are stored as transitions and they are allowed to + * overlap with each other. Each (activity, event_type) pair can be activated or deactivated + * independently of the other. The HAL implementation needs to keep track of which pairs are + * currently active and needs to detect only those pairs. + * + * activity_handle - Index of the specific activity that needs to be detected in the list + * returned by get_supported_activities_list. + * event_type - Specific transition of the activity that needs to be detected. + * max_batch_report_latency_ns - a transition can be delayed by at most + * “max_batch_report_latency†nanoseconds. + * Return 0 on success, negative errno code otherwise. + */ + int (*enable_activity_event)(const struct activity_recognition_device* dev, + uint32_t activity_handle, uint32_t event_type, int64_t max_batch_report_latency_ns); + + /* + * Disables detection of a specific (activity, event_type) pair. + */ + int (*disable_activity_event)(const struct activity_recognition_device* dev, + uint32_t activity_handle, uint32_t event_type); + + /* + * Flush all the batch FIFOs. Report all the activities that were stored in the FIFO so far as + * if max_batch_report_latency had expired. This shouldn't change the latency in any way. Add + * a flush_complete_event to indicate the end of the FIFO after all events are delivered. + * See ACTIVITY_EVENT_FLUSH_COMPLETE for more details. + * Return 0 on success, negative errno code otherwise. + */ + int (*flush)(const struct activity_recognition_device* dev); + + // Must be set to NULL. + void (*reserved_procs[16 - 4])(void); +} activity_recognition_device_t; + +static inline int activity_recognition_open(const hw_module_t* module, + activity_recognition_device_t** device) { + return module->methods->open(module, + ACTIVITY_RECOGNITION_HARDWARE_INTERFACE, (hw_device_t**)device); +} + +static inline int activity_recognition_close(activity_recognition_device_t* device) { + return device->common.close(&device->common); +} + +__END_DECLS + +#endif // ANDROID_ACTIVITY_RECOGNITION_INTERFACE_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/audio.h b/phonelibs/android_hardware_libhardware/include/hardware/audio.h new file mode 100644 index 0000000000..22e7419769 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/audio.h @@ -0,0 +1,700 @@ +/* + * 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_AUDIO_HAL_INTERFACE_H +#define ANDROID_AUDIO_HAL_INTERFACE_H + +#include +#include +#include +#include + +#include + +#include +#include +#include +#ifdef AUDIO_LISTEN_ENABLED +#include +#endif + +__BEGIN_DECLS + +/** + * The id of this module + */ +#define AUDIO_HARDWARE_MODULE_ID "audio" + +/** + * Name of the audio devices to open + */ +#define AUDIO_HARDWARE_INTERFACE "audio_hw_if" + + +/* Use version 0.1 to be compatible with first generation of audio hw module with version_major + * hardcoded to 1. No audio module API change. + */ +#define AUDIO_MODULE_API_VERSION_0_1 HARDWARE_MODULE_API_VERSION(0, 1) +#define AUDIO_MODULE_API_VERSION_CURRENT AUDIO_MODULE_API_VERSION_0_1 + +/* First generation of audio devices had version hardcoded to 0. all devices with versions < 1.0 + * will be considered of first generation API. + */ +#define AUDIO_DEVICE_API_VERSION_0_0 HARDWARE_DEVICE_API_VERSION(0, 0) +#define AUDIO_DEVICE_API_VERSION_1_0 HARDWARE_DEVICE_API_VERSION(1, 0) +#define AUDIO_DEVICE_API_VERSION_2_0 HARDWARE_DEVICE_API_VERSION(2, 0) +#define AUDIO_DEVICE_API_VERSION_3_0 HARDWARE_DEVICE_API_VERSION(3, 0) +#define AUDIO_DEVICE_API_VERSION_CURRENT AUDIO_DEVICE_API_VERSION_3_0 +/* Minimal audio HAL version supported by the audio framework */ +#define AUDIO_DEVICE_API_VERSION_MIN AUDIO_DEVICE_API_VERSION_2_0 + +/** + * List of known audio HAL modules. This is the base name of the audio HAL + * library composed of the "audio." prefix, one of the base names below and + * a suffix specific to the device. + * e.g: audio.primary.goldfish.so or audio.a2dp.default.so + */ + +#define AUDIO_HARDWARE_MODULE_ID_PRIMARY "primary" +#define AUDIO_HARDWARE_MODULE_ID_A2DP "a2dp" +#define AUDIO_HARDWARE_MODULE_ID_USB "usb" +#define AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX "r_submix" +#define AUDIO_HARDWARE_MODULE_ID_CODEC_OFFLOAD "codec_offload" + +/**************************************/ + +/** + * standard audio parameters that the HAL may need to handle + */ + +/** + * audio device parameters + */ + +/* BT SCO Noise Reduction + Echo Cancellation parameters */ +#define AUDIO_PARAMETER_KEY_BT_NREC "bt_headset_nrec" +#define AUDIO_PARAMETER_VALUE_ON "on" +#define AUDIO_PARAMETER_VALUE_OFF "off" + +/* TTY mode selection */ +#define AUDIO_PARAMETER_KEY_TTY_MODE "tty_mode" +#define AUDIO_PARAMETER_VALUE_TTY_OFF "tty_off" +#define AUDIO_PARAMETER_VALUE_TTY_VCO "tty_vco" +#define AUDIO_PARAMETER_VALUE_TTY_HCO "tty_hco" +#define AUDIO_PARAMETER_VALUE_TTY_FULL "tty_full" + +/* Hearing Aid Compatibility - Telecoil (HAC-T) mode on/off + Strings must be in sync with CallFeaturesSetting.java */ +#define AUDIO_PARAMETER_KEY_HAC "HACSetting" +#define AUDIO_PARAMETER_VALUE_HAC_ON "ON" +#define AUDIO_PARAMETER_VALUE_HAC_OFF "OFF" + +/* A2DP sink address set by framework */ +#define AUDIO_PARAMETER_A2DP_SINK_ADDRESS "a2dp_sink_address" + +/* A2DP source address set by framework */ +#define AUDIO_PARAMETER_A2DP_SOURCE_ADDRESS "a2dp_source_address" + +/* Screen state */ +#define AUDIO_PARAMETER_KEY_SCREEN_STATE "screen_state" + +/* Bluetooth SCO wideband */ +#define AUDIO_PARAMETER_KEY_BT_SCO_WB "bt_wbs" + +/* Get a new HW synchronization source identifier. + * Return a valid source (positive integer) or AUDIO_HW_SYNC_INVALID if an error occurs + * or no HW sync is available. */ +#define AUDIO_PARAMETER_HW_AV_SYNC "hw_av_sync" + +/* Device state*/ +#define AUDIO_PARAMETER_KEY_DEV_SHUTDOWN "dev_shutdown" + +/** + * audio stream parameters + */ + +#define AUDIO_PARAMETER_STREAM_ROUTING "routing" /* audio_devices_t */ +#define AUDIO_PARAMETER_STREAM_FORMAT "format" /* audio_format_t */ +#define AUDIO_PARAMETER_STREAM_CHANNELS "channels" /* audio_channel_mask_t */ +#define AUDIO_PARAMETER_STREAM_FRAME_COUNT "frame_count" /* size_t */ +#define AUDIO_PARAMETER_STREAM_INPUT_SOURCE "input_source" /* audio_source_t */ +#define AUDIO_PARAMETER_STREAM_SAMPLING_RATE "sampling_rate" /* uint32_t */ + +#define AUDIO_PARAMETER_DEVICE_CONNECT "connect" /* audio_devices_t */ +#define AUDIO_PARAMETER_DEVICE_DISCONNECT "disconnect" /* audio_devices_t */ + +/* Query supported formats. The response is a '|' separated list of strings from + * audio_format_t enum e.g: "sup_formats=AUDIO_FORMAT_PCM_16_BIT" */ +#define AUDIO_PARAMETER_STREAM_SUP_FORMATS "sup_formats" +/* Query supported channel masks. The response is a '|' separated list of strings from + * audio_channel_mask_t enum e.g: "sup_channels=AUDIO_CHANNEL_OUT_STEREO|AUDIO_CHANNEL_OUT_MONO" */ +#define AUDIO_PARAMETER_STREAM_SUP_CHANNELS "sup_channels" +/* Query supported sampling rates. The response is a '|' separated list of integer values e.g: + * "sup_sampling_rates=44100|48000" */ +#define AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES "sup_sampling_rates" + +/* Set the HW synchronization source for an output stream. */ +#define AUDIO_PARAMETER_STREAM_HW_AV_SYNC "hw_av_sync" + +/** + * audio codec parameters + */ + +#define AUDIO_OFFLOAD_CODEC_PARAMS "music_offload_codec_param" +#define AUDIO_OFFLOAD_CODEC_BIT_PER_SAMPLE "music_offload_bit_per_sample" +#define AUDIO_OFFLOAD_CODEC_BIT_RATE "music_offload_bit_rate" +#define AUDIO_OFFLOAD_CODEC_AVG_BIT_RATE "music_offload_avg_bit_rate" +#define AUDIO_OFFLOAD_CODEC_ID "music_offload_codec_id" +#define AUDIO_OFFLOAD_CODEC_BLOCK_ALIGN "music_offload_block_align" +#define AUDIO_OFFLOAD_CODEC_SAMPLE_RATE "music_offload_sample_rate" +#define AUDIO_OFFLOAD_CODEC_ENCODE_OPTION "music_offload_encode_option" +#define AUDIO_OFFLOAD_CODEC_NUM_CHANNEL "music_offload_num_channels" +#define AUDIO_OFFLOAD_CODEC_DOWN_SAMPLING "music_offload_down_sampling" +#define AUDIO_OFFLOAD_CODEC_DELAY_SAMPLES "delay_samples" +#define AUDIO_OFFLOAD_CODEC_PADDING_SAMPLES "padding_samples" + +/**************************************/ + +/* common audio stream parameters and operations */ +struct audio_stream { + + /** + * Return the sampling rate in Hz - eg. 44100. + */ + uint32_t (*get_sample_rate)(const struct audio_stream *stream); + + /* currently unused - use set_parameters with key + * AUDIO_PARAMETER_STREAM_SAMPLING_RATE + */ + int (*set_sample_rate)(struct audio_stream *stream, uint32_t rate); + + /** + * Return size of input/output buffer in bytes for this stream - eg. 4800. + * It should be a multiple of the frame size. See also get_input_buffer_size. + */ + size_t (*get_buffer_size)(const struct audio_stream *stream); + + /** + * Return the channel mask - + * e.g. AUDIO_CHANNEL_OUT_STEREO or AUDIO_CHANNEL_IN_STEREO + */ + audio_channel_mask_t (*get_channels)(const struct audio_stream *stream); + + /** + * Return the audio format - e.g. AUDIO_FORMAT_PCM_16_BIT + */ + audio_format_t (*get_format)(const struct audio_stream *stream); + + /* currently unused - use set_parameters with key + * AUDIO_PARAMETER_STREAM_FORMAT + */ + int (*set_format)(struct audio_stream *stream, audio_format_t format); + + /** + * Put the audio hardware input/output into standby mode. + * Driver should exit from standby mode at the next I/O operation. + * Returns 0 on success and <0 on failure. + */ + int (*standby)(struct audio_stream *stream); + + /** dump the state of the audio input/output device */ + int (*dump)(const struct audio_stream *stream, int fd); + + /** Return the set of device(s) which this stream is connected to */ + audio_devices_t (*get_device)(const struct audio_stream *stream); + + /** + * Currently unused - set_device() corresponds to set_parameters() with key + * AUDIO_PARAMETER_STREAM_ROUTING for both input and output. + * AUDIO_PARAMETER_STREAM_INPUT_SOURCE is an additional information used by + * input streams only. + */ + int (*set_device)(struct audio_stream *stream, audio_devices_t device); + + /** + * set/get audio stream parameters. The function accepts a list of + * parameter key value pairs in the form: key1=value1;key2=value2;... + * + * Some keys are reserved for standard parameters (See AudioParameter class) + * + * If the implementation does not accept a parameter change while + * the output is active but the parameter is acceptable otherwise, it must + * return -ENOSYS. + * + * The audio flinger will put the stream in standby and then change the + * parameter value. + */ + int (*set_parameters)(struct audio_stream *stream, const char *kv_pairs); + + /* + * Returns a pointer to a heap allocated string. The caller is responsible + * for freeing the memory for it using free(). + */ + char * (*get_parameters)(const struct audio_stream *stream, + const char *keys); + int (*add_audio_effect)(const struct audio_stream *stream, + effect_handle_t effect); + int (*remove_audio_effect)(const struct audio_stream *stream, + effect_handle_t effect); +}; +typedef struct audio_stream audio_stream_t; + +/* type of asynchronous write callback events. Mutually exclusive */ +typedef enum { + STREAM_CBK_EVENT_WRITE_READY, /* non blocking write completed */ + STREAM_CBK_EVENT_DRAIN_READY /* drain completed */ +} stream_callback_event_t; + +typedef int (*stream_callback_t)(stream_callback_event_t event, void *param, void *cookie); + +/* type of drain requested to audio_stream_out->drain(). Mutually exclusive */ +typedef enum { + AUDIO_DRAIN_ALL, /* drain() returns when all data has been played */ + AUDIO_DRAIN_EARLY_NOTIFY /* drain() returns a short time before all data + from the current track has been played to + give time for gapless track switch */ +} audio_drain_type_t; + +/** + * audio_stream_out is the abstraction interface for the audio output hardware. + * + * It provides information about various properties of the audio output + * hardware driver. + */ + +struct audio_stream_out { + /** + * Common methods of the audio stream out. This *must* be the first member of audio_stream_out + * as users of this structure will cast a audio_stream to audio_stream_out pointer in contexts + * where it's known the audio_stream references an audio_stream_out. + */ + struct audio_stream common; + + /** + * Return the audio hardware driver estimated latency in milliseconds. + */ + uint32_t (*get_latency)(const struct audio_stream_out *stream); + + /** + * Use this method in situations where audio mixing is done in the + * hardware. This method serves as a direct interface with hardware, + * allowing you to directly set the volume as apposed to via the framework. + * This method might produce multiple PCM outputs or hardware accelerated + * codecs, such as MP3 or AAC. + */ + int (*set_volume)(struct audio_stream_out *stream, float left, float right); + + /** + * Write audio buffer to driver. Returns number of bytes written, or a + * negative status_t. If at least one frame was written successfully prior to the error, + * it is suggested that the driver return that successful (short) byte count + * and then return an error in the subsequent call. + * + * If set_callback() has previously been called to enable non-blocking mode + * the write() is not allowed to block. It must write only the number of + * bytes that currently fit in the driver/hardware buffer and then return + * this byte count. If this is less than the requested write size the + * callback function must be called when more space is available in the + * driver/hardware buffer. + */ + ssize_t (*write)(struct audio_stream_out *stream, const void* buffer, + size_t bytes); + + /* return the number of audio frames written by the audio dsp to DAC since + * the output has exited standby + */ + int (*get_render_position)(const struct audio_stream_out *stream, + uint32_t *dsp_frames); + + /** + * get the local time at which the next write to the audio driver will be presented. + * The units are microseconds, where the epoch is decided by the local audio HAL. + */ + int (*get_next_write_timestamp)(const struct audio_stream_out *stream, + int64_t *timestamp); + + /** + * set the callback function for notifying completion of non-blocking + * write and drain. + * Calling this function implies that all future write() and drain() + * must be non-blocking and use the callback to signal completion. + */ + int (*set_callback)(struct audio_stream_out *stream, + stream_callback_t callback, void *cookie); + + /** + * Notifies to the audio driver to stop playback however the queued buffers are + * retained by the hardware. Useful for implementing pause/resume. Empty implementation + * if not supported however should be implemented for hardware with non-trivial + * latency. In the pause state audio hardware could still be using power. User may + * consider calling suspend after a timeout. + * + * Implementation of this function is mandatory for offloaded playback. + */ + int (*pause)(struct audio_stream_out* stream); + + /** + * Notifies to the audio driver to resume playback following a pause. + * Returns error if called without matching pause. + * + * Implementation of this function is mandatory for offloaded playback. + */ + int (*resume)(struct audio_stream_out* stream); + + /** + * Requests notification when data buffered by the driver/hardware has + * been played. If set_callback() has previously been called to enable + * non-blocking mode, the drain() must not block, instead it should return + * quickly and completion of the drain is notified through the callback. + * If set_callback() has not been called, the drain() must block until + * completion. + * If type==AUDIO_DRAIN_ALL, the drain completes when all previously written + * data has been played. + * If type==AUDIO_DRAIN_EARLY_NOTIFY, the drain completes shortly before all + * data for the current track has played to allow time for the framework + * to perform a gapless track switch. + * + * Drain must return immediately on stop() and flush() call + * + * Implementation of this function is mandatory for offloaded playback. + */ + int (*drain)(struct audio_stream_out* stream, audio_drain_type_t type ); + + /** + * Notifies to the audio driver to flush the queued data. Stream must already + * be paused before calling flush(). + * + * Implementation of this function is mandatory for offloaded playback. + */ + int (*flush)(struct audio_stream_out* stream); + + /** + * Return a recent count of the number of audio frames presented to an external observer. + * This excludes frames which have been written but are still in the pipeline. + * The count is not reset to zero when output enters standby. + * Also returns the value of CLOCK_MONOTONIC as of this presentation count. + * The returned count is expected to be 'recent', + * but does not need to be the most recent possible value. + * However, the associated time should correspond to whatever count is returned. + * Example: assume that N+M frames have been presented, where M is a 'small' number. + * Then it is permissible to return N instead of N+M, + * and the timestamp should correspond to N rather than N+M. + * The terms 'recent' and 'small' are not defined. + * They reflect the quality of the implementation. + * + * 3.0 and higher only. + */ + int (*get_presentation_position)(const struct audio_stream_out *stream, + uint64_t *frames, struct timespec *timestamp); + +}; +typedef struct audio_stream_out audio_stream_out_t; + +struct audio_stream_in { + /** + * Common methods of the audio stream in. This *must* be the first member of audio_stream_in + * as users of this structure will cast a audio_stream to audio_stream_in pointer in contexts + * where it's known the audio_stream references an audio_stream_in. + */ + struct audio_stream common; + + /** set the input gain for the audio driver. This method is for + * for future use */ + int (*set_gain)(struct audio_stream_in *stream, float gain); + + /** Read audio buffer in from audio driver. Returns number of bytes read, or a + * negative status_t. If at least one frame was read prior to the error, + * read should return that byte count and then return an error in the subsequent call. + */ + ssize_t (*read)(struct audio_stream_in *stream, void* buffer, + size_t bytes); + + /** + * Return the amount of input frames lost in the audio driver since the + * last call of this function. + * Audio driver is expected to reset the value to 0 and restart counting + * upon returning the current value by this function call. + * Such loss typically occurs when the user space process is blocked + * longer than the capacity of audio driver buffers. + * + * Unit: the number of input audio frames + */ + uint32_t (*get_input_frames_lost)(struct audio_stream_in *stream); +}; +typedef struct audio_stream_in audio_stream_in_t; + +/** + * return the frame size (number of bytes per sample). + * + * Deprecated: use audio_stream_out_frame_size() or audio_stream_in_frame_size() instead. + */ +__attribute__((__deprecated__)) +static inline size_t audio_stream_frame_size(const struct audio_stream *s) +{ + size_t chan_samp_sz; + audio_format_t format = s->get_format(s); + + if (audio_is_linear_pcm(format)) { + chan_samp_sz = audio_bytes_per_sample(format); + return popcount(s->get_channels(s)) * chan_samp_sz; + } + + return sizeof(int8_t); +} + +/** + * return the frame size (number of bytes per sample) of an output stream. + */ +static inline size_t audio_stream_out_frame_size(const struct audio_stream_out *s) +{ + size_t chan_samp_sz; + audio_format_t format = s->common.get_format(&s->common); + + if (audio_is_linear_pcm(format)) { + chan_samp_sz = audio_bytes_per_sample(format); + return audio_channel_count_from_out_mask(s->common.get_channels(&s->common)) * chan_samp_sz; + } + + return sizeof(int8_t); +} + +/** + * return the frame size (number of bytes per sample) of an input stream. + */ +static inline size_t audio_stream_in_frame_size(const struct audio_stream_in *s) +{ + size_t chan_samp_sz; + audio_format_t format = s->common.get_format(&s->common); + + if (audio_is_linear_pcm(format)) { + chan_samp_sz = audio_bytes_per_sample(format); + return audio_channel_count_from_in_mask(s->common.get_channels(&s->common)) * chan_samp_sz; + } + + return sizeof(int8_t); +} + +/**********************************************************************/ + +/** + * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM + * and the fields of this data structure must begin with hw_module_t + * followed by module specific information. + */ +struct audio_module { + struct hw_module_t common; +}; + +struct audio_hw_device { + /** + * Common methods of the audio device. This *must* be the first member of audio_hw_device + * as users of this structure will cast a hw_device_t to audio_hw_device pointer in contexts + * where it's known the hw_device_t references an audio_hw_device. + */ + struct hw_device_t common; + + /** + * used by audio flinger to enumerate what devices are supported by + * each audio_hw_device implementation. + * + * Return value is a bitmask of 1 or more values of audio_devices_t + * + * NOTE: audio HAL implementations starting with + * AUDIO_DEVICE_API_VERSION_2_0 do not implement this function. + * All supported devices should be listed in audio_policy.conf + * file and the audio policy manager must choose the appropriate + * audio module based on information in this file. + */ + uint32_t (*get_supported_devices)(const struct audio_hw_device *dev); + + /** + * check to see if the audio hardware interface has been initialized. + * returns 0 on success, -ENODEV on failure. + */ + int (*init_check)(const struct audio_hw_device *dev); + + /** set the audio volume of a voice call. Range is between 0.0 and 1.0 */ + int (*set_voice_volume)(struct audio_hw_device *dev, float volume); + + /** + * set the audio volume for all audio activities other than voice call. + * Range between 0.0 and 1.0. If any value other than 0 is returned, + * the software mixer will emulate this capability. + */ + int (*set_master_volume)(struct audio_hw_device *dev, float volume); + + /** + * Get the current master volume value for the HAL, if the HAL supports + * master volume control. AudioFlinger will query this value from the + * primary audio HAL when the service starts and use the value for setting + * the initial master volume across all HALs. HALs which do not support + * this method may leave it set to NULL. + */ + int (*get_master_volume)(struct audio_hw_device *dev, float *volume); + + /** + * set_mode is called when the audio mode changes. AUDIO_MODE_NORMAL mode + * is for standard audio playback, AUDIO_MODE_RINGTONE when a ringtone is + * playing, and AUDIO_MODE_IN_CALL when a call is in progress. + */ + int (*set_mode)(struct audio_hw_device *dev, audio_mode_t mode); + + /* mic mute */ + int (*set_mic_mute)(struct audio_hw_device *dev, bool state); + int (*get_mic_mute)(const struct audio_hw_device *dev, bool *state); + + /* set/get global audio parameters */ + int (*set_parameters)(struct audio_hw_device *dev, const char *kv_pairs); + + /* + * Returns a pointer to a heap allocated string. The caller is responsible + * for freeing the memory for it using free(). + */ + char * (*get_parameters)(const struct audio_hw_device *dev, + const char *keys); + + /* Returns audio input buffer size according to parameters passed or + * 0 if one of the parameters is not supported. + * See also get_buffer_size which is for a particular stream. + */ + size_t (*get_input_buffer_size)(const struct audio_hw_device *dev, + const struct audio_config *config); + + /** This method creates and opens the audio hardware output stream. + * The "address" parameter qualifies the "devices" audio device type if needed. + * The format format depends on the device type: + * - Bluetooth devices use the MAC address of the device in the form "00:11:22:AA:BB:CC" + * - USB devices use the ALSA card and device numbers in the form "card=X;device=Y" + * - Other devices may use a number or any other string. + */ + + int (*open_output_stream)(struct audio_hw_device *dev, + audio_io_handle_t handle, + audio_devices_t devices, + audio_output_flags_t flags, + struct audio_config *config, + struct audio_stream_out **stream_out, + const char *address); + + void (*close_output_stream)(struct audio_hw_device *dev, + struct audio_stream_out* stream_out); + + /** This method creates and opens the audio hardware input stream */ + int (*open_input_stream)(struct audio_hw_device *dev, + audio_io_handle_t handle, + audio_devices_t devices, + struct audio_config *config, + struct audio_stream_in **stream_in, + audio_input_flags_t flags, + const char *address, + audio_source_t source); + + void (*close_input_stream)(struct audio_hw_device *dev, + struct audio_stream_in *stream_in); + + /** This method dumps the state of the audio hardware */ + int (*dump)(const struct audio_hw_device *dev, int fd); + + /** + * set the audio mute status for all audio activities. If any value other + * than 0 is returned, the software mixer will emulate this capability. + */ + int (*set_master_mute)(struct audio_hw_device *dev, bool mute); + + /** + * Get the current master mute status for the HAL, if the HAL supports + * master mute control. AudioFlinger will query this value from the primary + * audio HAL when the service starts and use the value for setting the + * initial master mute across all HALs. HALs which do not support this + * method may leave it set to NULL. + */ + int (*get_master_mute)(struct audio_hw_device *dev, bool *mute); + + /** + * Routing control + */ + + /* Creates an audio patch between several source and sink ports. + * The handle is allocated by the HAL and should be unique for this + * audio HAL module. */ + int (*create_audio_patch)(struct audio_hw_device *dev, + unsigned int num_sources, + const struct audio_port_config *sources, + unsigned int num_sinks, + const struct audio_port_config *sinks, + audio_patch_handle_t *handle); + + /* Release an audio patch */ + int (*release_audio_patch)(struct audio_hw_device *dev, + audio_patch_handle_t handle); + + /* Fills the list of supported attributes for a given audio port. + * As input, "port" contains the information (type, role, address etc...) + * needed by the HAL to identify the port. + * As output, "port" contains possible attributes (sampling rates, formats, + * channel masks, gain controllers...) for this port. + */ + int (*get_audio_port)(struct audio_hw_device *dev, + struct audio_port *port); + + /* Set audio port configuration */ + int (*set_audio_port_config)(struct audio_hw_device *dev, + const struct audio_port_config *config); + +#ifdef AUDIO_LISTEN_ENABLED + /** This method creates the listen session and returns handle */ + int (*open_listen_session)(struct audio_hw_device *dev, + listen_open_params_t *params, + struct listen_session** handle); + + /** This method closes the listen session */ + int (*close_listen_session)(struct audio_hw_device *dev, + struct listen_session* handle); + + /** This method sets the mad observer callback */ + int (*set_mad_observer)(struct audio_hw_device *dev, + listen_callback_t cb_func); + + /** + * This method is used for setting listen hal specfic parameters. + * If multiple paramets are set in one call and setting any one of them + * fails it will return failure. + */ + int (*listen_set_parameters)(struct audio_hw_device *dev, + const char *kv_pairs); +#endif +}; +typedef struct audio_hw_device audio_hw_device_t; + +/** convenience API for opening and closing a supported device */ + +static inline int audio_hw_device_open(const struct hw_module_t* module, + struct audio_hw_device** device) +{ + return module->methods->open(module, AUDIO_HARDWARE_INTERFACE, + (struct hw_device_t**)device); +} + +static inline int audio_hw_device_close(struct audio_hw_device* device) +{ + return device->common.close(&device->common); +} + + +__END_DECLS + +#endif // ANDROID_AUDIO_INTERFACE_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/audio_alsaops.h b/phonelibs/android_hardware_libhardware/include/hardware/audio_alsaops.h new file mode 100644 index 0000000000..0d266ff554 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/audio_alsaops.h @@ -0,0 +1,102 @@ +/* + * Copyright (C) 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. + */ + +/* This file contains shared utility functions to handle the tinyalsa + * implementation for Android internal audio, generally in the hardware layer. + * Some routines may log a fatal error on failure, as noted. + */ + +#ifndef ANDROID_AUDIO_ALSAOPS_H +#define ANDROID_AUDIO_ALSAOPS_H + +#include +#include +#include + +__BEGIN_DECLS + +/* Converts audio_format to pcm_format. + * Parameters: + * format the audio_format_t to convert + * + * Logs a fatal error if format is not a valid convertible audio_format_t. + */ +static inline enum pcm_format pcm_format_from_audio_format(audio_format_t format) +{ + switch (format) { +#ifdef HAVE_BIG_ENDIAN + case AUDIO_FORMAT_PCM_16_BIT: + return PCM_FORMAT_S16_BE; + case AUDIO_FORMAT_PCM_24_BIT_PACKED: + return PCM_FORMAT_S24_3BE; + case AUDIO_FORMAT_PCM_32_BIT: + return PCM_FORMAT_S32_BE; + case AUDIO_FORMAT_PCM_8_24_BIT: + return PCM_FORMAT_S24_BE; +#else + case AUDIO_FORMAT_PCM_16_BIT: + return PCM_FORMAT_S16_LE; + case AUDIO_FORMAT_PCM_24_BIT_PACKED: + return PCM_FORMAT_S24_3LE; + case AUDIO_FORMAT_PCM_32_BIT: + return PCM_FORMAT_S32_LE; + case AUDIO_FORMAT_PCM_8_24_BIT: + return PCM_FORMAT_S24_LE; +#endif + case AUDIO_FORMAT_PCM_FLOAT: /* there is no equivalent for float */ + default: + LOG_ALWAYS_FATAL("pcm_format_from_audio_format: invalid audio format %#x", format); + return 0; + } +} + +/* Converts pcm_format to audio_format. + * Parameters: + * format the pcm_format to convert + * + * Logs a fatal error if format is not a valid convertible pcm_format. + */ +static inline audio_format_t audio_format_from_pcm_format(enum pcm_format format) +{ + switch (format) { +#ifdef HAVE_BIG_ENDIAN + case PCM_FORMAT_S16_BE: + return AUDIO_FORMAT_PCM_16_BIT; + case PCM_FORMAT_S24_3BE: + return AUDIO_FORMAT_PCM_24_BIT_PACKED; + case PCM_FORMAT_S24_BE: + return AUDIO_FORMAT_PCM_8_24_BIT; + case PCM_FORMAT_S32_BE: + return AUDIO_FORMAT_PCM_32_BIT; +#else + case PCM_FORMAT_S16_LE: + return AUDIO_FORMAT_PCM_16_BIT; + case PCM_FORMAT_S24_3LE: + return AUDIO_FORMAT_PCM_24_BIT_PACKED; + case PCM_FORMAT_S24_LE: + return AUDIO_FORMAT_PCM_8_24_BIT; + case PCM_FORMAT_S32_LE: + return AUDIO_FORMAT_PCM_32_BIT; +#endif + default: + LOG_ALWAYS_FATAL("audio_format_from_pcm_format: invalid pcm format %#x", format); + return 0; + } +} + +__END_DECLS + +#endif /* ANDROID_AUDIO_ALSAOPS_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/audio_amplifier.h b/phonelibs/android_hardware_libhardware/include/hardware/audio_amplifier.h new file mode 100644 index 0000000000..e3477d52ad --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/audio_amplifier.h @@ -0,0 +1,144 @@ +/* + * 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 CM_AUDIO_AMPLIFIER_INTERFACE_H +#define CM_AUDIO_AMPLIFIER_INTERFACE_H + +#include +#include +#include + +#include +#include + +#include + +__BEGIN_DECLS + +#define AMPLIFIER_HARDWARE_MODULE_ID "audio_amplifier" + +#define AMPLIFIER_HARDWARE_INTERFACE "audio_amplifier_hw_if" + +#define AMPLIFIER_MODULE_API_VERSION_0_1 HARDWARE_MODULE_API_VERSION(0, 1) + +#define AMPLIFIER_DEVICE_API_VERSION_1_0 HARDWARE_DEVICE_API_VERSION(1, 0) +#define AMPLIFIER_DEVICE_API_VERSION_2_0 HARDWARE_DEVICE_API_VERSION(2, 0) +#define AMPLIFIER_DEVICE_API_VERSION_CURRENT AMPLIFIER_DEVICE_API_VERSION_2_0 + +struct str_parms; + +typedef struct amplifier_device { + /** + * Common methods of the amplifier device. This *must* be the first member + * of amplifier_device as users of this structure will cast a hw_device_t + * to amplifier_device pointer in contexts where it's known + * the hw_device_t references a amplifier_device. + */ + struct hw_device_t common; + + /** + * Notify amplifier device of current input devices + * + * This function should handle only input devices. + */ + int (*set_input_devices)(struct amplifier_device *device, uint32_t devices); + + /** + * Notify amplifier device of current output devices + * + * This function should handle only output devices. + */ + int (*set_output_devices)(struct amplifier_device *device, uint32_t devices); + + /** + * Notify amplifier device of output device enable/disable + * + * This function should handle only output devices. + */ + int (*enable_output_devices)(struct amplifier_device *device, + uint32_t devices, bool enable); + + /** + * Notify amplifier device of input device enable/disable + * + * This function should handle only input devices. + */ + int (*enable_input_devices)(struct amplifier_device *device, + uint32_t devices, bool enable); + + /** + * Notify amplifier device about current audio mode + */ + int (*set_mode)(struct amplifier_device *device, audio_mode_t mode); + + /** + * Notify amplifier device that an output stream has started + */ + int (*output_stream_start)(struct amplifier_device *device, + struct audio_stream_out *stream, bool offload); + + /** + * Notify amplifier device that an input stream has started + */ + int (*input_stream_start)(struct amplifier_device *device, + struct audio_stream_in *stream); + + /** + * Notify amplifier device that an output stream has stopped + */ + int (*output_stream_standby)(struct amplifier_device *device, + struct audio_stream_out *stream); + + /** + * Notify amplifier device that an input stream has stopped + */ + int (*input_stream_standby)(struct amplifier_device *device, + struct audio_stream_in *stream); + + /** + * set/get output audio device parameters. + */ + int (*set_parameters)(struct amplifier_device *device, + struct str_parms *parms); +} amplifier_device_t; + +typedef struct amplifier_module { + /** + * Common methods of the amplifier module. This *must* be the first member + * of amplifier_module as users of this structure will cast a hw_module_t + * to amplifier_module pointer in contexts where it's known + * the hw_module_t references a amplifier_module. + */ + struct hw_module_t common; +} amplifier_module_t; + +/** convenience API for opening and closing a supported device */ + +static inline int amplifier_device_open(const struct hw_module_t *module, + struct amplifier_device **device) +{ + return module->methods->open(module, AMPLIFIER_HARDWARE_INTERFACE, + (struct hw_device_t **) device); +} + +static inline int amplifier_device_close(struct amplifier_device *device) +{ + return device->common.close(&device->common); +} + +__END_DECLS + +#endif // CM_AUDIO_AMPLIFIER_INTERFACE_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/audio_effect.h b/phonelibs/android_hardware_libhardware/include/hardware/audio_effect.h new file mode 100644 index 0000000000..41cd2e6146 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/audio_effect.h @@ -0,0 +1,1014 @@ +/* + * 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_AUDIO_EFFECT_H +#define ANDROID_AUDIO_EFFECT_H + +#include +#include +#include +#include +#include + +#include + +#include + + +__BEGIN_DECLS + + +///////////////////////////////////////////////// +// Common Definitions +///////////////////////////////////////////////// + +// +//--- Effect descriptor structure effect_descriptor_t +// + +// Unique effect ID (can be generated from the following site: +// http://www.itu.int/ITU-T/asn1/uuid.html) +// This format is used for both "type" and "uuid" fields of the effect descriptor structure. +// - When used for effect type and the engine is implementing and effect corresponding to a standard +// OpenSL ES interface, this ID must be the one defined in OpenSLES_IID.h for that interface. +// - When used as uuid, it should be a unique UUID for this particular implementation. +typedef struct effect_uuid_s { + uint32_t timeLow; + uint16_t timeMid; + uint16_t timeHiAndVersion; + uint16_t clockSeq; + uint8_t node[6]; +} effect_uuid_t; + +// Maximum length of character strings in structures defines by this API. +#define EFFECT_STRING_LEN_MAX 64 + +// NULL UUID definition (matches SL_IID_NULL_) +#define EFFECT_UUID_INITIALIZER { 0xec7178ec, 0xe5e1, 0x4432, 0xa3f4, \ + { 0x46, 0x57, 0xe6, 0x79, 0x52, 0x10 } } +static const effect_uuid_t EFFECT_UUID_NULL_ = EFFECT_UUID_INITIALIZER; +static const effect_uuid_t * const EFFECT_UUID_NULL = &EFFECT_UUID_NULL_; +static const char * const EFFECT_UUID_NULL_STR = "ec7178ec-e5e1-4432-a3f4-4657e6795210"; + + +// The effect descriptor contains necessary information to facilitate the enumeration of the effect +// engines present in a library. +typedef struct effect_descriptor_s { + effect_uuid_t type; // UUID of to the OpenSL ES interface implemented by this effect + effect_uuid_t uuid; // UUID for this particular implementation + uint32_t apiVersion; // Version of the effect control API implemented + uint32_t flags; // effect engine capabilities/requirements flags (see below) + uint16_t cpuLoad; // CPU load indication (see below) + uint16_t memoryUsage; // Data Memory usage (see below) + char name[EFFECT_STRING_LEN_MAX]; // human readable effect name + char implementor[EFFECT_STRING_LEN_MAX]; // human readable effect implementor name +} effect_descriptor_t; + +// CPU load and memory usage indication: each effect implementation must provide an indication of +// its CPU and memory usage for the audio effect framework to limit the number of effects +// instantiated at a given time on a given platform. +// The CPU load is expressed in 0.1 MIPS units as estimated on an ARM9E core (ARMv5TE) with 0 WS. +// The memory usage is expressed in KB and includes only dynamically allocated memory + +// Definitions for flags field of effect descriptor. +// +---------------------------+-----------+----------------------------------- +// | description | bits | values +// +---------------------------+-----------+----------------------------------- +// | connection mode | 0..2 | 0 insert: after track process +// | | | 1 auxiliary: connect to track auxiliary +// | | | output and use send level +// | | | 2 replace: replaces track process function; +// | | | must implement SRC, volume and mono to stereo. +// | | | 3 pre processing: applied below audio HAL on input +// | | | 4 post processing: applied below audio HAL on output +// | | | 5 - 7 reserved +// +---------------------------+-----------+----------------------------------- +// | insertion preference | 3..5 | 0 none +// | | | 1 first of the chain +// | | | 2 last of the chain +// | | | 3 exclusive (only effect in the insert chain) +// | | | 4..7 reserved +// +---------------------------+-----------+----------------------------------- +// | Volume management | 6..8 | 0 none +// | | | 1 implements volume control +// | | | 2 requires volume indication +// | | | 4 reserved +// +---------------------------+-----------+----------------------------------- +// | Device indication | 9..11 | 0 none +// | | | 1 requires device updates +// | | | 2, 4 reserved +// +---------------------------+-----------+----------------------------------- +// | Sample input mode | 12..13 | 1 direct: process() function or EFFECT_CMD_SET_CONFIG +// | | | command must specify a buffer descriptor +// | | | 2 provider: process() function uses the +// | | | bufferProvider indicated by the +// | | | EFFECT_CMD_SET_CONFIG command to request input. +// | | | buffers. +// | | | 3 both: both input modes are supported +// +---------------------------+-----------+----------------------------------- +// | Sample output mode | 14..15 | 1 direct: process() function or EFFECT_CMD_SET_CONFIG +// | | | command must specify a buffer descriptor +// | | | 2 provider: process() function uses the +// | | | bufferProvider indicated by the +// | | | EFFECT_CMD_SET_CONFIG command to request output +// | | | buffers. +// | | | 3 both: both output modes are supported +// +---------------------------+-----------+----------------------------------- +// | Hardware acceleration | 16..17 | 0 No hardware acceleration +// | | | 1 non tunneled hw acceleration: the process() function +// | | | reads the samples, send them to HW accelerated +// | | | effect processor, reads back the processed samples +// | | | and returns them to the output buffer. +// | | | 2 tunneled hw acceleration: the process() function is +// | | | transparent. The effect interface is only used to +// | | | control the effect engine. This mode is relevant for +// | | | global effects actually applied by the audio +// | | | hardware on the output stream. +// +---------------------------+-----------+----------------------------------- +// | Audio Mode indication | 18..19 | 0 none +// | | | 1 requires audio mode updates +// | | | 2..3 reserved +// +---------------------------+-----------+----------------------------------- +// | Audio source indication | 20..21 | 0 none +// | | | 1 requires audio source updates +// | | | 2..3 reserved +// +---------------------------+-----------+----------------------------------- +// | Effect offload supported | 22 | 0 The effect cannot be offloaded to an audio DSP +// | | | 1 The effect can be offloaded to an audio DSP +// +---------------------------+-----------+----------------------------------- + +// Insert mode +#define EFFECT_FLAG_TYPE_SHIFT 0 +#define EFFECT_FLAG_TYPE_SIZE 3 +#define EFFECT_FLAG_TYPE_MASK (((1 << EFFECT_FLAG_TYPE_SIZE) -1) \ + << EFFECT_FLAG_TYPE_SHIFT) +#define EFFECT_FLAG_TYPE_INSERT (0 << EFFECT_FLAG_TYPE_SHIFT) +#define EFFECT_FLAG_TYPE_AUXILIARY (1 << EFFECT_FLAG_TYPE_SHIFT) +#define EFFECT_FLAG_TYPE_REPLACE (2 << EFFECT_FLAG_TYPE_SHIFT) +#define EFFECT_FLAG_TYPE_PRE_PROC (3 << EFFECT_FLAG_TYPE_SHIFT) +#define EFFECT_FLAG_TYPE_POST_PROC (4 << EFFECT_FLAG_TYPE_SHIFT) + +// Insert preference +#define EFFECT_FLAG_INSERT_SHIFT (EFFECT_FLAG_TYPE_SHIFT + EFFECT_FLAG_TYPE_SIZE) +#define EFFECT_FLAG_INSERT_SIZE 3 +#define EFFECT_FLAG_INSERT_MASK (((1 << EFFECT_FLAG_INSERT_SIZE) -1) \ + << EFFECT_FLAG_INSERT_SHIFT) +#define EFFECT_FLAG_INSERT_ANY (0 << EFFECT_FLAG_INSERT_SHIFT) +#define EFFECT_FLAG_INSERT_FIRST (1 << EFFECT_FLAG_INSERT_SHIFT) +#define EFFECT_FLAG_INSERT_LAST (2 << EFFECT_FLAG_INSERT_SHIFT) +#define EFFECT_FLAG_INSERT_EXCLUSIVE (3 << EFFECT_FLAG_INSERT_SHIFT) + + +// Volume control +#define EFFECT_FLAG_VOLUME_SHIFT (EFFECT_FLAG_INSERT_SHIFT + EFFECT_FLAG_INSERT_SIZE) +#define EFFECT_FLAG_VOLUME_SIZE 3 +#define EFFECT_FLAG_VOLUME_MASK (((1 << EFFECT_FLAG_VOLUME_SIZE) -1) \ + << EFFECT_FLAG_VOLUME_SHIFT) +#define EFFECT_FLAG_VOLUME_CTRL (1 << EFFECT_FLAG_VOLUME_SHIFT) +#define EFFECT_FLAG_VOLUME_IND (2 << EFFECT_FLAG_VOLUME_SHIFT) +#define EFFECT_FLAG_VOLUME_NONE (0 << EFFECT_FLAG_VOLUME_SHIFT) + +// Device indication +#define EFFECT_FLAG_DEVICE_SHIFT (EFFECT_FLAG_VOLUME_SHIFT + EFFECT_FLAG_VOLUME_SIZE) +#define EFFECT_FLAG_DEVICE_SIZE 3 +#define EFFECT_FLAG_DEVICE_MASK (((1 << EFFECT_FLAG_DEVICE_SIZE) -1) \ + << EFFECT_FLAG_DEVICE_SHIFT) +#define EFFECT_FLAG_DEVICE_IND (1 << EFFECT_FLAG_DEVICE_SHIFT) +#define EFFECT_FLAG_DEVICE_NONE (0 << EFFECT_FLAG_DEVICE_SHIFT) + +// Sample input modes +#define EFFECT_FLAG_INPUT_SHIFT (EFFECT_FLAG_DEVICE_SHIFT + EFFECT_FLAG_DEVICE_SIZE) +#define EFFECT_FLAG_INPUT_SIZE 2 +#define EFFECT_FLAG_INPUT_MASK (((1 << EFFECT_FLAG_INPUT_SIZE) -1) \ + << EFFECT_FLAG_INPUT_SHIFT) +#define EFFECT_FLAG_INPUT_DIRECT (1 << EFFECT_FLAG_INPUT_SHIFT) +#define EFFECT_FLAG_INPUT_PROVIDER (2 << EFFECT_FLAG_INPUT_SHIFT) +#define EFFECT_FLAG_INPUT_BOTH (3 << EFFECT_FLAG_INPUT_SHIFT) + +// Sample output modes +#define EFFECT_FLAG_OUTPUT_SHIFT (EFFECT_FLAG_INPUT_SHIFT + EFFECT_FLAG_INPUT_SIZE) +#define EFFECT_FLAG_OUTPUT_SIZE 2 +#define EFFECT_FLAG_OUTPUT_MASK (((1 << EFFECT_FLAG_OUTPUT_SIZE) -1) \ + << EFFECT_FLAG_OUTPUT_SHIFT) +#define EFFECT_FLAG_OUTPUT_DIRECT (1 << EFFECT_FLAG_OUTPUT_SHIFT) +#define EFFECT_FLAG_OUTPUT_PROVIDER (2 << EFFECT_FLAG_OUTPUT_SHIFT) +#define EFFECT_FLAG_OUTPUT_BOTH (3 << EFFECT_FLAG_OUTPUT_SHIFT) + +// Hardware acceleration mode +#define EFFECT_FLAG_HW_ACC_SHIFT (EFFECT_FLAG_OUTPUT_SHIFT + EFFECT_FLAG_OUTPUT_SIZE) +#define EFFECT_FLAG_HW_ACC_SIZE 2 +#define EFFECT_FLAG_HW_ACC_MASK (((1 << EFFECT_FLAG_HW_ACC_SIZE) -1) \ + << EFFECT_FLAG_HW_ACC_SHIFT) +#define EFFECT_FLAG_HW_ACC_SIMPLE (1 << EFFECT_FLAG_HW_ACC_SHIFT) +#define EFFECT_FLAG_HW_ACC_TUNNEL (2 << EFFECT_FLAG_HW_ACC_SHIFT) + +// Audio mode indication +#define EFFECT_FLAG_AUDIO_MODE_SHIFT (EFFECT_FLAG_HW_ACC_SHIFT + EFFECT_FLAG_HW_ACC_SIZE) +#define EFFECT_FLAG_AUDIO_MODE_SIZE 2 +#define EFFECT_FLAG_AUDIO_MODE_MASK (((1 << EFFECT_FLAG_AUDIO_MODE_SIZE) -1) \ + << EFFECT_FLAG_AUDIO_MODE_SHIFT) +#define EFFECT_FLAG_AUDIO_MODE_IND (1 << EFFECT_FLAG_AUDIO_MODE_SHIFT) +#define EFFECT_FLAG_AUDIO_MODE_NONE (0 << EFFECT_FLAG_AUDIO_MODE_SHIFT) + +// Audio source indication +#define EFFECT_FLAG_AUDIO_SOURCE_SHIFT (EFFECT_FLAG_AUDIO_MODE_SHIFT + EFFECT_FLAG_AUDIO_MODE_SIZE) +#define EFFECT_FLAG_AUDIO_SOURCE_SIZE 2 +#define EFFECT_FLAG_AUDIO_SOURCE_MASK (((1 << EFFECT_FLAG_AUDIO_SOURCE_SIZE) -1) \ + << EFFECT_FLAG_AUDIO_SOURCE_SHIFT) +#define EFFECT_FLAG_AUDIO_SOURCE_IND (1 << EFFECT_FLAG_AUDIO_SOURCE_SHIFT) +#define EFFECT_FLAG_AUDIO_SOURCE_NONE (0 << EFFECT_FLAG_AUDIO_SOURCE_SHIFT) + +// Effect offload indication +#define EFFECT_FLAG_OFFLOAD_SHIFT (EFFECT_FLAG_AUDIO_SOURCE_SHIFT + \ + EFFECT_FLAG_AUDIO_SOURCE_SIZE) +#define EFFECT_FLAG_OFFLOAD_SIZE 1 +#define EFFECT_FLAG_OFFLOAD_MASK (((1 << EFFECT_FLAG_OFFLOAD_SIZE) -1) \ + << EFFECT_FLAG_OFFLOAD_SHIFT) +#define EFFECT_FLAG_OFFLOAD_SUPPORTED (1 << EFFECT_FLAG_OFFLOAD_SHIFT) + +#define EFFECT_MAKE_API_VERSION(M, m) (((M)<<16) | ((m) & 0xFFFF)) +#define EFFECT_API_VERSION_MAJOR(v) ((v)>>16) +#define EFFECT_API_VERSION_MINOR(v) ((m) & 0xFFFF) + + + +///////////////////////////////////////////////// +// Effect control interface +///////////////////////////////////////////////// + +// Effect control interface version 2.0 +#define EFFECT_CONTROL_API_VERSION EFFECT_MAKE_API_VERSION(2,0) + +// Effect control interface structure: effect_interface_s +// The effect control interface is exposed by each effect engine implementation. It consists of +// a set of functions controlling the configuration, activation and process of the engine. +// The functions are grouped in a structure of type effect_interface_s. +// +// Effect control interface handle: effect_handle_t +// The effect_handle_t serves two purposes regarding the implementation of the effect engine: +// - 1 it is the address of a pointer to an effect_interface_s structure where the functions +// of the effect control API for a particular effect are located. +// - 2 it is the address of the context of a particular effect instance. +// A typical implementation in the effect library would define a structure as follows: +// struct effect_module_s { +// const struct effect_interface_s *itfe; +// effect_config_t config; +// effect_context_t context; +// } +// The implementation of EffectCreate() function would then allocate a structure of this +// type and return its address as effect_handle_t +typedef struct effect_interface_s **effect_handle_t; + + +// Forward definition of type audio_buffer_t +typedef struct audio_buffer_s audio_buffer_t; + + + + + + +// Effect control interface definition +struct effect_interface_s { + //////////////////////////////////////////////////////////////////////////////// + // + // Function: process + // + // Description: Effect process function. Takes input samples as specified + // (count and location) in input buffer descriptor and output processed + // samples as specified in output buffer descriptor. If the buffer descriptor + // is not specified the function must use either the buffer or the + // buffer provider function installed by the EFFECT_CMD_SET_CONFIG command. + // The effect framework will call the process() function after the EFFECT_CMD_ENABLE + // command is received and until the EFFECT_CMD_DISABLE is received. When the engine + // receives the EFFECT_CMD_DISABLE command it should turn off the effect gracefully + // and when done indicate that it is OK to stop calling the process() function by + // returning the -ENODATA status. + // + // NOTE: the process() function implementation should be "real-time safe" that is + // it should not perform blocking calls: malloc/free, sleep, read/write/open/close, + // pthread_cond_wait/pthread_mutex_lock... + // + // Input: + // self: handle to the effect interface this function + // is called on. + // inBuffer: buffer descriptor indicating where to read samples to process. + // If NULL, use the configuration passed by EFFECT_CMD_SET_CONFIG command. + // + // outBuffer: buffer descriptor indicating where to write processed samples. + // If NULL, use the configuration passed by EFFECT_CMD_SET_CONFIG command. + // + // Output: + // returned value: 0 successful operation + // -ENODATA the engine has finished the disable phase and the framework + // can stop calling process() + // -EINVAL invalid interface handle or + // invalid input/output buffer description + //////////////////////////////////////////////////////////////////////////////// + int32_t (*process)(effect_handle_t self, + audio_buffer_t *inBuffer, + audio_buffer_t *outBuffer); + //////////////////////////////////////////////////////////////////////////////// + // + // Function: command + // + // Description: Send a command and receive a response to/from effect engine. + // + // Input: + // self: handle to the effect interface this function + // is called on. + // cmdCode: command code: the command can be a standardized command defined in + // effect_command_e (see below) or a proprietary command. + // cmdSize: size of command in bytes + // pCmdData: pointer to command data + // pReplyData: pointer to reply data + // + // Input/Output: + // replySize: maximum size of reply data as input + // actual size of reply data as output + // + // Output: + // returned value: 0 successful operation + // -EINVAL invalid interface handle or + // invalid command/reply size or format according to + // command code + // The return code should be restricted to indicate problems related to this API + // specification. Status related to the execution of a particular command should be + // indicated as part of the reply field. + // + // *pReplyData updated with command response + // + //////////////////////////////////////////////////////////////////////////////// + int32_t (*command)(effect_handle_t self, + uint32_t cmdCode, + uint32_t cmdSize, + void *pCmdData, + uint32_t *replySize, + void *pReplyData); + //////////////////////////////////////////////////////////////////////////////// + // + // Function: get_descriptor + // + // Description: Returns the effect descriptor + // + // Input: + // self: handle to the effect interface this function + // is called on. + // + // Input/Output: + // pDescriptor: address where to return the effect descriptor. + // + // Output: + // returned value: 0 successful operation. + // -EINVAL invalid interface handle or invalid pDescriptor + // *pDescriptor: updated with the effect descriptor. + // + //////////////////////////////////////////////////////////////////////////////// + int32_t (*get_descriptor)(effect_handle_t self, + effect_descriptor_t *pDescriptor); + //////////////////////////////////////////////////////////////////////////////// + // + // Function: process_reverse + // + // Description: Process reverse stream function. This function is used to pass + // a reference stream to the effect engine. If the engine does not need a reference + // stream, this function pointer can be set to NULL. + // This function would typically implemented by an Echo Canceler. + // + // Input: + // self: handle to the effect interface this function + // is called on. + // inBuffer: buffer descriptor indicating where to read samples to process. + // If NULL, use the configuration passed by EFFECT_CMD_SET_CONFIG_REVERSE command. + // + // outBuffer: buffer descriptor indicating where to write processed samples. + // If NULL, use the configuration passed by EFFECT_CMD_SET_CONFIG_REVERSE command. + // If the buffer and buffer provider in the configuration received by + // EFFECT_CMD_SET_CONFIG_REVERSE are also NULL, do not return modified reverse + // stream data + // + // Output: + // returned value: 0 successful operation + // -ENODATA the engine has finished the disable phase and the framework + // can stop calling process_reverse() + // -EINVAL invalid interface handle or + // invalid input/output buffer description + //////////////////////////////////////////////////////////////////////////////// + int32_t (*process_reverse)(effect_handle_t self, + audio_buffer_t *inBuffer, + audio_buffer_t *outBuffer); +}; + + +// +//--- Standardized command codes for command() function +// +enum effect_command_e { + EFFECT_CMD_INIT, // initialize effect engine + EFFECT_CMD_SET_CONFIG, // configure effect engine (see effect_config_t) + EFFECT_CMD_RESET, // reset effect engine + EFFECT_CMD_ENABLE, // enable effect process + EFFECT_CMD_DISABLE, // disable effect process + EFFECT_CMD_SET_PARAM, // set parameter immediately (see effect_param_t) + EFFECT_CMD_SET_PARAM_DEFERRED, // set parameter deferred + EFFECT_CMD_SET_PARAM_COMMIT, // commit previous set parameter deferred + EFFECT_CMD_GET_PARAM, // get parameter + EFFECT_CMD_SET_DEVICE, // set audio device (see audio.h, audio_devices_t) + EFFECT_CMD_SET_VOLUME, // set volume + EFFECT_CMD_SET_AUDIO_MODE, // set the audio mode (normal, ring, ...) + EFFECT_CMD_SET_CONFIG_REVERSE, // configure effect engine reverse stream(see effect_config_t) + EFFECT_CMD_SET_INPUT_DEVICE, // set capture device (see audio.h, audio_devices_t) + EFFECT_CMD_GET_CONFIG, // read effect engine configuration + EFFECT_CMD_GET_CONFIG_REVERSE, // read configure effect engine reverse stream configuration + EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS,// get all supported configurations for a feature. + EFFECT_CMD_GET_FEATURE_CONFIG, // get current feature configuration + EFFECT_CMD_SET_FEATURE_CONFIG, // set current feature configuration + EFFECT_CMD_SET_AUDIO_SOURCE, // set the audio source (see audio.h, audio_source_t) + EFFECT_CMD_OFFLOAD, // set if effect thread is an offload one, + // send the ioHandle of the effect thread + EFFECT_CMD_FIRST_PROPRIETARY = 0x10000 // first proprietary command code +}; + +//================================================================================================== +// command: EFFECT_CMD_INIT +//-------------------------------------------------------------------------------------------------- +// description: +// Initialize effect engine: All configurations return to default +//-------------------------------------------------------------------------------------------------- +// command format: +// size: 0 +// data: N/A +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: sizeof(int) +// data: status +//================================================================================================== +// command: EFFECT_CMD_SET_CONFIG +//-------------------------------------------------------------------------------------------------- +// description: +// Apply new audio parameters configurations for input and output buffers +//-------------------------------------------------------------------------------------------------- +// command format: +// size: sizeof(effect_config_t) +// data: effect_config_t +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: sizeof(int) +// data: status +//================================================================================================== +// command: EFFECT_CMD_RESET +//-------------------------------------------------------------------------------------------------- +// description: +// Reset the effect engine. Keep configuration but resets state and buffer content +//-------------------------------------------------------------------------------------------------- +// command format: +// size: 0 +// data: N/A +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: 0 +// data: N/A +//================================================================================================== +// command: EFFECT_CMD_ENABLE +//-------------------------------------------------------------------------------------------------- +// description: +// Enable the process. Called by the framework before the first call to process() +//-------------------------------------------------------------------------------------------------- +// command format: +// size: 0 +// data: N/A +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: sizeof(int) +// data: status +//================================================================================================== +// command: EFFECT_CMD_DISABLE +//-------------------------------------------------------------------------------------------------- +// description: +// Disable the process. Called by the framework after the last call to process() +//-------------------------------------------------------------------------------------------------- +// command format: +// size: 0 +// data: N/A +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: sizeof(int) +// data: status +//================================================================================================== +// command: EFFECT_CMD_SET_PARAM +//-------------------------------------------------------------------------------------------------- +// description: +// Set a parameter and apply it immediately +//-------------------------------------------------------------------------------------------------- +// command format: +// size: sizeof(effect_param_t) + size of param and value +// data: effect_param_t + param + value. See effect_param_t definition below for value offset +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: sizeof(int) +// data: status +//================================================================================================== +// command: EFFECT_CMD_SET_PARAM_DEFERRED +//-------------------------------------------------------------------------------------------------- +// description: +// Set a parameter but apply it only when receiving EFFECT_CMD_SET_PARAM_COMMIT command +//-------------------------------------------------------------------------------------------------- +// command format: +// size: sizeof(effect_param_t) + size of param and value +// data: effect_param_t + param + value. See effect_param_t definition below for value offset +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: 0 +// data: N/A +//================================================================================================== +// command: EFFECT_CMD_SET_PARAM_COMMIT +//-------------------------------------------------------------------------------------------------- +// description: +// Apply all previously received EFFECT_CMD_SET_PARAM_DEFERRED commands +//-------------------------------------------------------------------------------------------------- +// command format: +// size: 0 +// data: N/A +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: sizeof(int) +// data: status +//================================================================================================== +// command: EFFECT_CMD_GET_PARAM +//-------------------------------------------------------------------------------------------------- +// description: +// Get a parameter value +//-------------------------------------------------------------------------------------------------- +// command format: +// size: sizeof(effect_param_t) + size of param +// data: effect_param_t + param +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: sizeof(effect_param_t) + size of param and value +// data: effect_param_t + param + value. See effect_param_t definition below for value offset +//================================================================================================== +// command: EFFECT_CMD_SET_DEVICE +//-------------------------------------------------------------------------------------------------- +// description: +// Set the rendering device the audio output path is connected to. See audio.h, audio_devices_t +// for device values. +// The effect implementation must set EFFECT_FLAG_DEVICE_IND flag in its descriptor to receive this +// command when the device changes +//-------------------------------------------------------------------------------------------------- +// command format: +// size: sizeof(uint32_t) +// data: uint32_t +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: 0 +// data: N/A +//================================================================================================== +// command: EFFECT_CMD_SET_VOLUME +//-------------------------------------------------------------------------------------------------- +// description: +// Set and get volume. Used by audio framework to delegate volume control to effect engine. +// The effect implementation must set EFFECT_FLAG_VOLUME_IND or EFFECT_FLAG_VOLUME_CTRL flag in +// its descriptor to receive this command before every call to process() function +// If EFFECT_FLAG_VOLUME_CTRL flag is set in the effect descriptor, the effect engine must return +// the volume that should be applied before the effect is processed. The overall volume (the volume +// actually applied by the effect engine multiplied by the returned value) should match the value +// indicated in the command. +//-------------------------------------------------------------------------------------------------- +// command format: +// size: n * sizeof(uint32_t) +// data: volume for each channel defined in effect_config_t for output buffer expressed in +// 8.24 fixed point format +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: n * sizeof(uint32_t) / 0 +// data: - if EFFECT_FLAG_VOLUME_CTRL is set in effect descriptor: +// volume for each channel defined in effect_config_t for output buffer expressed in +// 8.24 fixed point format +// - if EFFECT_FLAG_VOLUME_CTRL is not set in effect descriptor: +// N/A +// It is legal to receive a null pointer as pReplyData in which case the effect framework has +// delegated volume control to another effect +//================================================================================================== +// command: EFFECT_CMD_SET_AUDIO_MODE +//-------------------------------------------------------------------------------------------------- +// description: +// Set the audio mode. The effect implementation must set EFFECT_FLAG_AUDIO_MODE_IND flag in its +// descriptor to receive this command when the audio mode changes. +//-------------------------------------------------------------------------------------------------- +// command format: +// size: sizeof(uint32_t) +// data: audio_mode_t +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: 0 +// data: N/A +//================================================================================================== +// command: EFFECT_CMD_SET_CONFIG_REVERSE +//-------------------------------------------------------------------------------------------------- +// description: +// Apply new audio parameters configurations for input and output buffers of reverse stream. +// An example of reverse stream is the echo reference supplied to an Acoustic Echo Canceler. +//-------------------------------------------------------------------------------------------------- +// command format: +// size: sizeof(effect_config_t) +// data: effect_config_t +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: sizeof(int) +// data: status +//================================================================================================== +// command: EFFECT_CMD_SET_INPUT_DEVICE +//-------------------------------------------------------------------------------------------------- +// description: +// Set the capture device the audio input path is connected to. See audio.h, audio_devices_t +// for device values. +// The effect implementation must set EFFECT_FLAG_DEVICE_IND flag in its descriptor to receive this +// command when the device changes +//-------------------------------------------------------------------------------------------------- +// command format: +// size: sizeof(uint32_t) +// data: uint32_t +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: 0 +// data: N/A +//================================================================================================== +// command: EFFECT_CMD_GET_CONFIG +//-------------------------------------------------------------------------------------------------- +// description: +// Read audio parameters configurations for input and output buffers +//-------------------------------------------------------------------------------------------------- +// command format: +// size: 0 +// data: N/A +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: sizeof(effect_config_t) +// data: effect_config_t +//================================================================================================== +// command: EFFECT_CMD_GET_CONFIG_REVERSE +//-------------------------------------------------------------------------------------------------- +// description: +// Read audio parameters configurations for input and output buffers of reverse stream +//-------------------------------------------------------------------------------------------------- +// command format: +// size: 0 +// data: N/A +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: sizeof(effect_config_t) +// data: effect_config_t +//================================================================================================== +// command: EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS +//-------------------------------------------------------------------------------------------------- +// description: +// Queries for supported configurations for a particular feature (e.g. get the supported +// combinations of main and auxiliary channels for a noise suppressor). +// The command parameter is the feature identifier (See effect_feature_e for a list of defined +// features) followed by the maximum number of configuration descriptor to return. +// The reply is composed of: +// - status (uint32_t): +// - 0 if feature is supported +// - -ENOSYS if the feature is not supported, +// - -ENOMEM if the feature is supported but the total number of supported configurations +// exceeds the maximum number indicated by the caller. +// - total number of supported configurations (uint32_t) +// - an array of configuration descriptors. +// The actual number of descriptors returned must not exceed the maximum number indicated by +// the caller. +//-------------------------------------------------------------------------------------------------- +// command format: +// size: 2 x sizeof(uint32_t) +// data: effect_feature_e + maximum number of configurations to return +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: 2 x sizeof(uint32_t) + n x sizeof () +// data: status + total number of configurations supported + array of n config descriptors +//================================================================================================== +// command: EFFECT_CMD_GET_FEATURE_CONFIG +//-------------------------------------------------------------------------------------------------- +// description: +// Retrieves current configuration for a given feature. +// The reply status is: +// - 0 if feature is supported +// - -ENOSYS if the feature is not supported, +//-------------------------------------------------------------------------------------------------- +// command format: +// size: sizeof(uint32_t) +// data: effect_feature_e +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: sizeof(uint32_t) + sizeof () +// data: status + config descriptor +//================================================================================================== +// command: EFFECT_CMD_SET_FEATURE_CONFIG +//-------------------------------------------------------------------------------------------------- +// description: +// Sets current configuration for a given feature. +// The reply status is: +// - 0 if feature is supported +// - -ENOSYS if the feature is not supported, +// - -EINVAL if the configuration is invalid +//-------------------------------------------------------------------------------------------------- +// command format: +// size: sizeof(uint32_t) + sizeof () +// data: effect_feature_e + config descriptor +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: sizeof(uint32_t) +// data: status +//================================================================================================== +// command: EFFECT_CMD_SET_AUDIO_SOURCE +//-------------------------------------------------------------------------------------------------- +// description: +// Set the audio source the capture path is configured for (Camcorder, voice recognition...). +// See audio.h, audio_source_t for values. +//-------------------------------------------------------------------------------------------------- +// command format: +// size: sizeof(uint32_t) +// data: uint32_t +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: 0 +// data: N/A +//================================================================================================== +// command: EFFECT_CMD_OFFLOAD +//-------------------------------------------------------------------------------------------------- +// description: +// 1.indicate if the playback thread the effect is attached to is offloaded or not +// 2.update the io handle of the playback thread the effect is attached to +//-------------------------------------------------------------------------------------------------- +// command format: +// size: sizeof(effect_offload_param_t) +// data: effect_offload_param_t +//-------------------------------------------------------------------------------------------------- +// reply format: +// size: sizeof(uint32_t) +// data: uint32_t +//-------------------------------------------------------------------------------------------------- +// command: EFFECT_CMD_FIRST_PROPRIETARY +//-------------------------------------------------------------------------------------------------- +// description: +// All proprietary effect commands must use command codes above this value. The size and format of +// command and response fields is free in this case +//================================================================================================== + + +// Audio buffer descriptor used by process(), bufferProvider() functions and buffer_config_t +// structure. Multi-channel audio is always interleaved. The channel order is from LSB to MSB with +// regard to the channel mask definition in audio.h, audio_channel_mask_t e.g : +// Stereo: left, right +// 5 point 1: front left, front right, front center, low frequency, back left, back right +// The buffer size is expressed in frame count, a frame being composed of samples for all +// channels at a given time. Frame size for unspecified format (AUDIO_FORMAT_OTHER) is 8 bit by +// definition +struct audio_buffer_s { + size_t frameCount; // number of frames in buffer + union { + void* raw; // raw pointer to start of buffer + int32_t* s32; // pointer to signed 32 bit data at start of buffer + int16_t* s16; // pointer to signed 16 bit data at start of buffer + uint8_t* u8; // pointer to unsigned 8 bit data at start of buffer + }; +}; + +// The buffer_provider_s structure contains functions that can be used +// by the effect engine process() function to query and release input +// or output audio buffer. +// The getBuffer() function is called to retrieve a buffer where data +// should read from or written to by process() function. +// The releaseBuffer() function MUST be called when the buffer retrieved +// with getBuffer() is not needed anymore. +// The process function should use the buffer provider mechanism to retrieve +// input or output buffer if the inBuffer or outBuffer passed as argument is NULL +// and the buffer configuration (buffer_config_t) given by the EFFECT_CMD_SET_CONFIG +// command did not specify an audio buffer. + +typedef int32_t (* buffer_function_t)(void *cookie, audio_buffer_t *buffer); + +typedef struct buffer_provider_s { + buffer_function_t getBuffer; // retrieve next buffer + buffer_function_t releaseBuffer; // release used buffer + void *cookie; // for use by client of buffer provider functions +} buffer_provider_t; + + +// The buffer_config_s structure specifies the input or output audio format +// to be used by the effect engine. It is part of the effect_config_t +// structure that defines both input and output buffer configurations and is +// passed by the EFFECT_CMD_SET_CONFIG or EFFECT_CMD_SET_CONFIG_REVERSE command. +typedef struct buffer_config_s { + audio_buffer_t buffer; // buffer for use by process() function if not passed explicitly + uint32_t samplingRate; // sampling rate + uint32_t channels; // channel mask (see audio_channel_mask_t in audio.h) + buffer_provider_t bufferProvider; // buffer provider + uint8_t format; // Audio format (see audio_format_t in audio.h) + uint8_t accessMode; // read/write or accumulate in buffer (effect_buffer_access_e) + uint16_t mask; // indicates which of the above fields is valid +} buffer_config_t; + +// Values for "accessMode" field of buffer_config_t: +// overwrite, read only, accumulate (read/modify/write) +enum effect_buffer_access_e { + EFFECT_BUFFER_ACCESS_WRITE, + EFFECT_BUFFER_ACCESS_READ, + EFFECT_BUFFER_ACCESS_ACCUMULATE + +}; + +// feature identifiers for EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS command +enum effect_feature_e { + EFFECT_FEATURE_AUX_CHANNELS, // supports auxiliary channels (e.g. dual mic noise suppressor) + EFFECT_FEATURE_CNT +}; + +// EFFECT_FEATURE_AUX_CHANNELS feature configuration descriptor. Describe a combination +// of main and auxiliary channels supported +typedef struct channel_config_s { + audio_channel_mask_t main_channels; // channel mask for main channels + audio_channel_mask_t aux_channels; // channel mask for auxiliary channels +} channel_config_t; + + +// Values for bit field "mask" in buffer_config_t. If a bit is set, the corresponding field +// in buffer_config_t must be taken into account when executing the EFFECT_CMD_SET_CONFIG command +#define EFFECT_CONFIG_BUFFER 0x0001 // buffer field must be taken into account +#define EFFECT_CONFIG_SMP_RATE 0x0002 // samplingRate field must be taken into account +#define EFFECT_CONFIG_CHANNELS 0x0004 // channels field must be taken into account +#define EFFECT_CONFIG_FORMAT 0x0008 // format field must be taken into account +#define EFFECT_CONFIG_ACC_MODE 0x0010 // accessMode field must be taken into account +#define EFFECT_CONFIG_PROVIDER 0x0020 // bufferProvider field must be taken into account +#define EFFECT_CONFIG_ALL (EFFECT_CONFIG_BUFFER | EFFECT_CONFIG_SMP_RATE | \ + EFFECT_CONFIG_CHANNELS | EFFECT_CONFIG_FORMAT | \ + EFFECT_CONFIG_ACC_MODE | EFFECT_CONFIG_PROVIDER) + + +// effect_config_s structure describes the format of the pCmdData argument of EFFECT_CMD_SET_CONFIG +// command to configure audio parameters and buffers for effect engine input and output. +typedef struct effect_config_s { + buffer_config_t inputCfg; + buffer_config_t outputCfg; +} effect_config_t; + + +// effect_param_s structure describes the format of the pCmdData argument of EFFECT_CMD_SET_PARAM +// command and pCmdData and pReplyData of EFFECT_CMD_GET_PARAM command. +// psize and vsize represent the actual size of parameter and value. +// +// NOTE: the start of value field inside the data field is always on a 32 bit boundary: +// +// +-----------+ +// | status | sizeof(int) +// +-----------+ +// | psize | sizeof(int) +// +-----------+ +// | vsize | sizeof(int) +// +-----------+ +// | | | | +// ~ parameter ~ > psize | +// | | | > ((psize - 1)/sizeof(int) + 1) * sizeof(int) +// +-----------+ | +// | padding | | +// +-----------+ +// | | | +// ~ value ~ > vsize +// | | | +// +-----------+ + +typedef struct effect_param_s { + int32_t status; // Transaction status (unused for command, used for reply) + uint32_t psize; // Parameter size + uint32_t vsize; // Value size + char data[]; // Start of Parameter + Value data +} effect_param_t; + +// structure used by EFFECT_CMD_OFFLOAD command +typedef struct effect_offload_param_s { + bool isOffload; // true if the playback thread the effect is attached to is offloaded + int ioHandle; // io handle of the playback thread the effect is attached to +} effect_offload_param_t; + + +///////////////////////////////////////////////// +// Effect library interface +///////////////////////////////////////////////// + +// Effect library interface version 3.0 +// Note that EffectsFactory.c only checks the major version component, so changes to the minor +// number can only be used for fully backwards compatible changes +#define EFFECT_LIBRARY_API_VERSION EFFECT_MAKE_API_VERSION(3,0) + +#define AUDIO_EFFECT_LIBRARY_TAG ((('A') << 24) | (('E') << 16) | (('L') << 8) | ('T')) + +// Every effect library must have a data structure named AUDIO_EFFECT_LIBRARY_INFO_SYM +// and the fields of this data structure must begin with audio_effect_library_t + +typedef struct audio_effect_library_s { + // tag must be initialized to AUDIO_EFFECT_LIBRARY_TAG + uint32_t tag; + // Version of the effect library API : 0xMMMMmmmm MMMM: Major, mmmm: minor + uint32_t version; + // Name of this library + const char *name; + // Author/owner/implementor of the library + const char *implementor; + + //////////////////////////////////////////////////////////////////////////////// + // + // Function: create_effect + // + // Description: Creates an effect engine of the specified implementation uuid and + // returns an effect control interface on this engine. The function will allocate the + // resources for an instance of the requested effect engine and return + // a handle on the effect control interface. + // + // Input: + // uuid: pointer to the effect uuid. + // sessionId: audio session to which this effect instance will be attached. + // All effects created with the same session ID are connected in series and process + // the same signal stream. Knowing that two effects are part of the same effect + // chain can help the library implement some kind of optimizations. + // ioId: identifies the output or input stream this effect is directed to in + // audio HAL. + // For future use especially with tunneled HW accelerated effects + // + // Input/Output: + // pHandle: address where to return the effect interface handle. + // + // Output: + // returned value: 0 successful operation. + // -ENODEV library failed to initialize + // -EINVAL invalid pEffectUuid or pHandle + // -ENOENT no effect with this uuid found + // *pHandle: updated with the effect interface handle. + // + //////////////////////////////////////////////////////////////////////////////// + int32_t (*create_effect)(const effect_uuid_t *uuid, + int32_t sessionId, + int32_t ioId, + effect_handle_t *pHandle); + + //////////////////////////////////////////////////////////////////////////////// + // + // Function: release_effect + // + // Description: Releases the effect engine whose handle is given as argument. + // All resources allocated to this particular instance of the effect are + // released. + // + // Input: + // handle: handle on the effect interface to be released. + // + // Output: + // returned value: 0 successful operation. + // -ENODEV library failed to initialize + // -EINVAL invalid interface handle + // + //////////////////////////////////////////////////////////////////////////////// + int32_t (*release_effect)(effect_handle_t handle); + + //////////////////////////////////////////////////////////////////////////////// + // + // Function: get_descriptor + // + // Description: Returns the descriptor of the effect engine which implementation UUID is + // given as argument. + // + // Input/Output: + // uuid: pointer to the effect uuid. + // pDescriptor: address where to return the effect descriptor. + // + // Output: + // returned value: 0 successful operation. + // -ENODEV library failed to initialize + // -EINVAL invalid pDescriptor or uuid + // *pDescriptor: updated with the effect descriptor. + // + //////////////////////////////////////////////////////////////////////////////// + int32_t (*get_descriptor)(const effect_uuid_t *uuid, + effect_descriptor_t *pDescriptor); +} audio_effect_library_t; + +// Name of the hal_module_info +#define AUDIO_EFFECT_LIBRARY_INFO_SYM AELI + +// Name of the hal_module_info as a string +#define AUDIO_EFFECT_LIBRARY_INFO_SYM_AS_STR "AELI" + +__END_DECLS + +#endif // ANDROID_AUDIO_EFFECT_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/audio_policy.h b/phonelibs/android_hardware_libhardware/include/hardware/audio_policy.h new file mode 100644 index 0000000000..99cb0449fb --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/audio_policy.h @@ -0,0 +1,457 @@ +/* + * 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_AUDIO_POLICY_INTERFACE_H +#define ANDROID_AUDIO_POLICY_INTERFACE_H + +#include +#include +#include + +#include + +#include +#include + +__BEGIN_DECLS + +/** + * The id of this module + */ +#define AUDIO_POLICY_HARDWARE_MODULE_ID "audio_policy" + +/** + * Name of the audio devices to open + */ +#define AUDIO_POLICY_INTERFACE "policy" + +/* ---------------------------------------------------------------------------- */ + +/* + * The audio_policy and audio_policy_service_ops structs define the + * communication interfaces between the platform specific audio policy manager + * and Android generic audio policy manager. + * The platform specific audio policy manager must implement methods of the + * audio_policy struct. + * This implementation makes use of the audio_policy_service_ops to control + * the activity and configuration of audio input and output streams. + * + * The platform specific audio policy manager is in charge of the audio + * routing and volume control policies for a given platform. + * The main roles of this module are: + * - keep track of current system state (removable device connections, phone + * state, user requests...). + * System state changes and user actions are notified to audio policy + * manager with methods of the audio_policy. + * + * - process get_output() queries received when AudioTrack objects are + * created: Those queries return a handler on an output that has been + * selected, configured and opened by the audio policy manager and that + * must be used by the AudioTrack when registering to the AudioFlinger + * with the createTrack() method. + * When the AudioTrack object is released, a release_output() query + * is received and the audio policy manager can decide to close or + * reconfigure the output depending on other streams using this output and + * current system state. + * + * - similarly process get_input() and release_input() queries received from + * AudioRecord objects and configure audio inputs. + * - process volume control requests: the stream volume is converted from + * an index value (received from UI) to a float value applicable to each + * output as a function of platform specific settings and current output + * route (destination device). It also make sure that streams are not + * muted if not allowed (e.g. camera shutter sound in some countries). + */ + +/* XXX: this should be defined OUTSIDE of frameworks/base */ +struct effect_descriptor_s; + +struct audio_policy { + /* + * configuration functions + */ + + /* indicate a change in device connection status */ + int (*set_device_connection_state)(struct audio_policy *pol, + audio_devices_t device, + audio_policy_dev_state_t state, + const char *device_address); + + /* retrieve a device connection status */ + audio_policy_dev_state_t (*get_device_connection_state)( + const struct audio_policy *pol, + audio_devices_t device, + const char *device_address); + + /* indicate a change in phone state. Valid phones states are defined + * by audio_mode_t */ + void (*set_phone_state)(struct audio_policy *pol, audio_mode_t state); + + /* deprecated, never called (was "indicate a change in ringer mode") */ + void (*set_ringer_mode)(struct audio_policy *pol, uint32_t mode, + uint32_t mask); + + /* force using a specific device category for the specified usage */ + void (*set_force_use)(struct audio_policy *pol, + audio_policy_force_use_t usage, + audio_policy_forced_cfg_t config); + + /* retrieve current device category forced for a given usage */ + audio_policy_forced_cfg_t (*get_force_use)(const struct audio_policy *pol, + audio_policy_force_use_t usage); + + /* if can_mute is true, then audio streams that are marked ENFORCED_AUDIBLE + * can still be muted. */ + void (*set_can_mute_enforced_audible)(struct audio_policy *pol, + bool can_mute); + + /* check proper initialization */ + int (*init_check)(const struct audio_policy *pol); + + /* + * Audio routing query functions + */ + + /* request an output appropriate for playback of the supplied stream type and + * parameters */ + audio_io_handle_t (*get_output)(struct audio_policy *pol, + audio_stream_type_t stream, + uint32_t samplingRate, + audio_format_t format, + audio_channel_mask_t channelMask, + audio_output_flags_t flags, + const audio_offload_info_t *offloadInfo); + + /* indicates to the audio policy manager that the output starts being used + * by corresponding stream. */ + int (*start_output)(struct audio_policy *pol, + audio_io_handle_t output, + audio_stream_type_t stream, + int session); + + /* indicates to the audio policy manager that the output stops being used + * by corresponding stream. */ + int (*stop_output)(struct audio_policy *pol, + audio_io_handle_t output, + audio_stream_type_t stream, + int session); + + /* releases the output. */ + void (*release_output)(struct audio_policy *pol, audio_io_handle_t output); + + /* request an input appropriate for record from the supplied device with + * supplied parameters. */ + audio_io_handle_t (*get_input)(struct audio_policy *pol, audio_source_t inputSource, + uint32_t samplingRate, + audio_format_t format, + audio_channel_mask_t channelMask, + audio_in_acoustics_t acoustics); + + /* indicates to the audio policy manager that the input starts being used */ + int (*start_input)(struct audio_policy *pol, audio_io_handle_t input); + + /* indicates to the audio policy manager that the input stops being used. */ + int (*stop_input)(struct audio_policy *pol, audio_io_handle_t input); + + /* releases the input. */ + void (*release_input)(struct audio_policy *pol, audio_io_handle_t input); + + /* + * volume control functions + */ + + /* initialises stream volume conversion parameters by specifying volume + * index range. The index range for each stream is defined by AudioService. */ + void (*init_stream_volume)(struct audio_policy *pol, + audio_stream_type_t stream, + int index_min, + int index_max); + + /* sets the new stream volume at a level corresponding to the supplied + * index. The index is within the range specified by init_stream_volume() */ + int (*set_stream_volume_index)(struct audio_policy *pol, + audio_stream_type_t stream, + int index); + + /* retrieve current volume index for the specified stream */ + int (*get_stream_volume_index)(const struct audio_policy *pol, + audio_stream_type_t stream, + int *index); + + /* sets the new stream volume at a level corresponding to the supplied + * index for the specified device. + * The index is within the range specified by init_stream_volume() */ + int (*set_stream_volume_index_for_device)(struct audio_policy *pol, + audio_stream_type_t stream, + int index, + audio_devices_t device); + + /* retrieve current volume index for the specified stream for the specified device */ + int (*get_stream_volume_index_for_device)(const struct audio_policy *pol, + audio_stream_type_t stream, + int *index, + audio_devices_t device); + + /* return the strategy corresponding to a given stream type */ + uint32_t (*get_strategy_for_stream)(const struct audio_policy *pol, + audio_stream_type_t stream); + + /* return the enabled output devices for the given stream type */ + audio_devices_t (*get_devices_for_stream)(const struct audio_policy *pol, + audio_stream_type_t stream); + + /* Audio effect management */ + audio_io_handle_t (*get_output_for_effect)(struct audio_policy *pol, + const struct effect_descriptor_s *desc); + + int (*register_effect)(struct audio_policy *pol, + const struct effect_descriptor_s *desc, + audio_io_handle_t output, + uint32_t strategy, + int session, + int id); + + int (*unregister_effect)(struct audio_policy *pol, int id); + + int (*set_effect_enabled)(struct audio_policy *pol, int id, bool enabled); + + bool (*is_stream_active)(const struct audio_policy *pol, + audio_stream_type_t stream, + uint32_t in_past_ms); + + bool (*is_stream_active_remotely)(const struct audio_policy *pol, + audio_stream_type_t stream, + uint32_t in_past_ms); + + bool (*is_source_active)(const struct audio_policy *pol, + audio_source_t source); + + /* dump state */ + int (*dump)(const struct audio_policy *pol, int fd); + + /* check if offload is possible for given sample rate, bitrate, duration, ... */ + bool (*is_offload_supported)(const struct audio_policy *pol, + const audio_offload_info_t *info); +}; + + +struct audio_policy_service_ops { + /* + * Audio output Control functions + */ + + /* Opens an audio output with the requested parameters. + * + * The parameter values can indicate to use the default values in case the + * audio policy manager has no specific requirements for the output being + * opened. + * + * When the function returns, the parameter values reflect the actual + * values used by the audio hardware output stream. + * + * The audio policy manager can check if the proposed parameters are + * suitable or not and act accordingly. + */ + audio_io_handle_t (*open_output)(void *service, + audio_devices_t *pDevices, + uint32_t *pSamplingRate, + audio_format_t *pFormat, + audio_channel_mask_t *pChannelMask, + uint32_t *pLatencyMs, + audio_output_flags_t flags); + + /* creates a special output that is duplicated to the two outputs passed as + * arguments. The duplication is performed by + * a special mixer thread in the AudioFlinger. + */ + audio_io_handle_t (*open_duplicate_output)(void *service, + audio_io_handle_t output1, + audio_io_handle_t output2); + + /* closes the output stream */ + int (*close_output)(void *service, audio_io_handle_t output); + + /* suspends the output. + * + * When an output is suspended, the corresponding audio hardware output + * stream is placed in standby and the AudioTracks attached to the mixer + * thread are still processed but the output mix is discarded. + */ + int (*suspend_output)(void *service, audio_io_handle_t output); + + /* restores a suspended output. */ + int (*restore_output)(void *service, audio_io_handle_t output); + + /* */ + /* Audio input Control functions */ + /* */ + + /* opens an audio input + * deprecated - new implementations should use open_input_on_module, + * and the acoustics parameter is ignored + */ + audio_io_handle_t (*open_input)(void *service, + audio_devices_t *pDevices, + uint32_t *pSamplingRate, + audio_format_t *pFormat, + audio_channel_mask_t *pChannelMask, + audio_in_acoustics_t acoustics); + + /* closes an audio input */ + int (*close_input)(void *service, audio_io_handle_t input); + + /* */ + /* misc control functions */ + /* */ + + /* set a stream volume for a particular output. + * + * For the same user setting, a given stream type can have different + * volumes for each output (destination device) it is attached to. + */ + int (*set_stream_volume)(void *service, + audio_stream_type_t stream, + float volume, + audio_io_handle_t output, + int delay_ms); + + /* invalidate a stream type, causing a reroute to an unspecified new output */ + int (*invalidate_stream)(void *service, + audio_stream_type_t stream); + + /* function enabling to send proprietary informations directly from audio + * policy manager to audio hardware interface. */ + void (*set_parameters)(void *service, + audio_io_handle_t io_handle, + const char *kv_pairs, + int delay_ms); + + /* function enabling to receive proprietary informations directly from + * audio hardware interface to audio policy manager. + * + * Returns a pointer to a heap allocated string. The caller is responsible + * for freeing the memory for it using free(). + */ + + char * (*get_parameters)(void *service, audio_io_handle_t io_handle, + const char *keys); + + /* request the playback of a tone on the specified stream. + * used for instance to replace notification sounds when playing over a + * telephony device during a phone call. + */ + int (*start_tone)(void *service, + audio_policy_tone_t tone, + audio_stream_type_t stream); + + int (*stop_tone)(void *service); + + /* set down link audio volume. */ + int (*set_voice_volume)(void *service, + float volume, + int delay_ms); + + /* move effect to the specified output */ + int (*move_effects)(void *service, + int session, + audio_io_handle_t src_output, + audio_io_handle_t dst_output); + + /* loads an audio hw module. + * + * The module name passed is the base name of the HW module library, e.g "primary" or "a2dp". + * The function returns a handle on the module that will be used to specify a particular + * module when calling open_output_on_module() or open_input_on_module() + */ + audio_module_handle_t (*load_hw_module)(void *service, + const char *name); + + /* Opens an audio output on a particular HW module. + * + * Same as open_output() but specifying a specific HW module on which the output must be opened. + */ + audio_io_handle_t (*open_output_on_module)(void *service, + audio_module_handle_t module, + audio_devices_t *pDevices, + uint32_t *pSamplingRate, + audio_format_t *pFormat, + audio_channel_mask_t *pChannelMask, + uint32_t *pLatencyMs, + audio_output_flags_t flags, + const audio_offload_info_t *offloadInfo); + + /* Opens an audio input on a particular HW module. + * + * Same as open_input() but specifying a specific HW module on which the input must be opened. + * Also removed deprecated acoustics parameter + */ + audio_io_handle_t (*open_input_on_module)(void *service, + audio_module_handle_t module, + audio_devices_t *pDevices, + uint32_t *pSamplingRate, + audio_format_t *pFormat, + audio_channel_mask_t *pChannelMask); + +}; + +/**********************************************************************/ + +/** + * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM + * and the fields of this data structure must begin with hw_module_t + * followed by module specific information. + */ +typedef struct audio_policy_module { + struct hw_module_t common; +} audio_policy_module_t; + +struct audio_policy_device { + /** + * Common methods of the audio policy device. This *must* be the first member of + * audio_policy_device as users of this structure will cast a hw_device_t to + * audio_policy_device pointer in contexts where it's known the hw_device_t references an + * audio_policy_device. + */ + struct hw_device_t common; + + int (*create_audio_policy)(const struct audio_policy_device *device, + struct audio_policy_service_ops *aps_ops, + void *service, + struct audio_policy **ap); + + int (*destroy_audio_policy)(const struct audio_policy_device *device, + struct audio_policy *ap); +}; + +/** convenience API for opening and closing a supported device */ + +static inline int audio_policy_dev_open(const hw_module_t* module, + struct audio_policy_device** device) +{ + return module->methods->open(module, AUDIO_POLICY_INTERFACE, + (hw_device_t**)device); +} + +static inline int audio_policy_dev_close(struct audio_policy_device* device) +{ + return device->common.close(&device->common); +} + + +__END_DECLS + +#endif // ANDROID_AUDIO_POLICY_INTERFACE_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/bluetooth.h b/phonelibs/android_hardware_libhardware/include/hardware/bluetooth.h new file mode 100644 index 0000000000..5e8b468d64 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/bluetooth.h @@ -0,0 +1,595 @@ +/* + * 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_INCLUDE_BLUETOOTH_H +#define ANDROID_INCLUDE_BLUETOOTH_H + +#include +#include +#include +#include + +#include + +__BEGIN_DECLS + +/** + * The Bluetooth Hardware Module ID + */ + +#define BT_HARDWARE_MODULE_ID "bluetooth" +#define BT_STACK_MODULE_ID "bluetooth" +#define BT_STACK_TEST_MODULE_ID "bluetooth_test" + + +/* Bluetooth profile interface IDs */ + +#define BT_PROFILE_HANDSFREE_ID "handsfree" +#define BT_PROFILE_HANDSFREE_CLIENT_ID "handsfree_client" +#define BT_PROFILE_ADVANCED_AUDIO_ID "a2dp" +#define BT_PROFILE_ADVANCED_AUDIO_SINK_ID "a2dp_sink" +#define BT_PROFILE_HEALTH_ID "health" +#define BT_PROFILE_SOCKETS_ID "socket" +#define BT_PROFILE_HIDHOST_ID "hidhost" +#define BT_PROFILE_HIDDEV_ID "hiddev" +#define BT_PROFILE_PAN_ID "pan" +#define BT_PROFILE_MAP_CLIENT_ID "map_client" +#define BT_PROFILE_SDP_CLIENT_ID "sdp" +#define BT_PROFILE_GATT_ID "gatt" +#define BT_PROFILE_AV_RC_ID "avrcp" +#define WIPOWER_PROFILE_ID "wipower" +#define BT_PROFILE_AV_RC_CTRL_ID "avrcp_ctrl" + +/** Bluetooth Address */ +typedef struct { + uint8_t address[6]; +} __attribute__((packed))bt_bdaddr_t; + +/** Bluetooth Device Name */ +typedef struct { + uint8_t name[249]; +} __attribute__((packed))bt_bdname_t; + +/** Bluetooth Adapter Visibility Modes*/ +typedef enum { + BT_SCAN_MODE_NONE, + BT_SCAN_MODE_CONNECTABLE, + BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE +} bt_scan_mode_t; + +/** Bluetooth Adapter State */ +typedef enum { + BT_STATE_OFF, + BT_STATE_ON +} bt_state_t; + +/** Bluetooth Error Status */ +/** We need to build on this */ + +typedef enum { + BT_STATUS_SUCCESS, + BT_STATUS_FAIL, + BT_STATUS_NOT_READY, + BT_STATUS_NOMEM, + BT_STATUS_BUSY, + BT_STATUS_DONE, /* request already completed */ + BT_STATUS_UNSUPPORTED, + BT_STATUS_PARM_INVALID, + BT_STATUS_UNHANDLED, + BT_STATUS_AUTH_FAILURE, + BT_STATUS_RMT_DEV_DOWN, + BT_STATUS_AUTH_REJECTED + +} bt_status_t; + +/** Bluetooth PinKey Code */ +typedef struct { + uint8_t pin[16]; +} __attribute__((packed))bt_pin_code_t; + +typedef struct { + uint8_t status; + uint8_t ctrl_state; /* stack reported state */ + uint64_t tx_time; /* in ms */ + uint64_t rx_time; /* in ms */ + uint64_t idle_time; /* in ms */ + uint64_t energy_used; /* a product of mA, V and ms */ +} __attribute__((packed))bt_activity_energy_info; + +/** Bluetooth Adapter Discovery state */ +typedef enum { + BT_DISCOVERY_STOPPED, + BT_DISCOVERY_STARTED +} bt_discovery_state_t; + +/** Bluetooth ACL connection state */ +typedef enum { + BT_ACL_STATE_CONNECTED, + BT_ACL_STATE_DISCONNECTED +} bt_acl_state_t; + +/** Bluetooth 128-bit UUID */ +typedef struct { + uint8_t uu[16]; +} bt_uuid_t; + +/** Bluetooth SDP service record */ +typedef struct +{ + bt_uuid_t uuid; + uint16_t channel; + char name[256]; // what's the maximum length +} bt_service_record_t; + + +/** Bluetooth Remote Version info */ +typedef struct +{ + int version; + int sub_ver; + int manufacturer; +} bt_remote_version_t; + +typedef struct +{ + uint16_t version_supported; + uint8_t local_privacy_enabled; + uint8_t max_adv_instance; + uint8_t rpa_offload_supported; + uint8_t max_irk_list_size; + uint8_t max_adv_filter_supported; + uint8_t activity_energy_info_supported; + uint16_t scan_result_storage_size; + uint16_t total_trackable_advertisers; + bool extended_scan_support; + bool debug_logging_supported; +}bt_local_le_features_t; + +/* Bluetooth Adapter and Remote Device property types */ +typedef enum { + /* Properties common to both adapter and remote device */ + /** + * Description - Bluetooth Device Name + * Access mode - Adapter name can be GET/SET. Remote device can be GET + * Data type - bt_bdname_t + */ + BT_PROPERTY_BDNAME = 0x1, + /** + * Description - Bluetooth Device Address + * Access mode - Only GET. + * Data type - bt_bdaddr_t + */ + BT_PROPERTY_BDADDR, + /** + * Description - Bluetooth Service 128-bit UUIDs + * Access mode - Only GET. + * Data type - Array of bt_uuid_t (Array size inferred from property length). + */ + BT_PROPERTY_UUIDS, + /** + * Description - Bluetooth Class of Device as found in Assigned Numbers + * Access mode - Only GET. + * Data type - uint32_t. + */ + BT_PROPERTY_CLASS_OF_DEVICE, + /** + * Description - Device Type - BREDR, BLE or DUAL Mode + * Access mode - Only GET. + * Data type - bt_device_type_t + */ + BT_PROPERTY_TYPE_OF_DEVICE, + /** + * Description - Bluetooth Service Record + * Access mode - Only GET. + * Data type - bt_service_record_t + */ + BT_PROPERTY_SERVICE_RECORD, + + /* Properties unique to adapter */ + /** + * Description - Bluetooth Adapter scan mode + * Access mode - GET and SET + * Data type - bt_scan_mode_t. + */ + BT_PROPERTY_ADAPTER_SCAN_MODE, + /** + * Description - List of bonded devices + * Access mode - Only GET. + * Data type - Array of bt_bdaddr_t of the bonded remote devices + * (Array size inferred from property length). + */ + BT_PROPERTY_ADAPTER_BONDED_DEVICES, + /** + * Description - Bluetooth Adapter Discovery timeout (in seconds) + * Access mode - GET and SET + * Data type - uint32_t + */ + BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT, + + /* Properties unique to remote device */ + /** + * Description - User defined friendly name of the remote device + * Access mode - GET and SET + * Data type - bt_bdname_t. + */ + BT_PROPERTY_REMOTE_FRIENDLY_NAME, + /** + * Description - RSSI value of the inquired remote device + * Access mode - Only GET. + * Data type - int32_t. + */ + BT_PROPERTY_REMOTE_RSSI, + /** + * Description - Remote version info + * Access mode - SET/GET. + * Data type - bt_remote_version_t. + */ + + BT_PROPERTY_REMOTE_VERSION_INFO, + + /** + * Description - Local LE features + * Access mode - GET. + * Data type - bt_local_le_features_t. + */ + BT_PROPERTY_LOCAL_LE_FEATURES, + + BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP = 0xFF, +} bt_property_type_t; + +/** Bluetooth Adapter Property data structure */ +typedef struct +{ + bt_property_type_t type; + int len; + void *val; +} bt_property_t; + + +/** Bluetooth Device Type */ +typedef enum { + BT_DEVICE_DEVTYPE_BREDR = 0x1, + BT_DEVICE_DEVTYPE_BLE, + BT_DEVICE_DEVTYPE_DUAL +} bt_device_type_t; +/** Bluetooth Bond state */ +typedef enum { + BT_BOND_STATE_NONE, + BT_BOND_STATE_BONDING, + BT_BOND_STATE_BONDED +} bt_bond_state_t; + +/** Bluetooth SSP Bonding Variant */ +typedef enum { + BT_SSP_VARIANT_PASSKEY_CONFIRMATION, + BT_SSP_VARIANT_PASSKEY_ENTRY, + BT_SSP_VARIANT_CONSENT, + BT_SSP_VARIANT_PASSKEY_NOTIFICATION +} bt_ssp_variant_t; + +#define BT_MAX_NUM_UUIDS 32 + +/** Bluetooth Interface callbacks */ + +/** Bluetooth Enable/Disable Callback. */ +typedef void (*adapter_state_changed_callback)(bt_state_t state); + +/** GET/SET Adapter Properties callback */ +/* TODO: For the GET/SET property APIs/callbacks, we may need a session + * identifier to associate the call with the callback. This would be needed + * whenever more than one simultaneous instance of the same adapter_type + * is get/set. + * + * If this is going to be handled in the Java framework, then we do not need + * to manage sessions here. + */ +typedef void (*adapter_properties_callback)(bt_status_t status, + int num_properties, + bt_property_t *properties); + +/** GET/SET Remote Device Properties callback */ +/** TODO: For remote device properties, do not see a need to get/set + * multiple properties - num_properties shall be 1 + */ +typedef void (*remote_device_properties_callback)(bt_status_t status, + bt_bdaddr_t *bd_addr, + int num_properties, + bt_property_t *properties); + +/** New device discovered callback */ +/** If EIR data is not present, then BD_NAME and RSSI shall be NULL and -1 + * respectively */ +typedef void (*device_found_callback)(int num_properties, + bt_property_t *properties); + +/** Discovery state changed callback */ +typedef void (*discovery_state_changed_callback)(bt_discovery_state_t state); + +/** Bluetooth Legacy PinKey Request callback */ +typedef void (*pin_request_callback)(bt_bdaddr_t *remote_bd_addr, + bt_bdname_t *bd_name, uint32_t cod, bool min_16_digit); + +/** Bluetooth SSP Request callback - Just Works & Numeric Comparison*/ +/** pass_key - Shall be 0 for BT_SSP_PAIRING_VARIANT_CONSENT & + * BT_SSP_PAIRING_PASSKEY_ENTRY */ +/* TODO: Passkey request callback shall not be needed for devices with display + * capability. We still need support this in the stack for completeness */ +typedef void (*ssp_request_callback)(bt_bdaddr_t *remote_bd_addr, + bt_bdname_t *bd_name, + uint32_t cod, + bt_ssp_variant_t pairing_variant, + uint32_t pass_key); + +/** Bluetooth Bond state changed callback */ +/* Invoked in response to create_bond, cancel_bond or remove_bond */ +typedef void (*bond_state_changed_callback)(bt_status_t status, + bt_bdaddr_t *remote_bd_addr, + bt_bond_state_t state); + +/** Bluetooth ACL connection state changed callback */ +typedef void (*acl_state_changed_callback)(bt_status_t status, bt_bdaddr_t *remote_bd_addr, + bt_acl_state_t state); + +typedef enum { + ASSOCIATE_JVM, + DISASSOCIATE_JVM +} bt_cb_thread_evt; + +/** Thread Associate/Disassociate JVM Callback */ +/* Callback that is invoked by the callback thread to allow upper layer to attach/detach to/from + * the JVM */ +typedef void (*callback_thread_event)(bt_cb_thread_evt evt); + +/** Bluetooth Test Mode Callback */ +/* Receive any HCI event from controller. Must be in DUT Mode for this callback to be received */ +typedef void (*dut_mode_recv_callback)(uint16_t opcode, uint8_t *buf, uint8_t len); + +/** Bluetooth HCI event Callback */ +/* Receive any HCI event from controller for raw commands */ +typedef void (*hci_event_recv_callback)(uint8_t event_code, uint8_t *buf, uint8_t len); + +/* LE Test mode callbacks +* This callback shall be invoked whenever the le_tx_test, le_rx_test or le_test_end is invoked +* The num_packets is valid only for le_test_end command */ +typedef void (*le_test_mode_callback)(bt_status_t status, uint16_t num_packets); + +/** Callback invoked when energy details are obtained */ +/* Ctrl_state-Current controller state-Active-1,scan-2,or idle-3 state as defined by HCI spec. + * If the ctrl_state value is 0, it means the API call failed + * Time values-In milliseconds as returned by the controller + * Energy used-Value as returned by the controller + * Status-Provides the status of the read_energy_info API call */ +typedef void (*energy_info_callback)(bt_activity_energy_info *energy_info); + +/** TODO: Add callbacks for Link Up/Down and other generic + * notifications/callbacks */ + +/** Bluetooth DM callback structure. */ +typedef struct { + /** set to sizeof(bt_callbacks_t) */ + size_t size; + adapter_state_changed_callback adapter_state_changed_cb; + adapter_properties_callback adapter_properties_cb; + remote_device_properties_callback remote_device_properties_cb; + device_found_callback device_found_cb; + discovery_state_changed_callback discovery_state_changed_cb; + pin_request_callback pin_request_cb; + ssp_request_callback ssp_request_cb; + bond_state_changed_callback bond_state_changed_cb; + acl_state_changed_callback acl_state_changed_cb; + callback_thread_event thread_evt_cb; + dut_mode_recv_callback dut_mode_recv_cb; + le_test_mode_callback le_test_mode_cb; + energy_info_callback energy_info_cb; + hci_event_recv_callback hci_event_recv_cb; +} bt_callbacks_t; + +typedef void (*alarm_cb)(void *data); +typedef bool (*set_wake_alarm_callout)(uint64_t delay_millis, bool should_wake, alarm_cb cb, void *data); +typedef int (*acquire_wake_lock_callout)(const char *lock_name); +typedef int (*release_wake_lock_callout)(const char *lock_name); + +/** The set of functions required by bluedroid to set wake alarms and + * grab wake locks. This struct is passed into the stack through the + * |set_os_callouts| function on |bt_interface_t|. + */ +typedef struct { + /* set to sizeof(bt_os_callouts_t) */ + size_t size; + + set_wake_alarm_callout set_wake_alarm; + acquire_wake_lock_callout acquire_wake_lock; + release_wake_lock_callout release_wake_lock; +} bt_os_callouts_t; + +/** NOTE: By default, no profiles are initialized at the time of init/enable. + * Whenever the application invokes the 'init' API of a profile, then one of + * the following shall occur: + * + * 1.) If Bluetooth is not enabled, then the Bluetooth core shall mark the + * profile as enabled. Subsequently, when the application invokes the + * Bluetooth 'enable', as part of the enable sequence the profile that were + * marked shall be enabled by calling appropriate stack APIs. The + * 'adapter_properties_cb' shall return the list of UUIDs of the + * enabled profiles. + * + * 2.) If Bluetooth is enabled, then the Bluetooth core shall invoke the stack + * profile API to initialize the profile and trigger a + * 'adapter_properties_cb' with the current list of UUIDs including the + * newly added profile's UUID. + * + * The reverse shall occur whenever the profile 'cleanup' APIs are invoked + */ + +/** Represents the standard Bluetooth DM interface. */ +typedef struct { + /** set to sizeof(bt_interface_t) */ + size_t size; + /** + * Opens the interface and provides the callback routines + * to the implemenation of this interface. + */ + int (*init)(bt_callbacks_t* callbacks ); + + /** Enable Bluetooth. */ + int (*enable)(bool guest_mode); + + /** Disable Bluetooth. */ + int (*disable)(void); + + /** Closes the interface. */ + void (*cleanup)(void); + + /** SSR cleanup. */ + void (*ssrcleanup)(void); + + /** Get all Bluetooth Adapter properties at init */ + int (*get_adapter_properties)(void); + + /** Get Bluetooth Adapter property of 'type' */ + int (*get_adapter_property)(bt_property_type_t type); + + /** Set Bluetooth Adapter property of 'type' */ + /* Based on the type, val shall be one of + * bt_bdaddr_t or bt_bdname_t or bt_scanmode_t etc + */ + int (*set_adapter_property)(const bt_property_t *property); + + /** Get all Remote Device properties */ + int (*get_remote_device_properties)(bt_bdaddr_t *remote_addr); + + /** Get Remote Device property of 'type' */ + int (*get_remote_device_property)(bt_bdaddr_t *remote_addr, + bt_property_type_t type); + + /** Set Remote Device property of 'type' */ + int (*set_remote_device_property)(bt_bdaddr_t *remote_addr, + const bt_property_t *property); + + /** Get Remote Device's service record for the given UUID */ + int (*get_remote_service_record)(bt_bdaddr_t *remote_addr, + bt_uuid_t *uuid); + + /** Start SDP to get remote services */ + int (*get_remote_services)(bt_bdaddr_t *remote_addr); + + /** Start Discovery */ + int (*start_discovery)(void); + + /** Cancel Discovery */ + int (*cancel_discovery)(void); + + /** Create Bluetooth Bonding */ + int (*create_bond)(const bt_bdaddr_t *bd_addr, int transport); + + /** Remove Bond */ + int (*remove_bond)(const bt_bdaddr_t *bd_addr); + + /** Cancel Bond */ + int (*cancel_bond)(const bt_bdaddr_t *bd_addr); + + /** + * Get the connection status for a given remote device. + * return value of 0 means the device is not connected, + * non-zero return status indicates an active connection. + */ + int (*get_connection_state)(const bt_bdaddr_t *bd_addr); + + /** BT Legacy PinKey Reply */ + /** If accept==FALSE, then pin_len and pin_code shall be 0x0 */ + int (*pin_reply)(const bt_bdaddr_t *bd_addr, uint8_t accept, + uint8_t pin_len, bt_pin_code_t *pin_code); + + /** BT SSP Reply - Just Works, Numeric Comparison and Passkey + * passkey shall be zero for BT_SSP_VARIANT_PASSKEY_COMPARISON & + * BT_SSP_VARIANT_CONSENT + * For BT_SSP_VARIANT_PASSKEY_ENTRY, if accept==FALSE, then passkey + * shall be zero */ + int (*ssp_reply)(const bt_bdaddr_t *bd_addr, bt_ssp_variant_t variant, + uint8_t accept, uint32_t passkey); + + /** Get Bluetooth profile interface */ + const void* (*get_profile_interface) (const char *profile_id); + + /** Bluetooth Test Mode APIs - Bluetooth must be enabled for these APIs */ + /* Configure DUT Mode - Use this mode to enter/exit DUT mode */ + int (*dut_mode_configure)(uint8_t enable); + + /* Send any test HCI (vendor-specific) command to the controller. Must be in DUT Mode */ + int (*dut_mode_send)(uint16_t opcode, uint8_t *buf, uint8_t len); + + /* Send any test HCI command to the controller. */ + int (*hci_cmd_send)(uint16_t opcode, uint8_t *buf, uint8_t len); + + /** BLE Test Mode APIs */ + /* opcode MUST be one of: LE_Receiver_Test, LE_Transmitter_Test, LE_Test_End */ + int (*le_test_mode)(uint16_t opcode, uint8_t *buf, uint8_t len); + + /* enable or disable bluetooth HCI snoop log */ + int (*config_hci_snoop_log)(uint8_t enable); + + /** Sets the OS call-out functions that bluedroid needs for alarms and wake locks. + * This should be called immediately after a successful |init|. + */ + int (*set_os_callouts)(bt_os_callouts_t *callouts); + + /** Read Energy info details - return value indicates BT_STATUS_SUCCESS or BT_STATUS_NOT_READY + * Success indicates that the VSC command was sent to controller + */ + int (*read_energy_info)(); + + /** + * Native support for dumpsys function + * Function is synchronous and |fd| is owned by caller. + */ + void (*dump)(int fd); + + /** + * Clear /data/misc/bt_config.conf and erase all stored connections + */ + int (*config_clear)(void); + + /** BT stack Test interface */ + const void* (*get_testapp_interface)(int test_app_profile); + + /** + * Clear (reset) the dynamic portion of the device interoperability database. + */ + void (*interop_database_clear)(void); + + /** + * Add a new device interoperability workaround for a remote device whose + * first |len| bytes of the its device address match |addr|. + * NOTE: |feature| has to match an item defined in interop_feature_t (interop.h). + */ + void (*interop_database_add)(uint16_t feature, const bt_bdaddr_t *addr, size_t len); +} bt_interface_t; + +/** TODO: Need to add APIs for Service Discovery, Service authorization and + * connection management. Also need to add APIs for configuring + * properties of remote bonded devices such as name, UUID etc. */ + +typedef struct { + struct hw_device_t common; + const bt_interface_t* (*get_bluetooth_interface)(); +} bluetooth_device_t; + +typedef bluetooth_device_t bluetooth_module_t; + + +__END_DECLS + +#endif /* ANDROID_INCLUDE_BLUETOOTH_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/bt_av.h b/phonelibs/android_hardware_libhardware/include/hardware/bt_av.h new file mode 100644 index 0000000000..be82fbeffd --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/bt_av.h @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2013-2014, The Linux Foundation. All rights reserved. + * Not a Contribution. + * + * 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_INCLUDE_BT_AV_H +#define ANDROID_INCLUDE_BT_AV_H + +__BEGIN_DECLS + +/* Bluetooth AV connection states */ +typedef enum { + BTAV_CONNECTION_STATE_DISCONNECTED = 0, + BTAV_CONNECTION_STATE_CONNECTING, + BTAV_CONNECTION_STATE_CONNECTED, + BTAV_CONNECTION_STATE_DISCONNECTING +} btav_connection_state_t; + +/* Bluetooth AV datapath states */ +typedef enum { + BTAV_AUDIO_STATE_REMOTE_SUSPEND = 0, + BTAV_AUDIO_STATE_STOPPED, + BTAV_AUDIO_STATE_STARTED, +} btav_audio_state_t; + + +/** Callback for connection state change. + * state will have one of the values from btav_connection_state_t + */ +typedef void (* btav_connection_state_callback)(btav_connection_state_t state, + bt_bdaddr_t *bd_addr); + +/** Callback for audiopath state change. + * state will have one of the values from btav_audio_state_t + */ +typedef void (* btav_audio_state_callback)(btav_audio_state_t state, + bt_bdaddr_t *bd_addr); + +/** Callback for connection priority of device for incoming connection + * btav_connection_priority_t + */ +typedef void (* btav_connection_priority_callback)(bt_bdaddr_t *bd_addr); + +/** Callback for audio configuration change. + * Used only for the A2DP sink interface. + * state will have one of the values from btav_audio_state_t + * sample_rate: sample rate in Hz + * channel_count: number of channels (1 for mono, 2 for stereo) + */ +typedef void (* btav_audio_config_callback)(bt_bdaddr_t *bd_addr, + uint32_t sample_rate, + uint8_t channel_count); + +/** Callback for updating apps for A2dp multicast state. + */ + +typedef void (* btav_is_multicast_enabled_callback)(int state); + +/* + * Callback for audio focus request to be used only in + * case of A2DP Sink. This is required because we are using + * AudioTrack approach for audio data rendering. + */ +typedef void (* btav_audio_focus_request_callback)(bt_bdaddr_t *bd_addr); + +/** BT-AV callback structure. */ +typedef struct { + /** set to sizeof(btav_callbacks_t) */ + size_t size; + btav_connection_state_callback connection_state_cb; + btav_audio_state_callback audio_state_cb; + btav_audio_config_callback audio_config_cb; + btav_connection_priority_callback connection_priority_cb; + btav_is_multicast_enabled_callback multicast_state_cb; + btav_audio_focus_request_callback audio_focus_request_cb; +} btav_callbacks_t; + +/** + * NOTE: + * + * 1. AVRCP 1.0 shall be supported initially. AVRCP passthrough commands + * shall be handled internally via uinput + * + * 2. A2DP data path shall be handled via a socket pipe between the AudioFlinger + * android_audio_hw library and the Bluetooth stack. + * + */ +/** Represents the standard BT-AV interface. + * Used for both the A2DP source and sink interfaces. + */ +typedef struct { + + /** set to sizeof(btav_interface_t) */ + size_t size; + /** + * Register the BtAv callbacks + */ + bt_status_t (*init)( btav_callbacks_t* callbacks , int max_a2dp_connections, + int a2dp_multicast_state); + + /** connect to headset */ + bt_status_t (*connect)( bt_bdaddr_t *bd_addr ); + + /** dis-connect from headset */ + bt_status_t (*disconnect)( bt_bdaddr_t *bd_addr ); + + /** Closes the interface. */ + void (*cleanup)( void ); + + /** Send priority of device to stack*/ + void (*allow_connection)( int is_valid , bt_bdaddr_t *bd_addr); + + /** Sends Audio Focus State. */ + void (*audio_focus_state)( int focus_state ); +} btav_interface_t; + +__END_DECLS + +#endif /* ANDROID_INCLUDE_BT_AV_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/bt_common_types.h b/phonelibs/android_hardware_libhardware/include/hardware/bt_common_types.h new file mode 100644 index 0000000000..e30ac24e3c --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/bt_common_types.h @@ -0,0 +1,44 @@ +/* + * 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. + */ + +/****************************************************************************** + * + * This file contains constants and definitions that can be used commonly between JNI and stack layer + * + ******************************************************************************/ +#ifndef ANDROID_INCLUDE_BT_COMMON_TYPES_H +#define ANDROID_INCLUDE_BT_COMMON_TYPES_H + +#include "bluetooth.h" + +typedef struct +{ + uint8_t client_if; + uint8_t filt_index; + uint8_t advertiser_state; + uint8_t advertiser_info_present; + uint8_t addr_type; + uint8_t tx_power; + int8_t rssi_value; + uint16_t time_stamp; + bt_bdaddr_t bd_addr; + uint8_t adv_pkt_len; + uint8_t *p_adv_pkt_data; + uint8_t scan_rsp_len; + uint8_t *p_scan_rsp_data; +} btgatt_track_adv_info_t; + +#endif /* ANDROID_INCLUDE_BT_COMMON_TYPES_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/bt_gatt.h b/phonelibs/android_hardware_libhardware/include/hardware/bt_gatt.h new file mode 100644 index 0000000000..42e14c2f15 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/bt_gatt.h @@ -0,0 +1,61 @@ +/* + * 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_INCLUDE_BT_GATT_H +#define ANDROID_INCLUDE_BT_GATT_H + +#include +#include "bt_gatt_client.h" +#include "bt_gatt_server.h" + +__BEGIN_DECLS + +/** BT-GATT callbacks */ +typedef struct { + /** Set to sizeof(btgatt_callbacks_t) */ + size_t size; + + /** GATT Client callbacks */ + const btgatt_client_callbacks_t* client; + + /** GATT Server callbacks */ + const btgatt_server_callbacks_t* server; +} btgatt_callbacks_t; + +/** Represents the standard Bluetooth GATT interface. */ +typedef struct { + /** Set to sizeof(btgatt_interface_t) */ + size_t size; + + /** + * Initializes the interface and provides callback routines + */ + bt_status_t (*init)( const btgatt_callbacks_t* callbacks ); + + /** Closes the interface */ + void (*cleanup)( void ); + + /** Pointer to the GATT client interface methods.*/ + const btgatt_client_interface_t* client; + + /** Pointer to the GATT server interface methods.*/ + const btgatt_server_interface_t* server; +} btgatt_interface_t; + +__END_DECLS + +#endif /* ANDROID_INCLUDE_BT_GATT_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/bt_gatt_client.h b/phonelibs/android_hardware_libhardware/include/hardware/bt_gatt_client.h new file mode 100644 index 0000000000..e7e8e82bb9 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/bt_gatt_client.h @@ -0,0 +1,455 @@ +/* + * 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_INCLUDE_BT_GATT_CLIENT_H +#define ANDROID_INCLUDE_BT_GATT_CLIENT_H + +#include +#include "bt_gatt_types.h" +#include "bt_common_types.h" + +__BEGIN_DECLS + +/** + * Buffer sizes for maximum attribute length and maximum read/write + * operation buffer size. + */ +#define BTGATT_MAX_ATTR_LEN 600 + +/** Buffer type for unformatted reads/writes */ +typedef struct +{ + uint8_t value[BTGATT_MAX_ATTR_LEN]; + uint16_t len; +} btgatt_unformatted_value_t; + +/** Parameters for GATT read operations */ +typedef struct +{ + btgatt_srvc_id_t srvc_id; + btgatt_gatt_id_t char_id; + btgatt_gatt_id_t descr_id; + btgatt_unformatted_value_t value; + uint16_t value_type; + uint8_t status; +} btgatt_read_params_t; + +/** Parameters for GATT write operations */ +typedef struct +{ + btgatt_srvc_id_t srvc_id; + btgatt_gatt_id_t char_id; + btgatt_gatt_id_t descr_id; + uint8_t status; +} btgatt_write_params_t; + +/** Attribute change notification parameters */ +typedef struct +{ + uint8_t value[BTGATT_MAX_ATTR_LEN]; + bt_bdaddr_t bda; + btgatt_srvc_id_t srvc_id; + btgatt_gatt_id_t char_id; + uint16_t len; + uint8_t is_notify; +} btgatt_notify_params_t; + +typedef struct +{ + uint8_t client_if; + uint8_t action; + uint8_t filt_index; + uint16_t feat_seln; + uint16_t list_logic_type; + uint8_t filt_logic_type; + uint8_t rssi_high_thres; + uint8_t rssi_low_thres; + uint8_t dely_mode; + uint16_t found_timeout; + uint16_t lost_timeout; + uint8_t found_timeout_cnt; + uint16_t num_of_tracking_entries; +} btgatt_filt_param_setup_t; + +typedef struct +{ + bt_bdaddr_t *bda1; + bt_uuid_t *uuid1; + uint16_t u1; + uint16_t u2; + uint16_t u3; + uint16_t u4; + uint16_t u5; +} btgatt_test_params_t; + +/* BT GATT client error codes */ +typedef enum +{ + BT_GATTC_COMMAND_SUCCESS = 0, /* 0 Command succeeded */ + BT_GATTC_COMMAND_STARTED, /* 1 Command started OK. */ + BT_GATTC_COMMAND_BUSY, /* 2 Device busy with another command */ + BT_GATTC_COMMAND_STORED, /* 3 request is stored in control block */ + BT_GATTC_NO_RESOURCES, /* 4 No resources to issue command */ + BT_GATTC_MODE_UNSUPPORTED, /* 5 Request for 1 or more unsupported modes */ + BT_GATTC_ILLEGAL_VALUE, /* 6 Illegal command /parameter value */ + BT_GATTC_INCORRECT_STATE, /* 7 Device in wrong state for request */ + BT_GATTC_UNKNOWN_ADDR, /* 8 Unknown remote BD address */ + BT_GATTC_DEVICE_TIMEOUT, /* 9 Device timeout */ + BT_GATTC_INVALID_CONTROLLER_OUTPUT,/* 10 An incorrect value was received from HCI */ + BT_GATTC_SECURITY_ERROR, /* 11 Authorization or security failure or not authorized */ + BT_GATTC_DELAYED_ENCRYPTION_CHECK, /*12 Delayed encryption check */ + BT_GATTC_ERR_PROCESSING /* 12 Generic error */ +} btgattc_error_t; + +/** BT-GATT Client callback structure. */ + +/** Callback invoked in response to register_client */ +typedef void (*register_client_callback)(int status, int client_if, + bt_uuid_t *app_uuid); + +/** Callback for scan results */ +typedef void (*scan_result_callback)(bt_bdaddr_t* bda, int rssi, uint8_t* adv_data); + +/** GATT open callback invoked in response to open */ +typedef void (*connect_callback)(int conn_id, int status, int client_if, bt_bdaddr_t* bda); + +/** Callback invoked in response to close */ +typedef void (*disconnect_callback)(int conn_id, int status, + int client_if, bt_bdaddr_t* bda); + +/** + * Invoked in response to search_service when the GATT service search + * has been completed. + */ +typedef void (*search_complete_callback)(int conn_id, int status); + +/** Reports GATT services on a remote device */ +typedef void (*search_result_callback)( int conn_id, btgatt_srvc_id_t *srvc_id); + +/** GATT characteristic enumeration result callback */ +typedef void (*get_characteristic_callback)(int conn_id, int status, + btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *char_id, + int char_prop); + +/** GATT descriptor enumeration result callback */ +typedef void (*get_descriptor_callback)(int conn_id, int status, + btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *char_id, + btgatt_gatt_id_t *descr_id); + +/** GATT included service enumeration result callback */ +typedef void (*get_included_service_callback)(int conn_id, int status, + btgatt_srvc_id_t *srvc_id, btgatt_srvc_id_t *incl_srvc_id); + +/** Callback invoked in response to [de]register_for_notification */ +typedef void (*register_for_notification_callback)(int conn_id, + int registered, int status, btgatt_srvc_id_t *srvc_id, + btgatt_gatt_id_t *char_id); + +/** + * Remote device notification callback, invoked when a remote device sends + * a notification or indication that a client has registered for. + */ +typedef void (*notify_callback)(int conn_id, btgatt_notify_params_t *p_data); + +/** Reports result of a GATT read operation */ +typedef void (*read_characteristic_callback)(int conn_id, int status, + btgatt_read_params_t *p_data); + +/** GATT write characteristic operation callback */ +typedef void (*write_characteristic_callback)(int conn_id, int status, + btgatt_write_params_t *p_data); + +/** GATT execute prepared write callback */ +typedef void (*execute_write_callback)(int conn_id, int status); + +/** Callback invoked in response to read_descriptor */ +typedef void (*read_descriptor_callback)(int conn_id, int status, + btgatt_read_params_t *p_data); + +/** Callback invoked in response to write_descriptor */ +typedef void (*write_descriptor_callback)(int conn_id, int status, + btgatt_write_params_t *p_data); + +/** Callback triggered in response to read_remote_rssi */ +typedef void (*read_remote_rssi_callback)(int client_if, bt_bdaddr_t* bda, + int rssi, int status); + +/** + * Callback indicating the status of a listen() operation + */ +typedef void (*listen_callback)(int status, int server_if); + +/** Callback invoked when the MTU for a given connection changes */ +typedef void (*configure_mtu_callback)(int conn_id, int status, int mtu); + +/** Callback invoked when a scan filter configuration command has completed */ +typedef void (*scan_filter_cfg_callback)(int action, int client_if, int status, int filt_type, + int avbl_space); + +/** Callback invoked when scan param has been added, cleared, or deleted */ +typedef void (*scan_filter_param_callback)(int action, int client_if, int status, + int avbl_space); + +/** Callback invoked when a scan filter configuration command has completed */ +typedef void (*scan_filter_status_callback)(int enable, int client_if, int status); + +/** Callback invoked when multi-adv enable operation has completed */ +typedef void (*multi_adv_enable_callback)(int client_if, int status); + +/** Callback invoked when multi-adv param update operation has completed */ +typedef void (*multi_adv_update_callback)(int client_if, int status); + +/** Callback invoked when multi-adv instance data set operation has completed */ +typedef void (*multi_adv_data_callback)(int client_if, int status); + +/** Callback invoked when multi-adv disable operation has completed */ +typedef void (*multi_adv_disable_callback)(int client_if, int status); + +/** + * Callback notifying an application that a remote device connection is currently congested + * and cannot receive any more data. An application should avoid sending more data until + * a further callback is received indicating the congestion status has been cleared. + */ +typedef void (*congestion_callback)(int conn_id, bool congested); +/** Callback invoked when batchscan storage config operation has completed */ +typedef void (*batchscan_cfg_storage_callback)(int client_if, int status); + +/** Callback invoked when batchscan enable / disable operation has completed */ +typedef void (*batchscan_enable_disable_callback)(int action, int client_if, int status); + +/** Callback invoked when batchscan reports are obtained */ +typedef void (*batchscan_reports_callback)(int client_if, int status, int report_format, + int num_records, int data_len, uint8_t* rep_data); + +/** Callback invoked when batchscan storage threshold limit is crossed */ +typedef void (*batchscan_threshold_callback)(int client_if); + +/** Track ADV VSE callback invoked when tracked device is found or lost */ +typedef void (*track_adv_event_callback)(btgatt_track_adv_info_t *p_track_adv_info); + +/** Callback invoked when scan parameter setup has completed */ +typedef void (*scan_parameter_setup_completed_callback)(int client_if, + btgattc_error_t status); + +typedef struct { + register_client_callback register_client_cb; + scan_result_callback scan_result_cb; + connect_callback open_cb; + disconnect_callback close_cb; + search_complete_callback search_complete_cb; + search_result_callback search_result_cb; + get_characteristic_callback get_characteristic_cb; + get_descriptor_callback get_descriptor_cb; + get_included_service_callback get_included_service_cb; + register_for_notification_callback register_for_notification_cb; + notify_callback notify_cb; + read_characteristic_callback read_characteristic_cb; + write_characteristic_callback write_characteristic_cb; + read_descriptor_callback read_descriptor_cb; + write_descriptor_callback write_descriptor_cb; + execute_write_callback execute_write_cb; + read_remote_rssi_callback read_remote_rssi_cb; + listen_callback listen_cb; + configure_mtu_callback configure_mtu_cb; + scan_filter_cfg_callback scan_filter_cfg_cb; + scan_filter_param_callback scan_filter_param_cb; + scan_filter_status_callback scan_filter_status_cb; + multi_adv_enable_callback multi_adv_enable_cb; + multi_adv_update_callback multi_adv_update_cb; + multi_adv_data_callback multi_adv_data_cb; + multi_adv_disable_callback multi_adv_disable_cb; + congestion_callback congestion_cb; + batchscan_cfg_storage_callback batchscan_cfg_storage_cb; + batchscan_enable_disable_callback batchscan_enb_disable_cb; + batchscan_reports_callback batchscan_reports_cb; + batchscan_threshold_callback batchscan_threshold_cb; + track_adv_event_callback track_adv_event_cb; + scan_parameter_setup_completed_callback scan_parameter_setup_completed_cb; +} btgatt_client_callbacks_t; + +/** Represents the standard BT-GATT client interface. */ + +typedef struct { + /** Registers a GATT client application with the stack */ + bt_status_t (*register_client)( bt_uuid_t *uuid ); + + /** Unregister a client application from the stack */ + bt_status_t (*unregister_client)(int client_if ); + + /** Start or stop LE device scanning */ + bt_status_t (*scan)( bool start ); + + /** Create a connection to a remote LE or dual-mode device */ + bt_status_t (*connect)( int client_if, const bt_bdaddr_t *bd_addr, + bool is_direct, int transport ); + + /** Disconnect a remote device or cancel a pending connection */ + bt_status_t (*disconnect)( int client_if, const bt_bdaddr_t *bd_addr, + int conn_id); + + /** Start or stop advertisements to listen for incoming connections */ + bt_status_t (*listen)(int client_if, bool start); + + /** Clear the attribute cache for a given device */ + bt_status_t (*refresh)( int client_if, const bt_bdaddr_t *bd_addr ); + + /** + * Enumerate all GATT services on a connected device. + * Optionally, the results can be filtered for a given UUID. + */ + bt_status_t (*search_service)(int conn_id, bt_uuid_t *filter_uuid ); + + /** + * Enumerate included services for a given service. + * Set start_incl_srvc_id to NULL to get the first included service. + */ + bt_status_t (*get_included_service)( int conn_id, btgatt_srvc_id_t *srvc_id, + btgatt_srvc_id_t *start_incl_srvc_id); + + /** + * Enumerate characteristics for a given service. + * Set start_char_id to NULL to get the first characteristic. + */ + bt_status_t (*get_characteristic)( int conn_id, + btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *start_char_id); + + /** + * Enumerate descriptors for a given characteristic. + * Set start_descr_id to NULL to get the first descriptor. + */ + bt_status_t (*get_descriptor)( int conn_id, + btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *char_id, + btgatt_gatt_id_t *start_descr_id); + + /** Read a characteristic on a remote device */ + bt_status_t (*read_characteristic)( int conn_id, + btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *char_id, + int auth_req ); + + /** Write a remote characteristic */ + bt_status_t (*write_characteristic)(int conn_id, + btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *char_id, + int write_type, int len, int auth_req, + char* p_value); + + /** Read the descriptor for a given characteristic */ + bt_status_t (*read_descriptor)(int conn_id, + btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *char_id, + btgatt_gatt_id_t *descr_id, int auth_req); + + /** Write a remote descriptor for a given characteristic */ + bt_status_t (*write_descriptor)( int conn_id, + btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *char_id, + btgatt_gatt_id_t *descr_id, int write_type, int len, + int auth_req, char* p_value); + + /** Execute a prepared write operation */ + bt_status_t (*execute_write)(int conn_id, int execute); + + /** + * Register to receive notifications or indications for a given + * characteristic + */ + bt_status_t (*register_for_notification)( int client_if, + const bt_bdaddr_t *bd_addr, btgatt_srvc_id_t *srvc_id, + btgatt_gatt_id_t *char_id); + + /** Deregister a previous request for notifications/indications */ + bt_status_t (*deregister_for_notification)( int client_if, + const bt_bdaddr_t *bd_addr, btgatt_srvc_id_t *srvc_id, + btgatt_gatt_id_t *char_id); + + /** Request RSSI for a given remote device */ + bt_status_t (*read_remote_rssi)( int client_if, const bt_bdaddr_t *bd_addr); + + /** Setup scan filter params */ + bt_status_t (*scan_filter_param_setup)(btgatt_filt_param_setup_t filt_param); + + + /** Configure a scan filter condition */ + bt_status_t (*scan_filter_add_remove)(int client_if, int action, int filt_type, + int filt_index, int company_id, + int company_id_mask, const bt_uuid_t *p_uuid, + const bt_uuid_t *p_uuid_mask, const bt_bdaddr_t *bd_addr, + char addr_type, int data_len, char* p_data, int mask_len, + char* p_mask); + + /** Clear all scan filter conditions for specific filter index*/ + bt_status_t (*scan_filter_clear)(int client_if, int filt_index); + + /** Enable / disable scan filter feature*/ + bt_status_t (*scan_filter_enable)(int client_if, bool enable); + + /** Determine the type of the remote device (LE, BR/EDR, Dual-mode) */ + int (*get_device_type)( const bt_bdaddr_t *bd_addr ); + + /** Set the advertising data or scan response data */ + bt_status_t (*set_adv_data)(int client_if, bool set_scan_rsp, bool include_name, + bool include_txpower, int min_interval, int max_interval, int appearance, + uint16_t manufacturer_len, char* manufacturer_data, + uint16_t service_data_len, char* service_data, + uint16_t service_uuid_len, char* service_uuid); + + /** Configure the MTU for a given connection */ + bt_status_t (*configure_mtu)(int conn_id, int mtu); + + /** Request a connection parameter update */ + bt_status_t (*conn_parameter_update)(const bt_bdaddr_t *bd_addr, int min_interval, + int max_interval, int latency, int timeout); + + /** Sets the LE scan interval and window in units of N*0.625 msec */ + bt_status_t (*set_scan_parameters)(int client_if, int scan_interval, int scan_window); + + /* Setup the parameters as per spec, user manual specified values and enable multi ADV */ + bt_status_t (*multi_adv_enable)(int client_if, int min_interval,int max_interval,int adv_type, + int chnl_map, int tx_power, int timeout_s); + + /* Update the parameters as per spec, user manual specified values and restart multi ADV */ + bt_status_t (*multi_adv_update)(int client_if, int min_interval,int max_interval,int adv_type, + int chnl_map, int tx_power, int timeout_s); + + /* Setup the data for the specified instance */ + bt_status_t (*multi_adv_set_inst_data)(int client_if, bool set_scan_rsp, bool include_name, + bool incl_txpower, int appearance, int manufacturer_len, + char* manufacturer_data, int service_data_len, + char* service_data, int service_uuid_len, char* service_uuid); + + /* Disable the multi adv instance */ + bt_status_t (*multi_adv_disable)(int client_if); + + /* Configure the batchscan storage */ + bt_status_t (*batchscan_cfg_storage)(int client_if, int batch_scan_full_max, + int batch_scan_trunc_max, int batch_scan_notify_threshold); + + /* Enable batchscan */ + bt_status_t (*batchscan_enb_batch_scan)(int client_if, int scan_mode, + int scan_interval, int scan_window, int addr_type, int discard_rule); + + /* Disable batchscan */ + bt_status_t (*batchscan_dis_batch_scan)(int client_if); + + /* Read out batchscan reports */ + bt_status_t (*batchscan_read_reports)(int client_if, int scan_mode); + + /** Test mode interface */ + bt_status_t (*test_command)( int command, btgatt_test_params_t* params); + +} btgatt_client_interface_t; + +__END_DECLS + +#endif /* ANDROID_INCLUDE_BT_GATT_CLIENT_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/bt_gatt_server.h b/phonelibs/android_hardware_libhardware/include/hardware/bt_gatt_server.h new file mode 100644 index 0000000000..0d6cc1e8d6 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/bt_gatt_server.h @@ -0,0 +1,196 @@ +/* + * 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_INCLUDE_BT_GATT_SERVER_H +#define ANDROID_INCLUDE_BT_GATT_SERVER_H + +#include + +#include "bt_gatt_types.h" + +__BEGIN_DECLS + +/** GATT value type used in response to remote read requests */ +typedef struct +{ + uint8_t value[BTGATT_MAX_ATTR_LEN]; + uint16_t handle; + uint16_t offset; + uint16_t len; + uint8_t auth_req; +} btgatt_value_t; + +/** GATT remote read request response type */ +typedef union +{ + btgatt_value_t attr_value; + uint16_t handle; +} btgatt_response_t; + +/** BT-GATT Server callback structure. */ + +/** Callback invoked in response to register_server */ +typedef void (*register_server_callback)(int status, int server_if, + bt_uuid_t *app_uuid); + +/** Callback indicating that a remote device has connected or been disconnected */ +typedef void (*connection_callback)(int conn_id, int server_if, int connected, + bt_bdaddr_t *bda); + +/** Callback invoked in response to create_service */ +typedef void (*service_added_callback)(int status, int server_if, + btgatt_srvc_id_t *srvc_id, int srvc_handle); + +/** Callback indicating that an included service has been added to a service */ +typedef void (*included_service_added_callback)(int status, int server_if, + int srvc_handle, int incl_srvc_handle); + +/** Callback invoked when a characteristic has been added to a service */ +typedef void (*characteristic_added_callback)(int status, int server_if, + bt_uuid_t *uuid, int srvc_handle, int char_handle); + +/** Callback invoked when a descriptor has been added to a characteristic */ +typedef void (*descriptor_added_callback)(int status, int server_if, + bt_uuid_t *uuid, int srvc_handle, int descr_handle); + +/** Callback invoked in response to start_service */ +typedef void (*service_started_callback)(int status, int server_if, + int srvc_handle); + +/** Callback invoked in response to stop_service */ +typedef void (*service_stopped_callback)(int status, int server_if, + int srvc_handle); + +/** Callback triggered when a service has been deleted */ +typedef void (*service_deleted_callback)(int status, int server_if, + int srvc_handle); + +/** + * Callback invoked when a remote device has requested to read a characteristic + * or descriptor. The application must respond by calling send_response + */ +typedef void (*request_read_callback)(int conn_id, int trans_id, bt_bdaddr_t *bda, + int attr_handle, int offset, bool is_long); + +/** + * Callback invoked when a remote device has requested to write to a + * characteristic or descriptor. + */ +typedef void (*request_write_callback)(int conn_id, int trans_id, bt_bdaddr_t *bda, + int attr_handle, int offset, int length, + bool need_rsp, bool is_prep, uint8_t* value); + +/** Callback invoked when a previously prepared write is to be executed */ +typedef void (*request_exec_write_callback)(int conn_id, int trans_id, + bt_bdaddr_t *bda, int exec_write); + +/** + * Callback triggered in response to send_response if the remote device + * sends a confirmation. + */ +typedef void (*response_confirmation_callback)(int status, int handle); + +/** + * Callback confirming that a notification or indication has been sent + * to a remote device. + */ +typedef void (*indication_sent_callback)(int conn_id, int status); + +/** + * Callback notifying an application that a remote device connection is currently congested + * and cannot receive any more data. An application should avoid sending more data until + * a further callback is received indicating the congestion status has been cleared. + */ +typedef void (*congestion_callback)(int conn_id, bool congested); + +/** Callback invoked when the MTU for a given connection changes */ +typedef void (*mtu_changed_callback)(int conn_id, int mtu); + +typedef struct { + register_server_callback register_server_cb; + connection_callback connection_cb; + service_added_callback service_added_cb; + included_service_added_callback included_service_added_cb; + characteristic_added_callback characteristic_added_cb; + descriptor_added_callback descriptor_added_cb; + service_started_callback service_started_cb; + service_stopped_callback service_stopped_cb; + service_deleted_callback service_deleted_cb; + request_read_callback request_read_cb; + request_write_callback request_write_cb; + request_exec_write_callback request_exec_write_cb; + response_confirmation_callback response_confirmation_cb; + indication_sent_callback indication_sent_cb; + congestion_callback congestion_cb; + mtu_changed_callback mtu_changed_cb; +} btgatt_server_callbacks_t; + +/** Represents the standard BT-GATT server interface. */ +typedef struct { + /** Registers a GATT server application with the stack */ + bt_status_t (*register_server)( bt_uuid_t *uuid ); + + /** Unregister a server application from the stack */ + bt_status_t (*unregister_server)(int server_if ); + + /** Create a connection to a remote peripheral */ + bt_status_t (*connect)(int server_if, const bt_bdaddr_t *bd_addr, + bool is_direct, int transport); + + /** Disconnect an established connection or cancel a pending one */ + bt_status_t (*disconnect)(int server_if, const bt_bdaddr_t *bd_addr, + int conn_id ); + + /** Create a new service */ + bt_status_t (*add_service)( int server_if, btgatt_srvc_id_t *srvc_id, int num_handles); + + /** Assign an included service to it's parent service */ + bt_status_t (*add_included_service)( int server_if, int service_handle, int included_handle); + + /** Add a characteristic to a service */ + bt_status_t (*add_characteristic)( int server_if, + int service_handle, bt_uuid_t *uuid, + int properties, int permissions); + + /** Add a descriptor to a given service */ + bt_status_t (*add_descriptor)(int server_if, int service_handle, + bt_uuid_t *uuid, int permissions); + + /** Starts a local service */ + bt_status_t (*start_service)(int server_if, int service_handle, + int transport); + + /** Stops a local service */ + bt_status_t (*stop_service)(int server_if, int service_handle); + + /** Delete a local service */ + bt_status_t (*delete_service)(int server_if, int service_handle); + + /** Send value indication to a remote device */ + bt_status_t (*send_indication)(int server_if, int attribute_handle, + int conn_id, int len, int confirm, + char* p_value); + + /** Send a response to a read/write operation */ + bt_status_t (*send_response)(int conn_id, int trans_id, + int status, btgatt_response_t *response); + +} btgatt_server_interface_t; + +__END_DECLS + +#endif /* ANDROID_INCLUDE_BT_GATT_CLIENT_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/bt_gatt_types.h b/phonelibs/android_hardware_libhardware/include/hardware/bt_gatt_types.h new file mode 100644 index 0000000000..e037ddcdbb --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/bt_gatt_types.h @@ -0,0 +1,56 @@ +/* + * 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_INCLUDE_BT_GATT_TYPES_H +#define ANDROID_INCLUDE_BT_GATT_TYPES_H + +#include +#include + +__BEGIN_DECLS + +/** + * GATT Service types + */ +#define BTGATT_SERVICE_TYPE_PRIMARY 0 +#define BTGATT_SERVICE_TYPE_SECONDARY 1 + +/** GATT ID adding instance id tracking to the UUID */ +typedef struct +{ + bt_uuid_t uuid; + uint8_t inst_id; +} btgatt_gatt_id_t; + +/** GATT Service ID also identifies the service type (primary/secondary) */ +typedef struct +{ + btgatt_gatt_id_t id; + uint8_t is_primary; +} btgatt_srvc_id_t; + +/** Preferred physical Transport for GATT connection */ +typedef enum +{ + GATT_TRANSPORT_AUTO, + GATT_TRANSPORT_BREDR, + GATT_TRANSPORT_LE +} btgatt_transport_t; + +__END_DECLS + +#endif /* ANDROID_INCLUDE_BT_GATT_TYPES_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/bt_hd.h b/phonelibs/android_hardware_libhardware/include/hardware/bt_hd.h new file mode 100644 index 0000000000..6ba5b097d0 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/bt_hd.h @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2013, The Linux Foundation. All rights reserved. + * Not a Contribution + * 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_INCLUDE_BT_HD_H +#define ANDROID_INCLUDE_BT_HD_H + +#include + +__BEGIN_DECLS + +typedef enum +{ + BTHD_REPORT_TYPE_OTHER = 0, + BTHD_REPORT_TYPE_INPUT, + BTHD_REPORT_TYPE_OUTPUT, + BTHD_REPORT_TYPE_FEATURE, + BTHD_REPORT_TYPE_INTRDATA // special value for reports to be sent on INTR (INPUT is assumed) +} bthd_report_type_t; + +typedef enum +{ + BTHD_APP_STATE_NOT_REGISTERED, + BTHD_APP_STATE_REGISTERED +} bthd_application_state_t; + +typedef enum +{ + BTHD_CONN_STATE_CONNECTED, + BTHD_CONN_STATE_CONNECTING, + BTHD_CONN_STATE_DISCONNECTED, + BTHD_CONN_STATE_DISCONNECTING, + BTHD_CONN_STATE_UNKNOWN +} bthd_connection_state_t; + +typedef struct +{ + const char *name; + const char *description; + const char *provider; + uint8_t subclass; + uint8_t *desc_list; + int desc_list_len; +} bthd_app_param_t; + +typedef struct +{ + uint8_t service_type; + uint32_t token_rate; + uint32_t token_bucket_size; + uint32_t peak_bandwidth; + uint32_t access_latency; + uint32_t delay_variation; +} bthd_qos_param_t; + +typedef void (* bthd_application_state_callback)(bt_bdaddr_t *bd_addr, bthd_application_state_t state); +typedef void (* bthd_connection_state_callback)(bt_bdaddr_t *bd_addr, bthd_connection_state_t state); +typedef void (* bthd_get_report_callback)(uint8_t type, uint8_t id, uint16_t buffer_size); +typedef void (* bthd_set_report_callback)(uint8_t type, uint8_t id, uint16_t len, uint8_t *p_data); +typedef void (* bthd_set_protocol_callback)(uint8_t protocol); +typedef void (* bthd_intr_data_callback)(uint8_t report_id, uint16_t len, uint8_t *p_data); +typedef void (* bthd_vc_unplug_callback)(void); + +/** BT-HD callbacks */ +typedef struct { + size_t size; + + bthd_application_state_callback application_state_cb; + bthd_connection_state_callback connection_state_cb; + bthd_get_report_callback get_report_cb; + bthd_set_report_callback set_report_cb; + bthd_set_protocol_callback set_protocol_cb; + bthd_intr_data_callback intr_data_cb; + bthd_vc_unplug_callback vc_unplug_cb; +} bthd_callbacks_t; + +/** BT-HD interface */ +typedef struct { + + size_t size; + + /** init interface and register callbacks */ + bt_status_t (*init)(bthd_callbacks_t* callbacks); + + /** close interface */ + void (*cleanup)(void); + + /** register application */ + bt_status_t (*register_app)(bthd_app_param_t *app_param, bthd_qos_param_t *in_qos, + bthd_qos_param_t *out_qos); + + /** unregister application */ + bt_status_t (*unregister_app)(void); + + /** connects to host with virtual cable */ + bt_status_t (*connect)(void); + + /** disconnects from currently connected host */ + bt_status_t (*disconnect)(void); + + /** send report */ + bt_status_t (*send_report)(bthd_report_type_t type, uint8_t id, uint16_t len, uint8_t *p_data); + + /** notifies error for invalid SET_REPORT */ + bt_status_t (*report_error)(uint8_t error); + + /** send Virtual Cable Unplug */ + bt_status_t (*virtual_cable_unplug)(void); + +} bthd_interface_t; + +__END_DECLS + +#endif /* ANDROID_INCLUDE_BT_HD_H */ + diff --git a/phonelibs/android_hardware_libhardware/include/hardware/bt_hf.h b/phonelibs/android_hardware_libhardware/include/hardware/bt_hf.h new file mode 100644 index 0000000000..dbac061308 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/bt_hf.h @@ -0,0 +1,348 @@ +/* + * 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_INCLUDE_BT_HF_H +#define ANDROID_INCLUDE_BT_HF_H + +__BEGIN_DECLS + +/* AT response code - OK/Error */ +typedef enum { + BTHF_AT_RESPONSE_ERROR = 0, + BTHF_AT_RESPONSE_OK +} bthf_at_response_t; + +typedef enum { + BTHF_CONNECTION_STATE_DISCONNECTED = 0, + BTHF_CONNECTION_STATE_CONNECTING, + BTHF_CONNECTION_STATE_CONNECTED, + BTHF_CONNECTION_STATE_SLC_CONNECTED, + BTHF_CONNECTION_STATE_DISCONNECTING +} bthf_connection_state_t; + +typedef enum { + BTHF_AUDIO_STATE_DISCONNECTED = 0, + BTHF_AUDIO_STATE_CONNECTING, + BTHF_AUDIO_STATE_CONNECTED, + BTHF_AUDIO_STATE_DISCONNECTING +} bthf_audio_state_t; + +typedef enum { + BTHF_VR_STATE_STOPPED = 0, + BTHF_VR_STATE_STARTED +} bthf_vr_state_t; + +typedef enum { + BTHF_VOLUME_TYPE_SPK = 0, + BTHF_VOLUME_TYPE_MIC +} bthf_volume_type_t; + +/* Noise Reduction and Echo Cancellation */ +typedef enum +{ + BTHF_NREC_STOP, + BTHF_NREC_START +} bthf_nrec_t; + +/* WBS codec setting */ +typedef enum +{ + BTHF_WBS_NONE, + BTHF_WBS_NO, + BTHF_WBS_YES +}bthf_wbs_config_t; + +/* BIND type*/ +typedef enum +{ + BTHF_BIND_SET, + BTHF_BIND_READ, + BTHF_BIND_TEST +}bthf_bind_type_t; + + +/* CHLD - Call held handling */ +typedef enum +{ + BTHF_CHLD_TYPE_RELEASEHELD, // Terminate all held or set UDUB("busy") to a waiting call + BTHF_CHLD_TYPE_RELEASEACTIVE_ACCEPTHELD, // Terminate all active calls and accepts a waiting/held call + BTHF_CHLD_TYPE_HOLDACTIVE_ACCEPTHELD, // Hold all active calls and accepts a waiting/held call + BTHF_CHLD_TYPE_ADDHELDTOCONF, // Add all held calls to a conference +} bthf_chld_type_t; + +/** Callback for connection state change. + * state will have one of the values from BtHfConnectionState + */ +typedef void (* bthf_connection_state_callback)(bthf_connection_state_t state, bt_bdaddr_t *bd_addr); + +/** Callback for audio connection state change. + * state will have one of the values from BtHfAudioState + */ +typedef void (* bthf_audio_state_callback)(bthf_audio_state_t state, bt_bdaddr_t *bd_addr); + +/** Callback for VR connection state change. + * state will have one of the values from BtHfVRState + */ +typedef void (* bthf_vr_cmd_callback)(bthf_vr_state_t state, bt_bdaddr_t *bd_addr); + +/** Callback for answer incoming call (ATA) + */ +typedef void (* bthf_answer_call_cmd_callback)(bt_bdaddr_t *bd_addr); + +/** Callback for disconnect call (AT+CHUP) + */ +typedef void (* bthf_hangup_call_cmd_callback)(bt_bdaddr_t *bd_addr); + +/** Callback for disconnect call (AT+CHUP) + * type will denote Speaker/Mic gain (BtHfVolumeControl). + */ +typedef void (* bthf_volume_cmd_callback)(bthf_volume_type_t type, int volume, bt_bdaddr_t *bd_addr); + +/** Callback for dialing an outgoing call + * If number is NULL, redial + */ +typedef void (* bthf_dial_call_cmd_callback)(char *number, bt_bdaddr_t *bd_addr); + +/** Callback for sending DTMF tones + * tone contains the dtmf character to be sent + */ +typedef void (* bthf_dtmf_cmd_callback)(char tone, bt_bdaddr_t *bd_addr); + +/** Callback for enabling/disabling noise reduction/echo cancellation + * value will be 1 to enable, 0 to disable + */ +typedef void (* bthf_nrec_cmd_callback)(bthf_nrec_t nrec, bt_bdaddr_t *bd_addr); + +/** Callback for AT+BCS and event from BAC + * WBS enable, WBS disable + */ +typedef void (* bthf_wbs_callback)(bthf_wbs_config_t wbs, bt_bdaddr_t *bd_addr); + +/** Callback for call hold handling (AT+CHLD) + * value will contain the call hold command (0, 1, 2, 3) + */ +typedef void (* bthf_chld_cmd_callback)(bthf_chld_type_t chld, bt_bdaddr_t *bd_addr); + +/** Callback for CNUM (subscriber number) + */ +typedef void (* bthf_cnum_cmd_callback)(bt_bdaddr_t *bd_addr); + +/** Callback for indicators (CIND) + */ +typedef void (* bthf_cind_cmd_callback)(bt_bdaddr_t *bd_addr); + +/** Callback for operator selection (COPS) + */ +typedef void (* bthf_cops_cmd_callback)(bt_bdaddr_t *bd_addr); + +/** Callback for call list (AT+CLCC) + */ +typedef void (* bthf_clcc_cmd_callback) (bt_bdaddr_t *bd_addr); + +/** Callback for unknown AT command recd from HF + * at_string will contain the unparsed AT string + */ +typedef void (* bthf_unknown_at_cmd_callback)(char *at_string, bt_bdaddr_t *bd_addr); + +/** Callback for keypressed (HSP) event. + */ +typedef void (* bthf_key_pressed_cmd_callback)(bt_bdaddr_t *bd_addr); + +/** Callback for HF indicators (BIND) + */ +typedef void (* bthf_bind_cmd_callback)(char* hf_ind, bthf_bind_type_t type, bt_bdaddr_t *bd_addr); + +/** Callback for HF indicator value (BIEV) + */ +typedef void (* bthf_biev_cmd_callback)(char* hf_ind_val, bt_bdaddr_t *bd_addr); + + +/** BT-HF callback structure. */ +typedef struct { + /** set to sizeof(BtHfCallbacks) */ + size_t size; + bthf_connection_state_callback connection_state_cb; + bthf_audio_state_callback audio_state_cb; + bthf_vr_cmd_callback vr_cmd_cb; + bthf_answer_call_cmd_callback answer_call_cmd_cb; + bthf_hangup_call_cmd_callback hangup_call_cmd_cb; + bthf_volume_cmd_callback volume_cmd_cb; + bthf_dial_call_cmd_callback dial_call_cmd_cb; + bthf_dtmf_cmd_callback dtmf_cmd_cb; + bthf_nrec_cmd_callback nrec_cmd_cb; + bthf_wbs_callback wbs_cb; + bthf_chld_cmd_callback chld_cmd_cb; + bthf_cnum_cmd_callback cnum_cmd_cb; + bthf_cind_cmd_callback cind_cmd_cb; + bthf_cops_cmd_callback cops_cmd_cb; + bthf_clcc_cmd_callback clcc_cmd_cb; + bthf_unknown_at_cmd_callback unknown_at_cmd_cb; + bthf_key_pressed_cmd_callback key_pressed_cmd_cb; + bthf_bind_cmd_callback bind_cmd_cb; + bthf_biev_cmd_callback biev_cmd_cb; +} bthf_callbacks_t; + +/** Network Status */ +typedef enum +{ + BTHF_NETWORK_STATE_NOT_AVAILABLE = 0, + BTHF_NETWORK_STATE_AVAILABLE +} bthf_network_state_t; + +/** Service type */ +typedef enum +{ + BTHF_SERVICE_TYPE_HOME = 0, + BTHF_SERVICE_TYPE_ROAMING +} bthf_service_type_t; + +typedef enum { + BTHF_CALL_STATE_ACTIVE = 0, + BTHF_CALL_STATE_HELD, + BTHF_CALL_STATE_DIALING, + BTHF_CALL_STATE_ALERTING, + BTHF_CALL_STATE_INCOMING, + BTHF_CALL_STATE_WAITING, + BTHF_CALL_STATE_IDLE +} bthf_call_state_t; + +typedef enum { + BTHF_CALL_DIRECTION_OUTGOING = 0, + BTHF_CALL_DIRECTION_INCOMING +} bthf_call_direction_t; + +typedef enum { + BTHF_CALL_TYPE_VOICE = 0, + BTHF_CALL_TYPE_DATA, + BTHF_CALL_TYPE_FAX +} bthf_call_mode_t; + +typedef enum { + BTHF_CALL_MPTY_TYPE_SINGLE = 0, + BTHF_CALL_MPTY_TYPE_MULTI +} bthf_call_mpty_type_t; + +typedef enum { + BTHF_HF_INDICATOR_STATE_DISABLED = 0, + BTHF_HF_INDICATOR_STATE_ENABLED +} bthf_hf_indicator_status_t; + +typedef enum { + BTHF_CALL_ADDRTYPE_UNKNOWN = 0x81, + BTHF_CALL_ADDRTYPE_INTERNATIONAL = 0x91 +} bthf_call_addrtype_t; + +typedef enum { + BTHF_VOIP_CALL_NETWORK_TYPE_MOBILE = 0, + BTHF_VOIP_CALL_NETWORK_TYPE_WIFI +} bthf_voip_call_network_type_t; + +typedef enum { + BTHF_VOIP_STATE_STOPPED = 0, + BTHF_VOIP_STATE_STARTED +} bthf_voip_state_t; + +/** Represents the standard BT-HF interface. */ +typedef struct { + + /** set to sizeof(BtHfInterface) */ + size_t size; + /** + * Register the BtHf callbacks + */ + bt_status_t (*init)( bthf_callbacks_t* callbacks, int max_hf_clients); + + /** connect to headset */ + bt_status_t (*connect)( bt_bdaddr_t *bd_addr ); + + /** dis-connect from headset */ + bt_status_t (*disconnect)( bt_bdaddr_t *bd_addr ); + + /** create an audio connection */ + bt_status_t (*connect_audio)( bt_bdaddr_t *bd_addr ); + + /** close the audio connection */ + bt_status_t (*disconnect_audio)( bt_bdaddr_t *bd_addr ); + + /** start voice recognition */ + bt_status_t (*start_voice_recognition)( bt_bdaddr_t *bd_addr ); + + /** stop voice recognition */ + bt_status_t (*stop_voice_recognition)( bt_bdaddr_t *bd_addr ); + + /** volume control */ + bt_status_t (*volume_control) (bthf_volume_type_t type, int volume, bt_bdaddr_t *bd_addr ); + + /** Combined device status change notification */ + bt_status_t (*device_status_notification)(bthf_network_state_t ntk_state, bthf_service_type_t svc_type, int signal, + int batt_chg); + + /** Response for COPS command */ + bt_status_t (*cops_response)(const char *cops, bt_bdaddr_t *bd_addr ); + + /** Response for CIND command */ + bt_status_t (*cind_response)(int svc, int num_active, int num_held, bthf_call_state_t call_setup_state, + int signal, int roam, int batt_chg, bt_bdaddr_t *bd_addr ); + + /** Pre-formatted AT response, typically in response to unknown AT cmd */ + bt_status_t (*formatted_at_response)(const char *rsp, bt_bdaddr_t *bd_addr ); + + /** ok/error response + * ERROR (0) + * OK (1) + */ + bt_status_t (*at_response) (bthf_at_response_t response_code, int error_code, bt_bdaddr_t *bd_addr ); + + /** response for CLCC command + * Can be iteratively called for each call index + * Call index of 0 will be treated as NULL termination (Completes response) + */ + bt_status_t (*clcc_response) (int index, bthf_call_direction_t dir, + bthf_call_state_t state, bthf_call_mode_t mode, + bthf_call_mpty_type_t mpty, const char *number, + bthf_call_addrtype_t type, bt_bdaddr_t *bd_addr ); + + /** notify of a call state change + * Each update notifies + * 1. Number of active/held/ringing calls + * 2. call_state: This denotes the state change that triggered this msg + * This will take one of the values from BtHfCallState + * 3. number & type: valid only for incoming & waiting call + */ + bt_status_t (*phone_state_change) (int num_active, int num_held, bthf_call_state_t call_setup_state, + const char *number, bthf_call_addrtype_t type); + + /** Closes the interface. */ + void (*cleanup)( void ); + + /** configureation for the SCO codec */ + bt_status_t (*configure_wbs)( bt_bdaddr_t *bd_addr ,bthf_wbs_config_t config ); + + /** Response for BIND READ command and activation/deactivation of HF indicator */ + bt_status_t (*bind_response) (int anum, bthf_hf_indicator_status_t status, + bt_bdaddr_t *bd_addr); + + /** Response for BIND TEST command */ + bt_status_t (*bind_string_response) (const char* result, bt_bdaddr_t *bd_addr); + + /** Sends connectivity network type used by Voip currently to stack */ + bt_status_t (*voip_network_type_wifi) (bthf_voip_state_t is_voip_started, + bthf_voip_call_network_type_t is_network_wifi); +} bthf_interface_t; + +__END_DECLS + +#endif /* ANDROID_INCLUDE_BT_HF_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/bt_hf_client.h b/phonelibs/android_hardware_libhardware/include/hardware/bt_hf_client.h new file mode 100644 index 0000000000..0577e97d4b --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/bt_hf_client.h @@ -0,0 +1,375 @@ +/* + * Copyright (C) 2012-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_INCLUDE_BT_HF_CLIENT_H +#define ANDROID_INCLUDE_BT_HF_CLIENT_H + +__BEGIN_DECLS + +typedef enum { + BTHF_CLIENT_CONNECTION_STATE_DISCONNECTED = 0, + BTHF_CLIENT_CONNECTION_STATE_CONNECTING, + BTHF_CLIENT_CONNECTION_STATE_CONNECTED, + BTHF_CLIENT_CONNECTION_STATE_SLC_CONNECTED, + BTHF_CLIENT_CONNECTION_STATE_DISCONNECTING +} bthf_client_connection_state_t; + +typedef enum { + BTHF_CLIENT_AUDIO_STATE_DISCONNECTED = 0, + BTHF_CLIENT_AUDIO_STATE_CONNECTING, + BTHF_CLIENT_AUDIO_STATE_CONNECTED, + BTHF_CLIENT_AUDIO_STATE_CONNECTED_MSBC, +} bthf_client_audio_state_t; + +typedef enum { + BTHF_CLIENT_VR_STATE_STOPPED = 0, + BTHF_CLIENT_VR_STATE_STARTED +} bthf_client_vr_state_t; + +typedef enum { + BTHF_CLIENT_VOLUME_TYPE_SPK = 0, + BTHF_CLIENT_VOLUME_TYPE_MIC +} bthf_client_volume_type_t; + +typedef enum +{ + BTHF_CLIENT_NETWORK_STATE_NOT_AVAILABLE = 0, + BTHF_CLIENT_NETWORK_STATE_AVAILABLE +} bthf_client_network_state_t; + +typedef enum +{ + BTHF_CLIENT_SERVICE_TYPE_HOME = 0, + BTHF_CLIENT_SERVICE_TYPE_ROAMING +} bthf_client_service_type_t; + +typedef enum { + BTHF_CLIENT_CALL_STATE_ACTIVE = 0, + BTHF_CLIENT_CALL_STATE_HELD, + BTHF_CLIENT_CALL_STATE_DIALING, + BTHF_CLIENT_CALL_STATE_ALERTING, + BTHF_CLIENT_CALL_STATE_INCOMING, + BTHF_CLIENT_CALL_STATE_WAITING, + BTHF_CLIENT_CALL_STATE_HELD_BY_RESP_HOLD, +} bthf_client_call_state_t; + +typedef enum { + BTHF_CLIENT_CALL_NO_CALLS_IN_PROGRESS = 0, + BTHF_CLIENT_CALL_CALLS_IN_PROGRESS +} bthf_client_call_t; + +typedef enum { + BTHF_CLIENT_CALLSETUP_NONE = 0, + BTHF_CLIENT_CALLSETUP_INCOMING, + BTHF_CLIENT_CALLSETUP_OUTGOING, + BTHF_CLIENT_CALLSETUP_ALERTING + +} bthf_client_callsetup_t; + +typedef enum { + BTHF_CLIENT_CALLHELD_NONE = 0, + BTHF_CLIENT_CALLHELD_HOLD_AND_ACTIVE, + BTHF_CLIENT_CALLHELD_HOLD, +} bthf_client_callheld_t; + +typedef enum { + BTHF_CLIENT_RESP_AND_HOLD_HELD = 0, + BTRH_CLIENT_RESP_AND_HOLD_ACCEPT, + BTRH_CLIENT_RESP_AND_HOLD_REJECT, +} bthf_client_resp_and_hold_t; + +typedef enum { + BTHF_CLIENT_CALL_DIRECTION_OUTGOING = 0, + BTHF_CLIENT_CALL_DIRECTION_INCOMING +} bthf_client_call_direction_t; + +typedef enum { + BTHF_CLIENT_CALL_MPTY_TYPE_SINGLE = 0, + BTHF_CLIENT_CALL_MPTY_TYPE_MULTI +} bthf_client_call_mpty_type_t; + +typedef enum { + BTHF_CLIENT_CMD_COMPLETE_OK = 0, + BTHF_CLIENT_CMD_COMPLETE_ERROR, + BTHF_CLIENT_CMD_COMPLETE_ERROR_NO_CARRIER, + BTHF_CLIENT_CMD_COMPLETE_ERROR_BUSY, + BTHF_CLIENT_CMD_COMPLETE_ERROR_NO_ANSWER, + BTHF_CLIENT_CMD_COMPLETE_ERROR_DELAYED, + BTHF_CLIENT_CMD_COMPLETE_ERROR_BLACKLISTED, + BTHF_CLIENT_CMD_COMPLETE_ERROR_CME +} bthf_client_cmd_complete_t; + +typedef enum { + BTHF_CLIENT_CALL_ACTION_CHLD_0 = 0, + BTHF_CLIENT_CALL_ACTION_CHLD_1, + BTHF_CLIENT_CALL_ACTION_CHLD_2, + BTHF_CLIENT_CALL_ACTION_CHLD_3, + BTHF_CLIENT_CALL_ACTION_CHLD_4, + BTHF_CLIENT_CALL_ACTION_CHLD_1x, + BTHF_CLIENT_CALL_ACTION_CHLD_2x, + BTHF_CLIENT_CALL_ACTION_ATA, + BTHF_CLIENT_CALL_ACTION_CHUP, + BTHF_CLIENT_CALL_ACTION_BTRH_0, + BTHF_CLIENT_CALL_ACTION_BTRH_1, + BTHF_CLIENT_CALL_ACTION_BTRH_2, +} bthf_client_call_action_t; + +typedef enum { + BTHF_CLIENT_SERVICE_UNKNOWN = 0, + BTHF_CLIENT_SERVICE_VOICE, + BTHF_CLIENT_SERVICE_FAX +} bthf_client_subscriber_service_type_t; + +typedef enum { + BTHF_CLIENT_IN_BAND_RINGTONE_NOT_PROVIDED = 0, + BTHF_CLIENT_IN_BAND_RINGTONE_PROVIDED, +} bthf_client_in_band_ring_state_t; + +/* Peer features masks */ +#define BTHF_CLIENT_PEER_FEAT_3WAY 0x00000001 /* Three-way calling */ +#define BTHF_CLIENT_PEER_FEAT_ECNR 0x00000002 /* Echo cancellation and/or noise reduction */ +#define BTHF_CLIENT_PEER_FEAT_VREC 0x00000004 /* Voice recognition */ +#define BTHF_CLIENT_PEER_FEAT_INBAND 0x00000008 /* In-band ring tone */ +#define BTHF_CLIENT_PEER_FEAT_VTAG 0x00000010 /* Attach a phone number to a voice tag */ +#define BTHF_CLIENT_PEER_FEAT_REJECT 0x00000020 /* Ability to reject incoming call */ +#define BTHF_CLIENT_PEER_FEAT_ECS 0x00000040 /* Enhanced Call Status */ +#define BTHF_CLIENT_PEER_FEAT_ECC 0x00000080 /* Enhanced Call Control */ +#define BTHF_CLIENT_PEER_FEAT_EXTERR 0x00000100 /* Extended error codes */ +#define BTHF_CLIENT_PEER_FEAT_CODEC 0x00000200 /* Codec Negotiation */ + +/* Peer call handling features masks */ +#define BTHF_CLIENT_CHLD_FEAT_REL 0x00000001 /* 0 Release waiting call or held calls */ +#define BTHF_CLIENT_CHLD_FEAT_REL_ACC 0x00000002 /* 1 Release active calls and accept other + (waiting or held) cal */ +#define BTHF_CLIENT_CHLD_FEAT_REL_X 0x00000004 /* 1x Release specified active call only */ +#define BTHF_CLIENT_CHLD_FEAT_HOLD_ACC 0x00000008 /* 2 Active calls on hold and accept other + (waiting or held) call */ +#define BTHF_CLIENT_CHLD_FEAT_PRIV_X 0x00000010 /* 2x Request private mode with specified + call (put the rest on hold) */ +#define BTHF_CLIENT_CHLD_FEAT_MERGE 0x00000020 /* 3 Add held call to multiparty */ +#define BTHF_CLIENT_CHLD_FEAT_MERGE_DETACH 0x00000040 /* 4 Connect two calls and leave + (disconnect from) multiparty */ + +/** Callback for connection state change. + * state will have one of the values from BtHfConnectionState + * peer/chld_features are valid only for BTHF_CLIENT_CONNECTION_STATE_SLC_CONNECTED state + */ +typedef void (* bthf_client_connection_state_callback)(bthf_client_connection_state_t state, + unsigned int peer_feat, + unsigned int chld_feat, + bt_bdaddr_t *bd_addr); + +/** Callback for audio connection state change. + * state will have one of the values from BtHfAudioState + */ +typedef void (* bthf_client_audio_state_callback)(bthf_client_audio_state_t state, + bt_bdaddr_t *bd_addr); + +/** Callback for VR connection state change. + * state will have one of the values from BtHfVRState + */ +typedef void (* bthf_client_vr_cmd_callback)(bthf_client_vr_state_t state); + +/** Callback for network state change + */ +typedef void (* bthf_client_network_state_callback) (bthf_client_network_state_t state); + +/** Callback for network roaming status change + */ +typedef void (* bthf_client_network_roaming_callback) (bthf_client_service_type_t type); + +/** Callback for signal strength indication + */ +typedef void (* bthf_client_network_signal_callback) (int signal_strength); + +/** Callback for battery level indication + */ +typedef void (* bthf_client_battery_level_callback) (int battery_level); + +/** Callback for current operator name + */ +typedef void (* bthf_client_current_operator_callback) (const char *name); + +/** Callback for call indicator + */ +typedef void (* bthf_client_call_callback) (bthf_client_call_t call); + +/** Callback for callsetup indicator + */ +typedef void (* bthf_client_callsetup_callback) (bthf_client_callsetup_t callsetup); + +/** Callback for callheld indicator + */ +typedef void (* bthf_client_callheld_callback) (bthf_client_callheld_t callheld); + +/** Callback for response and hold + */ +typedef void (* bthf_client_resp_and_hold_callback) (bthf_client_resp_and_hold_t resp_and_hold); + +/** Callback for Calling Line Identification notification + * Will be called only when there is an incoming call and number is provided. + */ +typedef void (* bthf_client_clip_callback) (const char *number); + +/** + * Callback for Call Waiting notification + */ +typedef void (* bthf_client_call_waiting_callback) (const char *number); + +/** + * Callback for listing current calls. Can be called multiple time. + * If number is unknown NULL is passed. + */ +typedef void (*bthf_client_current_calls) (int index, bthf_client_call_direction_t dir, + bthf_client_call_state_t state, + bthf_client_call_mpty_type_t mpty, + const char *number); + +/** Callback for audio volume change + */ +typedef void (*bthf_client_volume_change_callback) (bthf_client_volume_type_t type, int volume); + +/** Callback for command complete event + * cme is valid only for BTHF_CLIENT_CMD_COMPLETE_ERROR_CME type + */ +typedef void (*bthf_client_cmd_complete_callback) (bthf_client_cmd_complete_t type, int cme); + +/** Callback for subscriber information + */ +typedef void (* bthf_client_subscriber_info_callback) (const char *name, + bthf_client_subscriber_service_type_t type); + +/** Callback for in-band ring tone settings + */ +typedef void (* bthf_client_in_band_ring_tone_callback) (bthf_client_in_band_ring_state_t state); + +/** + * Callback for requested number from AG + */ +typedef void (* bthf_client_last_voice_tag_number_callback) (const char *number); + +/** + * Callback for sending ring indication to app + */ +typedef void (* bthf_client_ring_indication_callback) (void); + +/** + * Callback for sending cgmi indication to app + */ +typedef void (* bthf_client_cgmi_indication_callback) (const char *str); + +/** + * Callback for sending cgmm indication to app + */ +typedef void (* bthf_client_cgmm_indication_callback) (const char *str); + +/** BT-HF callback structure. */ +typedef struct { + /** set to sizeof(BtHfClientCallbacks) */ + size_t size; + bthf_client_connection_state_callback connection_state_cb; + bthf_client_audio_state_callback audio_state_cb; + bthf_client_vr_cmd_callback vr_cmd_cb; + bthf_client_network_state_callback network_state_cb; + bthf_client_network_roaming_callback network_roaming_cb; + bthf_client_network_signal_callback network_signal_cb; + bthf_client_battery_level_callback battery_level_cb; + bthf_client_current_operator_callback current_operator_cb; + bthf_client_call_callback call_cb; + bthf_client_callsetup_callback callsetup_cb; + bthf_client_callheld_callback callheld_cb; + bthf_client_resp_and_hold_callback resp_and_hold_cb; + bthf_client_clip_callback clip_cb; + bthf_client_call_waiting_callback call_waiting_cb; + bthf_client_current_calls current_calls_cb; + bthf_client_volume_change_callback volume_change_cb; + bthf_client_cmd_complete_callback cmd_complete_cb; + bthf_client_subscriber_info_callback subscriber_info_cb; + bthf_client_in_band_ring_tone_callback in_band_ring_tone_cb; + bthf_client_last_voice_tag_number_callback last_voice_tag_number_callback; + bthf_client_ring_indication_callback ring_indication_cb; + bthf_client_cgmi_indication_callback cgmi_cb; + bthf_client_cgmm_indication_callback cgmm_cb; +} bthf_client_callbacks_t; + +/** Represents the standard BT-HF interface. */ +typedef struct { + + /** set to sizeof(BtHfClientInterface) */ + size_t size; + /** + * Register the BtHf callbacks + */ + bt_status_t (*init)(bthf_client_callbacks_t* callbacks); + + /** connect to audio gateway */ + bt_status_t (*connect)(bt_bdaddr_t *bd_addr); + + /** disconnect from audio gateway */ + bt_status_t (*disconnect)(bt_bdaddr_t *bd_addr); + + /** create an audio connection */ + bt_status_t (*connect_audio)(bt_bdaddr_t *bd_addr); + + /** close the audio connection */ + bt_status_t (*disconnect_audio)(bt_bdaddr_t *bd_addr); + + /** start voice recognition */ + bt_status_t (*start_voice_recognition)(void); + + /** stop voice recognition */ + bt_status_t (*stop_voice_recognition)(void); + + /** volume control */ + bt_status_t (*volume_control) (bthf_client_volume_type_t type, int volume); + + /** place a call with number a number + * if number is NULL last called number is called (aka re-dial)*/ + bt_status_t (*dial) (const char *number); + + /** place a call with number specified by location (speed dial) */ + bt_status_t (*dial_memory) (int location); + + /** perform specified call related action + * idx is limited only for enhanced call control related action + */ + bt_status_t (*handle_call_action) (bthf_client_call_action_t action, int idx); + + /** query list of current calls */ + bt_status_t (*query_current_calls) (void); + + /** query name of current selected operator */ + bt_status_t (*query_current_operator_name) (void); + + /** Retrieve subscriber information */ + bt_status_t (*retrieve_subscriber_info) (void); + + /** Send DTMF code*/ + bt_status_t (*send_dtmf) (char code); + + /** Request a phone number from AG corresponding to last voice tag recorded */ + bt_status_t (*request_last_voice_tag_number) (void); + + /** Closes the interface. */ + void (*cleanup)(void); + + /** Send AT Command. */ + bt_status_t (*send_at_cmd) (int cmd, int val1, int val2, const char *arg); +} bthf_client_interface_t; + +__END_DECLS + +#endif /* ANDROID_INCLUDE_BT_HF_CLIENT_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/bt_hh.h b/phonelibs/android_hardware_libhardware/include/hardware/bt_hh.h new file mode 100644 index 0000000000..ece3c11428 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/bt_hh.h @@ -0,0 +1,191 @@ +/* + * 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_INCLUDE_BT_HH_H +#define ANDROID_INCLUDE_BT_HH_H + +#include + +__BEGIN_DECLS + +#define BTHH_MAX_DSC_LEN 884 + +/* HH connection states */ +typedef enum +{ + BTHH_CONN_STATE_CONNECTED = 0, + BTHH_CONN_STATE_CONNECTING, + BTHH_CONN_STATE_DISCONNECTED, + BTHH_CONN_STATE_DISCONNECTING, + BTHH_CONN_STATE_FAILED_MOUSE_FROM_HOST, + BTHH_CONN_STATE_FAILED_KBD_FROM_HOST, + BTHH_CONN_STATE_FAILED_TOO_MANY_DEVICES, + BTHH_CONN_STATE_FAILED_NO_BTHID_DRIVER, + BTHH_CONN_STATE_FAILED_GENERIC, + BTHH_CONN_STATE_UNKNOWN +} bthh_connection_state_t; + +typedef enum +{ + BTHH_OK = 0, + BTHH_HS_HID_NOT_READY, /* handshake error : device not ready */ + BTHH_HS_INVALID_RPT_ID, /* handshake error : invalid report ID */ + BTHH_HS_TRANS_NOT_SPT, /* handshake error : transaction not spt */ + BTHH_HS_INVALID_PARAM, /* handshake error : invalid paremter */ + BTHH_HS_ERROR, /* handshake error : unspecified HS error */ + BTHH_ERR, /* general BTA HH error */ + BTHH_ERR_SDP, /* SDP error */ + BTHH_ERR_PROTO, /* SET_Protocol error, + only used in BTA_HH_OPEN_EVT callback */ + BTHH_ERR_DB_FULL, /* device database full error, used */ + BTHH_ERR_TOD_UNSPT, /* type of device not supported */ + BTHH_ERR_NO_RES, /* out of system resources */ + BTHH_ERR_AUTH_FAILED, /* authentication fail */ + BTHH_ERR_HDL +}bthh_status_t; + +/* Protocol modes */ +typedef enum { + BTHH_REPORT_MODE = 0x00, + BTHH_BOOT_MODE = 0x01, + BTHH_UNSUPPORTED_MODE = 0xff +}bthh_protocol_mode_t; + +/* Report types */ +typedef enum { + BTHH_INPUT_REPORT = 1, + BTHH_OUTPUT_REPORT, + BTHH_FEATURE_REPORT +}bthh_report_type_t; + +typedef struct +{ + int attr_mask; + uint8_t sub_class; + uint8_t app_id; + int vendor_id; + int product_id; + int version; + uint8_t ctry_code; + int dl_len; + uint8_t dsc_list[BTHH_MAX_DSC_LEN]; +} bthh_hid_info_t; + +/** Callback for connection state change. + * state will have one of the values from bthh_connection_state_t + */ +typedef void (* bthh_connection_state_callback)(bt_bdaddr_t *bd_addr, bthh_connection_state_t state); + +/** Callback for vitual unplug api. + * the status of the vitual unplug + */ +typedef void (* bthh_virtual_unplug_callback)(bt_bdaddr_t *bd_addr, bthh_status_t hh_status); + +/** Callback for get hid info + * hid_info will contain attr_mask, sub_class, app_id, vendor_id, product_id, version, ctry_code, len + */ +typedef void (* bthh_hid_info_callback)(bt_bdaddr_t *bd_addr, bthh_hid_info_t hid_info); + +/** Callback for get protocol api. + * the protocol mode is one of the value from bthh_protocol_mode_t + */ +typedef void (* bthh_protocol_mode_callback)(bt_bdaddr_t *bd_addr, bthh_status_t hh_status, bthh_protocol_mode_t mode); + +/** Callback for get/set_idle_time api. + */ +typedef void (* bthh_idle_time_callback)(bt_bdaddr_t *bd_addr, bthh_status_t hh_status, int idle_rate); + + +/** Callback for get report api. + * if staus is ok rpt_data contains the report data + */ +typedef void (* bthh_get_report_callback)(bt_bdaddr_t *bd_addr, bthh_status_t hh_status, uint8_t* rpt_data, int rpt_size); + +/** Callback for set_report/set_protocol api and if error + * occurs for get_report/get_protocol api. + */ +typedef void (* bthh_handshake_callback)(bt_bdaddr_t *bd_addr, bthh_status_t hh_status); + + +/** BT-HH callback structure. */ +typedef struct { + /** set to sizeof(BtHfCallbacks) */ + size_t size; + bthh_connection_state_callback connection_state_cb; + bthh_hid_info_callback hid_info_cb; + bthh_protocol_mode_callback protocol_mode_cb; + bthh_idle_time_callback idle_time_cb; + bthh_get_report_callback get_report_cb; + bthh_virtual_unplug_callback virtual_unplug_cb; + bthh_handshake_callback handshake_cb; + +} bthh_callbacks_t; + + + +/** Represents the standard BT-HH interface. */ +typedef struct { + + /** set to sizeof(BtHhInterface) */ + size_t size; + + /** + * Register the BtHh callbacks + */ + bt_status_t (*init)( bthh_callbacks_t* callbacks ); + + /** connect to hid device */ + bt_status_t (*connect)( bt_bdaddr_t *bd_addr); + + /** dis-connect from hid device */ + bt_status_t (*disconnect)( bt_bdaddr_t *bd_addr ); + + /** Virtual UnPlug (VUP) the specified HID device */ + bt_status_t (*virtual_unplug)(bt_bdaddr_t *bd_addr); + + /** Set the HID device descriptor for the specified HID device. */ + bt_status_t (*set_info)(bt_bdaddr_t *bd_addr, bthh_hid_info_t hid_info ); + + /** Get the HID proto mode. */ + bt_status_t (*get_protocol) (bt_bdaddr_t *bd_addr, bthh_protocol_mode_t protocolMode); + + /** Set the HID proto mode. */ + bt_status_t (*set_protocol)(bt_bdaddr_t *bd_addr, bthh_protocol_mode_t protocolMode); + + /** Get the HID Idle Time */ + bt_status_t (*get_idle_time)(bt_bdaddr_t *bd_addr); + + /** Set the HID Idle Time */ + bt_status_t (*set_idle_time)(bt_bdaddr_t *bd_addr, uint8_t idleTime); + + /** Send a GET_REPORT to HID device. */ + bt_status_t (*get_report)(bt_bdaddr_t *bd_addr, bthh_report_type_t reportType, uint8_t reportId, int bufferSize); + + /** Send a SET_REPORT to HID device. */ + bt_status_t (*set_report)(bt_bdaddr_t *bd_addr, bthh_report_type_t reportType, char* report); + + /** Send data to HID device. */ + bt_status_t (*send_data)(bt_bdaddr_t *bd_addr, char* data); + + /** Closes the interface. */ + void (*cleanup)( void ); + +} bthh_interface_t; +__END_DECLS + +#endif /* ANDROID_INCLUDE_BT_HH_H */ + + diff --git a/phonelibs/android_hardware_libhardware/include/hardware/bt_hl.h b/phonelibs/android_hardware_libhardware/include/hardware/bt_hl.h new file mode 100644 index 0000000000..bd29e3abf5 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/bt_hl.h @@ -0,0 +1,123 @@ +/* + * 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_INCLUDE_BT_HL_H +#define ANDROID_INCLUDE_BT_HL_H + +__BEGIN_DECLS + +/* HL connection states */ + +typedef enum +{ + BTHL_MDEP_ROLE_SOURCE, + BTHL_MDEP_ROLE_SINK +} bthl_mdep_role_t; + +typedef enum { + BTHL_APP_REG_STATE_REG_SUCCESS, + BTHL_APP_REG_STATE_REG_FAILED, + BTHL_APP_REG_STATE_DEREG_SUCCESS, + BTHL_APP_REG_STATE_DEREG_FAILED +} bthl_app_reg_state_t; + +typedef enum +{ + BTHL_CHANNEL_TYPE_RELIABLE, + BTHL_CHANNEL_TYPE_STREAMING, + BTHL_CHANNEL_TYPE_ANY +} bthl_channel_type_t; + + +/* HL connection states */ +typedef enum { + BTHL_CONN_STATE_CONNECTING, + BTHL_CONN_STATE_CONNECTED, + BTHL_CONN_STATE_DISCONNECTING, + BTHL_CONN_STATE_DISCONNECTED, + BTHL_CONN_STATE_DESTROYED +} bthl_channel_state_t; + +typedef struct +{ + bthl_mdep_role_t mdep_role; + int data_type; + bthl_channel_type_t channel_type; + const char *mdep_description; /* MDEP description to be used in the SDP (optional); null terminated */ +} bthl_mdep_cfg_t; + +typedef struct +{ + const char *application_name; + const char *provider_name; /* provider name to be used in the SDP (optional); null terminated */ + const char *srv_name; /* service name to be used in the SDP (optional); null terminated*/ + const char *srv_desp; /* service description to be used in the SDP (optional); null terminated */ + int number_of_mdeps; + bthl_mdep_cfg_t *mdep_cfg; /* Dynamic array */ +} bthl_reg_param_t; + +/** Callback for application registration status. + * state will have one of the values from bthl_app_reg_state_t + */ +typedef void (* bthl_app_reg_state_callback)(int app_id, bthl_app_reg_state_t state); + +/** Callback for channel connection state change. + * state will have one of the values from + * bthl_connection_state_t and fd (file descriptor) + */ +typedef void (* bthl_channel_state_callback)(int app_id, bt_bdaddr_t *bd_addr, int mdep_cfg_index, int channel_id, bthl_channel_state_t state, int fd); + +/** BT-HL callback structure. */ +typedef struct { + /** set to sizeof(bthl_callbacks_t) */ + size_t size; + bthl_app_reg_state_callback app_reg_state_cb; + bthl_channel_state_callback channel_state_cb; +} bthl_callbacks_t; + + +/** Represents the standard BT-HL interface. */ +typedef struct { + + /** set to sizeof(bthl_interface_t) */ + size_t size; + + /** + * Register the Bthl callbacks + */ + bt_status_t (*init)( bthl_callbacks_t* callbacks ); + + /** Register HL application */ + bt_status_t (*register_application) ( bthl_reg_param_t *p_reg_param, int *app_id); + + /** Unregister HL application */ + bt_status_t (*unregister_application) (int app_id); + + /** connect channel */ + bt_status_t (*connect_channel)(int app_id, bt_bdaddr_t *bd_addr, int mdep_cfg_index, int *channel_id); + + /** destroy channel */ + bt_status_t (*destroy_channel)(int channel_id); + + /** Close the Bthl callback **/ + void (*cleanup)(void); + +} bthl_interface_t; +__END_DECLS + +#endif /* ANDROID_INCLUDE_BT_HL_H */ + + diff --git a/phonelibs/android_hardware_libhardware/include/hardware/bt_mce.h b/phonelibs/android_hardware_libhardware/include/hardware/bt_mce.h new file mode 100644 index 0000000000..5d159b336d --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/bt_mce.h @@ -0,0 +1,54 @@ +/* + * Copyright (C) 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_INCLUDE_BT_MCE_H +#define ANDROID_INCLUDE_BT_MCE_H + +__BEGIN_DECLS + +/** MAS instance description */ +typedef struct +{ + int id; + int scn; + int msg_types; + char *p_name; +} btmce_mas_instance_t; + +/** callback for get_remote_mas_instances */ +typedef void (*btmce_remote_mas_instances_callback)(bt_status_t status, bt_bdaddr_t *bd_addr, + int num_instances, btmce_mas_instance_t *instances); + +typedef struct { + /** set to sizeof(btmce_callbacks_t) */ + size_t size; + btmce_remote_mas_instances_callback remote_mas_instances_cb; +} btmce_callbacks_t; + +typedef struct { + /** set to size of this struct */ + size_t size; + + /** register BT MCE callbacks */ + bt_status_t (*init)(btmce_callbacks_t *callbacks); + + /** search for MAS instances on remote device */ + bt_status_t (*get_remote_mas_instances)(bt_bdaddr_t *bd_addr); +} btmce_interface_t; + +__END_DECLS + +#endif /* ANDROID_INCLUDE_BT_MCE_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/bt_pan.h b/phonelibs/android_hardware_libhardware/include/hardware/bt_pan.h new file mode 100644 index 0000000000..83e7949b21 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/bt_pan.h @@ -0,0 +1,87 @@ +/* + * 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_INCLUDE_BT_PAN_H +#define ANDROID_INCLUDE_BT_PAN_H + +__BEGIN_DECLS + +#define BTPAN_ROLE_NONE 0 +#define BTPAN_ROLE_PANNAP 1 +#define BTPAN_ROLE_PANU 2 + +typedef enum { + BTPAN_STATE_CONNECTED = 0, + BTPAN_STATE_CONNECTING = 1, + BTPAN_STATE_DISCONNECTED = 2, + BTPAN_STATE_DISCONNECTING = 3 +} btpan_connection_state_t; + +typedef enum { + BTPAN_STATE_ENABLED = 0, + BTPAN_STATE_DISABLED = 1 +} btpan_control_state_t; + +/** +* Callback for pan connection state +*/ +typedef void (*btpan_connection_state_callback)(btpan_connection_state_t state, bt_status_t error, + const bt_bdaddr_t *bd_addr, int local_role, int remote_role); +typedef void (*btpan_control_state_callback)(btpan_control_state_t state, int local_role, + bt_status_t error, const char* ifname); + +typedef struct { + size_t size; + btpan_control_state_callback control_state_cb; + btpan_connection_state_callback connection_state_cb; +} btpan_callbacks_t; +typedef struct { + /** set to size of this struct*/ + size_t size; + /** + * Initialize the pan interface and register the btpan callbacks + */ + bt_status_t (*init)(const btpan_callbacks_t* callbacks); + /* + * enable the pan service by specified role. The result state of + * enabl will be returned by btpan_control_state_callback. when pan-nap is enabled, + * the state of connecting panu device will be notified by btpan_connection_state_callback + */ + bt_status_t (*enable)(int local_role); + /* + * get current pan local role + */ + int (*get_local_role)(void); + /** + * start bluetooth pan connection to the remote device by specified pan role. The result state will be + * returned by btpan_connection_state_callback + */ + bt_status_t (*connect)(const bt_bdaddr_t *bd_addr, int local_role, int remote_role); + /** + * stop bluetooth pan connection. The result state will be returned by btpan_connection_state_callback + */ + bt_status_t (*disconnect)(const bt_bdaddr_t *bd_addr); + + /** + * Cleanup the pan interface + */ + void (*cleanup)(void); + +} btpan_interface_t; + +__END_DECLS + +#endif /* ANDROID_INCLUDE_BT_PAN_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/bt_rc.h b/phonelibs/android_hardware_libhardware/include/hardware/bt_rc.h new file mode 100644 index 0000000000..6e1109d381 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/bt_rc.h @@ -0,0 +1,527 @@ +/* + * Copyright (C) 2013-2014, The Linux Foundation. All rights reserved. + * Not a Contribution. + * + * 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_INCLUDE_BT_RC_H +#define ANDROID_INCLUDE_BT_RC_H + +__BEGIN_DECLS + +/* Macros */ +#define BTRC_MAX_ATTR_STR_LEN 255 +#define BTRC_UID_SIZE 8 +#define BTRC_MAX_APP_SETTINGS 8 +#define BTRC_MAX_FOLDER_DEPTH 4 +#define BTRC_MAX_APP_ATTR_SIZE 16 +#define BTRC_MAX_ELEM_ATTR_SIZE 7 +#define BTRC_CHARSET_UTF8 0x006A + +typedef uint8_t btrc_uid_t[BTRC_UID_SIZE]; + +typedef enum { + BTRC_FEAT_NONE = 0x00, /* AVRCP 1.0 */ + BTRC_FEAT_METADATA = 0x01, /* AVRCP 1.3 */ + BTRC_FEAT_ABSOLUTE_VOLUME = 0x02, /* Supports TG role and volume sync */ + BTRC_FEAT_BROWSE = 0x04, /* AVRCP 1.4 and up, with Browsing support */ +} btrc_remote_features_t; + +typedef enum { + BTRC_PLAYSTATE_STOPPED = 0x00, /* Stopped */ + BTRC_PLAYSTATE_PLAYING = 0x01, /* Playing */ + BTRC_PLAYSTATE_PAUSED = 0x02, /* Paused */ + BTRC_PLAYSTATE_FWD_SEEK = 0x03, /* Fwd Seek*/ + BTRC_PLAYSTATE_REV_SEEK = 0x04, /* Rev Seek*/ + BTRC_PLAYSTATE_ERROR = 0xFF, /* Error */ +} btrc_play_status_t; + +typedef enum { + BTRC_EVT_PLAY_STATUS_CHANGED = 0x01, + BTRC_EVT_TRACK_CHANGE = 0x02, + BTRC_EVT_TRACK_REACHED_END = 0x03, + BTRC_EVT_TRACK_REACHED_START = 0x04, + BTRC_EVT_PLAY_POS_CHANGED = 0x05, + BTRC_EVT_APP_SETTINGS_CHANGED = 0x08, + BTRC_EVT_NOW_PLAYING_CONTENT_CHANGED = 0x09, + BTRC_EVT_AVAILABLE_PLAYERS_CHANGED = 0x0a, + BTRC_EVT_ADDRESSED_PLAYER_CHANGED = 0x0b, +} btrc_event_id_t; + +//used for Scope +typedef enum { + BTRC_EVT_MEDIA_PLAYLIST = 0, + BTRC_EVT_MEDIA_VIRTUALFILESYST = 1, + BTRC_EVT_SEARCH = 2, + BTRC_EVT_NOWPLAYING = 3, + BTRC_EVT_MAX_BROWSE = 4, +} btrc_browse_folderitem_t; + +typedef enum { + BTRC_NOTIFICATION_TYPE_INTERIM = 0, + BTRC_NOTIFICATION_TYPE_CHANGED = 1, + BTRC_NOTIFICATION_TYPE_REJECT = 2, +} btrc_notification_type_t; + +typedef enum { + BTRC_PLAYER_ATTR_EQUALIZER = 0x01, + BTRC_PLAYER_ATTR_REPEAT = 0x02, + BTRC_PLAYER_ATTR_SHUFFLE = 0x03, + BTRC_PLAYER_ATTR_SCAN = 0x04, +} btrc_player_attr_t; + +typedef enum { + BTRC_MEDIA_ATTR_TITLE = 0x01, + BTRC_MEDIA_ATTR_ARTIST = 0x02, + BTRC_MEDIA_ATTR_ALBUM = 0x03, + BTRC_MEDIA_ATTR_TRACK_NUM = 0x04, + BTRC_MEDIA_ATTR_NUM_TRACKS = 0x05, + BTRC_MEDIA_ATTR_GENRE = 0x06, + BTRC_MEDIA_ATTR_PLAYING_TIME = 0x07, +} btrc_media_attr_t; + +typedef enum { + BTRC_PLAYER_VAL_OFF_REPEAT = 0x01, + BTRC_PLAYER_VAL_SINGLE_REPEAT = 0x02, + BTRC_PLAYER_VAL_ALL_REPEAT = 0x03, + BTRC_PLAYER_VAL_GROUP_REPEAT = 0x04 +} btrc_player_repeat_val_t; + +typedef enum { + BTRC_PLAYER_VAL_OFF_SHUFFLE = 0x01, + BTRC_PLAYER_VAL_ALL_SHUFFLE = 0x02, + BTRC_PLAYER_VAL_GROUP_SHUFFLE = 0x03 +} btrc_player_shuffle_val_t; + +typedef enum { + BTRC_STS_BAD_CMD = 0x00, /* Invalid command */ + BTRC_STS_BAD_PARAM = 0x01, /* Invalid parameter */ + BTRC_STS_NOT_FOUND = 0x02, /* Specified parameter is wrong or not found */ + BTRC_STS_INTERNAL_ERR = 0x03, /* Internal Error */ + BTRC_STS_NO_ERROR = 0x04 /* Operation Success */ +} btrc_status_t; + +typedef enum { + BTRC_TYPE_MEDIA_PLAYER = 0x01, + BTRC_TYPE_FOLDER = 0x02, + BTRC_TYPE_MEDIA_ELEMENT = 0x03 +} btrc_folder_list_item_type_t; + +typedef struct { + uint8_t num_attr; + uint8_t attr_ids[BTRC_MAX_APP_SETTINGS]; + uint8_t attr_values[BTRC_MAX_APP_SETTINGS]; +} btrc_player_settings_t; + +typedef struct { + uint32_t start_item; + uint32_t end_item; + uint32_t size; + uint32_t attrs[BTRC_MAX_ELEM_ATTR_SIZE]; + uint8_t attr_count; +}btrc_getfolderitem_t; + +typedef union +{ + btrc_play_status_t play_status; + btrc_uid_t track; /* queue position in NowPlaying */ + uint32_t song_pos; + btrc_player_settings_t player_setting; + uint16_t player_id; +} btrc_register_notification_t; + +typedef struct { + uint8_t id; /* can be attr_id or value_id */ + uint8_t text[BTRC_MAX_ATTR_STR_LEN]; +} btrc_player_setting_text_t; + +typedef struct { + uint32_t attr_id; + uint8_t text[BTRC_MAX_ATTR_STR_LEN]; +} btrc_element_attr_val_t; + +/** Callback for the controller's supported feautres */ +typedef void (* btrc_remote_features_callback)(bt_bdaddr_t *bd_addr, + btrc_remote_features_t features); +#define BTRC_FEATURE_MASK_SIZE 16 + +typedef uint8_t btrc_feature_mask_t[BTRC_FEATURE_MASK_SIZE]; + +typedef struct { + uint16_t charset_id; + uint16_t str_len; + uint8_t *p_str; +} btrc_player_full_name_t; + +typedef struct +{ + uint32_t sub_type; + uint16_t player_id; + uint8_t major_type; + uint8_t play_status; + btrc_feature_mask_t features; /* Supported feature bit mask*/ + btrc_player_full_name_t name; /* The player name, name length and character set id.*/ +} btrc_folder_list_item_player_t; + +typedef struct +{ + uint64_t uid; + uint8_t type; + uint8_t playable; + btrc_player_full_name_t name; +} btrc_folder_list_item_folder_t; + +typedef struct +{ + uint32_t attr_id; + btrc_player_full_name_t name; +} btrc_attr_entry_t; + +typedef struct +{ + uint64_t uid; + uint8_t type; + uint8_t attr_count; + btrc_player_full_name_t name; + btrc_attr_entry_t* p_attr_list; +} btrc_folder_list_item_media_t; + +typedef struct { + uint16_t str_len; + uint8_t *p_str; +} btrc_name_t; + +/* SetBrowsedPlayer */ +typedef struct +{ + uint32_t num_items; + uint16_t uid_counter; + uint16_t charset_id; + uint8_t status; + uint8_t folder_depth; + btrc_name_t *p_folders; +} btrc_set_browsed_player_rsp_t; + +typedef struct +{ + uint8_t item_type; + union + { + btrc_folder_list_item_player_t player; + btrc_folder_list_item_folder_t folder; + btrc_folder_list_item_media_t media; + } u; +} btrc_folder_list_item_t; + +/* GetFolderItems */ +typedef struct +{ + uint16_t uid_counter; + uint16_t item_count; + uint8_t status; + btrc_folder_list_item_t *p_item_list; +} btrc_folder_list_entries_t; + +/** Callback for play status request */ +typedef void (* btrc_get_play_status_callback)(bt_bdaddr_t *bd_addr); + +/** Callback for list player application attributes (Shuffle, Repeat,...) */ +typedef void (* btrc_list_player_app_attr_callback)(bt_bdaddr_t *bd_addr); + +/** Callback for list player application attributes (Shuffle, Repeat,...) */ +typedef void (* btrc_list_player_app_values_callback)(btrc_player_attr_t attr_id, + bt_bdaddr_t *bd_addr); + +/** Callback for getting the current player application settings value +** num_attr: specifies the number of attribute ids contained in p_attrs +*/ +typedef void (* btrc_get_player_app_value_callback) (uint8_t num_attr, btrc_player_attr_t *p_attrs, + bt_bdaddr_t *bd_addr); + +/** Callback for getting the player application settings attributes' text +** num_attr: specifies the number of attribute ids contained in p_attrs +*/ +typedef void (* btrc_get_player_app_attrs_text_callback) (uint8_t num_attr, + btrc_player_attr_t *p_attrs, bt_bdaddr_t *bd_addr); + +/** Callback for getting the player application settings values' text +** num_attr: specifies the number of value ids contained in p_vals +*/ +typedef void (* btrc_get_player_app_values_text_callback) (uint8_t attr_id, + uint8_t num_val, uint8_t *p_vals, bt_bdaddr_t *bd_addr); + +/** Callback for setting the player application settings values */ +typedef void (* btrc_set_player_app_value_callback) (btrc_player_settings_t *p_vals, + bt_bdaddr_t *bd_addr); + +/** Callback to fetch the get element attributes of the current song +** num_attr: specifies the number of attributes requested in p_attrs +*/ +typedef void (* btrc_get_element_attr_callback) (uint8_t num_attr, btrc_media_attr_t *p_attrs, + bt_bdaddr_t *bd_addr); + +/** Callback for register notification (Play state change/track change/...) +** param: Is only valid if event_id is BTRC_EVT_PLAY_POS_CHANGED +*/ +typedef void (* btrc_register_notification_callback) (btrc_event_id_t event_id, uint32_t param, + bt_bdaddr_t *bd_addr); + +/* AVRCP 1.4 Enhancements */ +/** Callback for volume change on CT +** volume: Current volume setting on the CT (0-127) +*/ +typedef void (* btrc_volume_change_callback) (uint8_t volume, uint8_t ctype, bt_bdaddr_t *bd_addr); + +/** Callback for passthrough commands */ +typedef void (* btrc_passthrough_cmd_callback) (int id, int key_state, bt_bdaddr_t *bd_addr); + +/** BT-RC Target callback structure. */ + +typedef void (* btrc_get_folder_items_callback) (btrc_browse_folderitem_t id, + btrc_getfolderitem_t *param, bt_bdaddr_t *bd_addr); + +typedef void (* btrc_set_addressed_player_callback) (uint32_t player_id, bt_bdaddr_t *bd_addr); + +typedef void (* btrc_set_browsed_player_callback) (uint32_t player_id, bt_bdaddr_t *bd_addr); + +typedef void (* btrc_change_path_callback) (uint8_t direction, uint64_t uid, bt_bdaddr_t *bd_addr); + +typedef void (* btrc_play_item_callback) (uint8_t scope, uint64_t uid, bt_bdaddr_t *bd_addr); + +typedef void (* btrc_get_item_attr_callback) (uint8_t scope, uint64_t uid, + uint8_t num_attr, btrc_media_attr_t *p_attrs, bt_bdaddr_t *bd_addr); + +typedef void (* btrc_connection_state_callback) (bool state, bt_bdaddr_t *bd_addr); + +typedef struct { + /** set to sizeof(BtRcCallbacks) */ + size_t size; + btrc_remote_features_callback remote_features_cb; + btrc_get_play_status_callback get_play_status_cb; + btrc_list_player_app_attr_callback list_player_app_attr_cb; + btrc_list_player_app_values_callback list_player_app_values_cb; + btrc_get_player_app_value_callback get_player_app_value_cb; + btrc_get_player_app_attrs_text_callback get_player_app_attrs_text_cb; + btrc_get_player_app_values_text_callback get_player_app_values_text_cb; + btrc_set_player_app_value_callback set_player_app_value_cb; + btrc_get_element_attr_callback get_element_attr_cb; + btrc_register_notification_callback register_notification_cb; + btrc_volume_change_callback volume_change_cb; + btrc_passthrough_cmd_callback passthrough_cmd_cb; + btrc_get_folder_items_callback get_folderitems_cb; + btrc_set_addressed_player_callback set_addrplayer_cb; + btrc_set_browsed_player_callback set_browsed_player_cb; + btrc_change_path_callback change_path_cb; + btrc_play_item_callback play_item_cb; + btrc_get_item_attr_callback get_item_attr_cb; + btrc_connection_state_callback connection_state_cb; +} btrc_callbacks_t; + +/** Represents the standard BT-RC AVRCP Target interface. */ +typedef struct { + + /** set to sizeof(BtRcInterface) */ + size_t size; + /** + * Register the BtRc callbacks + */ + bt_status_t (*init)( btrc_callbacks_t* callbacks , int max_avrcp_connections); + + /** Respose to GetPlayStatus request. Contains the current + ** 1. Play status + ** 2. Song duration/length + ** 3. Song position + */ + bt_status_t (*get_play_status_rsp)( btrc_play_status_t play_status, uint32_t song_len, + uint32_t song_pos, bt_bdaddr_t *bd_addr); + + /** Lists the support player application attributes (Shuffle/Repeat/...) + ** num_attr: Specifies the number of attributes contained in the pointer p_attrs + */ + bt_status_t (*list_player_app_attr_rsp)( uint8_t num_attr, btrc_player_attr_t *p_attrs, + bt_bdaddr_t *bd_addr); + + /** Lists the support player application attributes (Shuffle Off/On/Group) + ** num_val: Specifies the number of values contained in the pointer p_vals + */ + bt_status_t (*list_player_app_value_rsp)( uint8_t num_val, uint8_t *p_vals, + bt_bdaddr_t *bd_addr); + + /** Returns the current application attribute values for each of the specified attr_id */ + bt_status_t (*get_player_app_value_rsp)( btrc_player_settings_t *p_vals, + bt_bdaddr_t *bd_addr); + + /** Returns the application attributes text ("Shuffle"/"Repeat"/...) + ** num_attr: Specifies the number of attributes' text contained in the pointer p_attrs + */ + bt_status_t (*get_player_app_attr_text_rsp)( int num_attr, btrc_player_setting_text_t *p_attrs, + bt_bdaddr_t *bd_addr); + + /** Returns the application attributes text ("Shuffle"/"Repeat"/...) + ** num_attr: Specifies the number of attribute values' text contained in the pointer p_vals + */ + bt_status_t (*get_player_app_value_text_rsp)( int num_val, btrc_player_setting_text_t *p_vals, + bt_bdaddr_t *bd_addr); + + /** Returns the current songs' element attributes text ("Title"/"Album"/"Artist") + ** num_attr: Specifies the number of attributes' text contained in the pointer p_attrs + */ + bt_status_t (*get_element_attr_rsp)( uint8_t num_attr, btrc_element_attr_val_t *p_attrs, + bt_bdaddr_t *bd_addr); + + /** Response to set player attribute request ("Shuffle"/"Repeat") + ** rsp_status: Status of setting the player attributes for the current media player + */ + bt_status_t (*set_player_app_value_rsp)(btrc_status_t rsp_status, bt_bdaddr_t *bd_addr); + + /* Response to the register notification request (Play state change/track change/...). + ** event_id: Refers to the event_id this notification change corresponds too + ** type: Response type - interim/changed + ** p_params: Based on the event_id, this parameter should be populated + */ + bt_status_t (*register_notification_rsp)(btrc_event_id_t event_id, + btrc_notification_type_t type, + btrc_register_notification_t *p_param, + bt_bdaddr_t *bd_addr); + + /* AVRCP 1.4 enhancements */ + + /**Send current volume setting to remote side. Support limited to SetAbsoluteVolume + ** This can be enhanced to support Relative Volume (AVRCP 1.0). + ** With RelateVolume, we will send VOLUME_UP/VOLUME_DOWN opposed to absolute volume level + ** volume: Should be in the range 0-127. bit7 is reseved and cannot be set + */ + bt_status_t (*set_volume)(uint8_t volume, bt_bdaddr_t *bd_addr); + bt_status_t (*get_folder_items_rsp) (btrc_folder_list_entries_t *p_param, bt_bdaddr_t *bd_addr); + + bt_status_t (*set_addressed_player_rsp) (btrc_status_t status_code, bt_bdaddr_t *bd_addr); + bt_status_t (*set_browsed_player_rsp) (btrc_set_browsed_player_rsp_t *p_param, + bt_bdaddr_t *bd_addr); + bt_status_t (*change_path_rsp) (uint8_t status_code, uint32_t item_count, + bt_bdaddr_t *bd_addr); + bt_status_t (*play_item_rsp) (uint8_t status_code, bt_bdaddr_t *bd_addr); + bt_status_t (*get_item_attr_rsp)( uint8_t num_attr, btrc_element_attr_val_t *p_attrs, + bt_bdaddr_t *bd_addr); + bt_status_t (*is_device_active_in_handoff) (bt_bdaddr_t *bd_addr); + + /** Closes the interface. */ + void (*cleanup)( void ); +} btrc_interface_t; + + +typedef void (* btrc_passthrough_rsp_callback) (int id, int key_state); + +typedef void (* btrc_connection_state_callback) (bool state, bt_bdaddr_t *bd_addr); + +typedef void (* btrc_ctrl_getrcfeatures_callback) (bt_bdaddr_t *bd_addr, int features); + +typedef void (* btrc_ctrl_getcapability_rsp_callback) (bt_bdaddr_t *bd_addr, int cap_id, + uint32_t* supported_values, int num_supported, uint8_t rsp_type); + +typedef void (* btrc_ctrl_listplayerappsettingattrib_rsp_callback) (bt_bdaddr_t *bd_addr, + uint8_t* supported_attribs, int num_attrib, uint8_t rsp_type); + +typedef void (* btrc_ctrl_listplayerappsettingvalue_rsp_callback) (bt_bdaddr_t *bd_addr, + uint8_t* supported_val, uint8_t num_supported, uint8_t rsp_type); + +typedef void (* btrc_ctrl_currentplayerappsetting_rsp_callback) (bt_bdaddr_t *bd_addr,uint8_t* supported_ids, + uint8_t* supported_val, uint8_t num_attrib, uint8_t rsp_type); + +typedef void (* btrc_ctrl_setplayerapplicationsetting_rsp_callback) (bt_bdaddr_t *bd_addr,uint8_t rsp_type); + +typedef void (* btrc_ctrl_notification_rsp_callback) (bt_bdaddr_t *bd_addr, uint8_t rsp_type, + int rsp_len, uint8_t* notification_rsp); + +typedef void (* btrc_ctrl_getelementattrib_rsp_callback) (bt_bdaddr_t *bd_addr, uint8_t num_attributes, + int rsp_len, uint8_t* attrib_rsp, uint8_t rsp_type); + +typedef void (* btrc_ctrl_getplaystatus_rsp_callback) (bt_bdaddr_t *bd_addr, int param_len, uint8_t* play_status_rsp + ,uint8_t rsp_type); + +typedef void (* btrc_ctrl_setabsvol_cmd_callback) (bt_bdaddr_t *bd_addr, uint8_t abs_vol); + +typedef void (* btrc_ctrl_registernotification_abs_vol_callback) (bt_bdaddr_t *bd_addr); +/** BT-RC Controller callback structure. */ +typedef struct { + /** set to sizeof(BtRcCallbacks) */ + size_t size; + btrc_passthrough_rsp_callback passthrough_rsp_cb; + btrc_connection_state_callback connection_state_cb; + btrc_ctrl_getrcfeatures_callback getrcfeatures_cb; + btrc_ctrl_getcapability_rsp_callback getcap_rsp_cb; + btrc_ctrl_listplayerappsettingattrib_rsp_callback listplayerappsettingattrib_rsp_cb; + btrc_ctrl_listplayerappsettingvalue_rsp_callback listplayerappsettingvalue_rsp_cb; + btrc_ctrl_currentplayerappsetting_rsp_callback currentplayerappsetting_rsp_cb; + btrc_ctrl_setplayerapplicationsetting_rsp_callback setplayerappsetting_rsp_cb; + btrc_ctrl_notification_rsp_callback notification_rsp_cb; + btrc_ctrl_getelementattrib_rsp_callback getelementattrib_rsp_cb; + btrc_ctrl_getplaystatus_rsp_callback getplaystatus_rsp_cb; + btrc_ctrl_setabsvol_cmd_callback setabsvol_cmd_cb; + btrc_ctrl_registernotification_abs_vol_callback registernotification_absvol_cb; +} btrc_ctrl_callbacks_t; + +/** Represents the standard BT-RC AVRCP Controller interface. */ +typedef struct { + + /** set to sizeof(BtRcInterface) */ + size_t size; + /** + * Register the BtRc callbacks + */ + bt_status_t (*init)( btrc_ctrl_callbacks_t* callbacks ); + + /** send pass through command to target */ + bt_status_t (*send_pass_through_cmd) ( bt_bdaddr_t *bd_addr, uint8_t key_code, + uint8_t key_state ); + + /** send get_cap command to target */ + bt_status_t (*getcapabilities_cmd) (uint8_t cap_id); + + /** send command to get supported player application settings to target */ + bt_status_t (*list_player_app_setting_attrib_cmd) (void); + + /** send command to get supported values of player application settings for a + * particular attribute to target */ + bt_status_t (*list_player_app_setting_value_cmd) (uint8_t attrib_id); + + /** send command to get current player attributes to target */ + bt_status_t (*get_player_app_setting_cmd) (uint8_t num_attrib, uint8_t* attrib_ids); + + /** send command to set player applicaiton setting attributes to target */ + bt_status_t (*set_player_app_setting_cmd) (uint8_t num_attrib, uint8_t* attrib_ids, uint8_t* attrib_vals); + + /** send command to register for supported notificaiton events to target */ + bt_status_t (*register_notification_cmd) (uint8_t event_id, uint32_t event_value); + + /** send command to get element attribute to target */ + bt_status_t (*get_element_attribute_cmd) (uint8_t num_attribute, uint32_t attribute_id); + + /** send command to get play status to target */ + bt_status_t (*get_play_status_cmd) (void); + + /** send rsp to set_abs_vol received from target */ + bt_status_t (*send_abs_vol_rsp) (uint8_t abs_vol); + + /** send notificaiton rsp for abs vol to target */ + bt_status_t (*send_register_abs_vol_rsp) (uint8_t rsp_type, uint8_t abs_vol); + + /** Closes the interface. */ + void (*cleanup)( void ); +} btrc_ctrl_interface_t; + +__END_DECLS + +#endif /* ANDROID_INCLUDE_BT_RC_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/bt_sdp.h b/phonelibs/android_hardware_libhardware/include/hardware/bt_sdp.h new file mode 100644 index 0000000000..8f39bc5bdc --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/bt_sdp.h @@ -0,0 +1,150 @@ +/* + * 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. + */ + +#pragma once + +#include "bluetooth.h" + +#define SDP_OPP_SUPPORTED_FORMATS_MAX_LENGTH 15 + +__BEGIN_DECLS + +/** + * These events are handled by the state machine + */ +typedef enum { + SDP_TYPE_RAW, // Used to carry raw SDP search data for unknown UUIDs + SDP_TYPE_MAP_MAS, // Message Access Profile - Server + SDP_TYPE_MAP_MNS, // Message Access Profile - Client (Notification Server) + SDP_TYPE_PBAP_PSE, // Phone Book Profile - Server + SDP_TYPE_PBAP_PCE, // Phone Book Profile - Client + SDP_TYPE_OPP_SERVER, // Object Push Profile + SDP_TYPE_SAP_SERVER // SIM Access Profile +} bluetooth_sdp_types; + +typedef struct _bluetooth_sdp_hdr { + bluetooth_sdp_types type; + bt_uuid_t uuid; + uint32_t service_name_length; + char *service_name; + int32_t rfcomm_channel_number; + int32_t l2cap_psm; + int32_t profile_version; +} bluetooth_sdp_hdr; + +/** + * Some signals need additional pointers, hence we introduce a + * generic way to handle these pointers. + */ +typedef struct _bluetooth_sdp_hdr_overlay { + bluetooth_sdp_types type; + bt_uuid_t uuid; + uint32_t service_name_length; + char *service_name; + int32_t rfcomm_channel_number; + int32_t l2cap_psm; + int32_t profile_version; + + // User pointers, only used for some signals - see bluetooth_sdp_ops_record + int user1_ptr_len; + uint8_t *user1_ptr; + int user2_ptr_len; + uint8_t *user2_ptr; +} bluetooth_sdp_hdr_overlay; + +typedef struct _bluetooth_sdp_mas_record { + bluetooth_sdp_hdr_overlay hdr; + uint32_t mas_instance_id; + uint32_t supported_features; + uint32_t supported_message_types; +} bluetooth_sdp_mas_record; + +typedef struct _bluetooth_sdp_mns_record { + bluetooth_sdp_hdr_overlay hdr; + uint32_t supported_features; +} bluetooth_sdp_mns_record; + +typedef struct _bluetooth_sdp_pse_record { + bluetooth_sdp_hdr_overlay hdr; + uint32_t supported_features; + uint32_t supported_repositories; +} bluetooth_sdp_pse_record; + +typedef struct _bluetooth_sdp_pce_record { + bluetooth_sdp_hdr_overlay hdr; +} bluetooth_sdp_pce_record; + +typedef struct _bluetooth_sdp_ops_record { + bluetooth_sdp_hdr_overlay hdr; + int supported_formats_list_len; + uint8_t supported_formats_list[SDP_OPP_SUPPORTED_FORMATS_MAX_LENGTH]; +} bluetooth_sdp_ops_record; + +typedef struct _bluetooth_sdp_sap_record { + bluetooth_sdp_hdr_overlay hdr; +} bluetooth_sdp_sap_record; + +typedef union { + bluetooth_sdp_hdr_overlay hdr; + bluetooth_sdp_mas_record mas; + bluetooth_sdp_mns_record mns; + bluetooth_sdp_pse_record pse; + bluetooth_sdp_pce_record pce; + bluetooth_sdp_ops_record ops; + bluetooth_sdp_sap_record sap; +} bluetooth_sdp_record; + + +/** Callback for SDP search */ +typedef void (*btsdp_search_callback)(bt_status_t status, bt_bdaddr_t *bd_addr, uint8_t* uuid, int num_records, bluetooth_sdp_record *records); + +typedef struct { + /** Set to sizeof(btsdp_callbacks_t) */ + size_t size; + btsdp_search_callback sdp_search_cb; +} btsdp_callbacks_t; + +typedef struct { + /** Set to size of this struct */ + size_t size; + + /** Register BT SDP search callbacks */ + bt_status_t (*init)(btsdp_callbacks_t *callbacks); + + /** Unregister BT SDP */ + bt_status_t (*deinit)(); + + /** Search for SDP records with specific uuid on remote device */ + bt_status_t (*sdp_search)(bt_bdaddr_t *bd_addr, const uint8_t* uuid); + + /** + * Use listen in the socket interface to create rfcomm and/or l2cap PSM channels, + * (without UUID and service_name and set the BTSOCK_FLAG_NO_SDP flag in flags). + * Then use createSdpRecord to create the SDP record associated with the rfcomm/l2cap channels. + * + * Returns a handle to the SDP record, which can be parsed to remove_sdp_record. + * + * record (in) The SDP record to create + * record_handle (out)The corresponding record handle will be written to this pointer. + */ + bt_status_t (*create_sdp_record)(bluetooth_sdp_record *record, int* record_handle); + + /** Remove a SDP record created by createSdpRecord */ + bt_status_t (*remove_sdp_record)(int sdp_handle); +} btsdp_interface_t; + +__END_DECLS + diff --git a/phonelibs/android_hardware_libhardware/include/hardware/bt_sock.h b/phonelibs/android_hardware_libhardware/include/hardware/bt_sock.h new file mode 100644 index 0000000000..9dd83bb1c9 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/bt_sock.h @@ -0,0 +1,91 @@ +/* + * 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. + */ + +#pragma once + +__BEGIN_DECLS + +#define BTSOCK_FLAG_ENCRYPT 1 +#define BTSOCK_FLAG_AUTH (1 << 1) +#define BTSOCK_FLAG_NO_SDP (1 << 2) +#define BTSOCK_FLAG_AUTH_MITM (1 << 3) +#define BTSOCK_FLAG_AUTH_16_DIGIT (1 << 4) + +typedef enum { + BTSOCK_RFCOMM = 1, + BTSOCK_SCO = 2, + BTSOCK_L2CAP = 3 +} btsock_type_t; + +typedef enum { + BTSOCK_OPT_GET_MODEM_BITS = 1, + BTSOCK_OPT_SET_MODEM_BITS = 2, + BTSOCK_OPT_CLR_MODEM_BITS = 3, +} btsock_option_type_t; + +/** Represents the standard BT SOCKET interface. */ +typedef struct { + short size; + bt_bdaddr_t bd_addr; + int channel; + int status; + + // The writer must make writes using a buffer of this maximum size + // to avoid loosing data. (L2CAP only) + unsigned short max_tx_packet_size; + + // The reader must read using a buffer of at least this size to avoid + // loosing data. (L2CAP only) + unsigned short max_rx_packet_size; +} __attribute__((packed)) sock_connect_signal_t; + +typedef struct { + /** set to size of this struct*/ + size_t size; + + /** + * Listen to a RFCOMM UUID or channel. It returns the socket fd from which + * btsock_connect_signal can be read out when a remote device connected. + * If neither a UUID nor a channel is provided, a channel will be allocated + * and a service record can be created providing the channel number to + * create_sdp_record(...) in bt_sdp. + */ + bt_status_t (*listen)(btsock_type_t type, const char* service_name, + const uint8_t* service_uuid, int channel, int* sock_fd, int flags); + + /** + * Connect to a RFCOMM UUID channel of remote device, It returns the socket fd from which + * the btsock_connect_signal and a new socket fd to be accepted can be read out when connected + */ + bt_status_t (*connect)(const bt_bdaddr_t *bd_addr, btsock_type_t type, const uint8_t* uuid, + int channel, int* sock_fd, int flags); + + /* + * get socket option of rfcomm channel socket. + */ + bt_status_t (*get_sock_opt)(btsock_type_t type, int channel, btsock_option_type_t option_name, + void *option_value, int *option_len); + /* + + * set socket option of rfcomm channel socket. + */ + bt_status_t (*set_sock_opt)(btsock_type_t type, int channel, btsock_option_type_t option_name, + void *option_value, int option_len); + +} btsock_interface_t; + +__END_DECLS + diff --git a/phonelibs/android_hardware_libhardware/include/hardware/camera.h b/phonelibs/android_hardware_libhardware/include/hardware/camera.h new file mode 100644 index 0000000000..b1f18fffce --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/camera.h @@ -0,0 +1,298 @@ +/* + * Copyright (C) 2010-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_INCLUDE_CAMERA_H +#define ANDROID_INCLUDE_CAMERA_H + +#include "camera_common.h" + +/** + * Camera device HAL, initial version [ CAMERA_DEVICE_API_VERSION_1_0 ] + * + * DEPRECATED. New devices should use Camera HAL v3.2 or newer. + * + * Supports the android.hardware.Camera API, and the android.hardware.camera2 + * API in legacy mode only. + * + * Camera devices that support this version of the HAL must return a value in + * the range HARDWARE_DEVICE_API_VERSION(0,0)-(1,FF) in + * camera_device_t.common.version. CAMERA_DEVICE_API_VERSION_1_0 is the + * recommended value. + * + * Camera modules that implement version 2.0 or higher of camera_module_t must + * also return the value of camera_device_t.common.version in + * camera_info_t.device_version. + * + * See camera_common.h for more details. + */ + +__BEGIN_DECLS + +struct camera_memory; +typedef void (*camera_release_memory)(struct camera_memory *mem); + +typedef struct camera_memory { + void *data; + size_t size; + void *handle; + camera_release_memory release; +} camera_memory_t; + +typedef camera_memory_t* (*camera_request_memory)(int fd, size_t buf_size, unsigned int num_bufs, + void *user); + +typedef void (*camera_notify_callback)(int32_t msg_type, + int32_t ext1, + int32_t ext2, + void *user); + +typedef void (*camera_data_callback)(int32_t msg_type, + const camera_memory_t *data, unsigned int index, + camera_frame_metadata_t *metadata, void *user); + +typedef void (*camera_data_timestamp_callback)(int64_t timestamp, + int32_t msg_type, + const camera_memory_t *data, unsigned int index, + void *user); + +#define HAL_CAMERA_PREVIEW_WINDOW_TAG 0xcafed00d + +typedef struct preview_stream_ops { + int (*dequeue_buffer)(struct preview_stream_ops* w, + buffer_handle_t** buffer, int *stride); + int (*enqueue_buffer)(struct preview_stream_ops* w, + buffer_handle_t* buffer); + int (*cancel_buffer)(struct preview_stream_ops* w, + buffer_handle_t* buffer); + int (*set_buffer_count)(struct preview_stream_ops* w, int count); + int (*set_buffers_geometry)(struct preview_stream_ops* pw, + int w, int h, int format); + int (*set_crop)(struct preview_stream_ops *w, + int left, int top, int right, int bottom); + int (*set_usage)(struct preview_stream_ops* w, int usage); + int (*set_swap_interval)(struct preview_stream_ops *w, int interval); + int (*get_min_undequeued_buffer_count)(const struct preview_stream_ops *w, + int *count); + int (*lock_buffer)(struct preview_stream_ops* w, + buffer_handle_t* buffer); + // Timestamps are measured in nanoseconds, and must be comparable + // and monotonically increasing between two frames in the same + // preview stream. They do not need to be comparable between + // consecutive or parallel preview streams, cameras, or app runs. + int (*set_timestamp)(struct preview_stream_ops *w, int64_t timestamp); +} preview_stream_ops_t; + +struct camera_device; +typedef struct camera_device_ops { + /** Set the ANativeWindow to which preview frames are sent */ + int (*set_preview_window)(struct camera_device *, + struct preview_stream_ops *window); + + /** Set the notification and data callbacks */ + void (*set_callbacks)(struct camera_device *, + camera_notify_callback notify_cb, + camera_data_callback data_cb, + camera_data_timestamp_callback data_cb_timestamp, + camera_request_memory get_memory, + void *user); + + /** + * The following three functions all take a msg_type, which is a bitmask of + * the messages defined in include/ui/Camera.h + */ + + /** + * Enable a message, or set of messages. + */ + void (*enable_msg_type)(struct camera_device *, int32_t msg_type); + + /** + * Disable a message, or a set of messages. + * + * Once received a call to disableMsgType(CAMERA_MSG_VIDEO_FRAME), camera + * HAL should not rely on its client to call releaseRecordingFrame() to + * release video recording frames sent out by the cameral HAL before and + * after the disableMsgType(CAMERA_MSG_VIDEO_FRAME) call. Camera HAL + * clients must not modify/access any video recording frame after calling + * disableMsgType(CAMERA_MSG_VIDEO_FRAME). + */ + void (*disable_msg_type)(struct camera_device *, int32_t msg_type); + + /** + * Query whether a message, or a set of messages, is enabled. Note that + * this is operates as an AND, if any of the messages queried are off, this + * will return false. + */ + int (*msg_type_enabled)(struct camera_device *, int32_t msg_type); + + /** + * Start preview mode. + */ + int (*start_preview)(struct camera_device *); + + /** + * Stop a previously started preview. + */ + void (*stop_preview)(struct camera_device *); + + /** + * Returns true if preview is enabled. + */ + int (*preview_enabled)(struct camera_device *); + + /** + * Request the camera HAL to store meta data or real YUV data in the video + * buffers sent out via CAMERA_MSG_VIDEO_FRAME for a recording session. If + * it is not called, the default camera HAL behavior is to store real YUV + * data in the video buffers. + * + * This method should be called before startRecording() in order to be + * effective. + * + * If meta data is stored in the video buffers, it is up to the receiver of + * the video buffers to interpret the contents and to find the actual frame + * data with the help of the meta data in the buffer. How this is done is + * outside of the scope of this method. + * + * Some camera HALs may not support storing meta data in the video buffers, + * but all camera HALs should support storing real YUV data in the video + * buffers. If the camera HAL does not support storing the meta data in the + * video buffers when it is requested to do do, INVALID_OPERATION must be + * returned. It is very useful for the camera HAL to pass meta data rather + * than the actual frame data directly to the video encoder, since the + * amount of the uncompressed frame data can be very large if video size is + * large. + * + * @param enable if true to instruct the camera HAL to store + * meta data in the video buffers; false to instruct + * the camera HAL to store real YUV data in the video + * buffers. + * + * @return OK on success. + */ + int (*store_meta_data_in_buffers)(struct camera_device *, int enable); + + /** + * Start record mode. When a record image is available, a + * CAMERA_MSG_VIDEO_FRAME message is sent with the corresponding + * frame. Every record frame must be released by a camera HAL client via + * releaseRecordingFrame() before the client calls + * disableMsgType(CAMERA_MSG_VIDEO_FRAME). After the client calls + * disableMsgType(CAMERA_MSG_VIDEO_FRAME), it is the camera HAL's + * responsibility to manage the life-cycle of the video recording frames, + * and the client must not modify/access any video recording frames. + */ + int (*start_recording)(struct camera_device *); + + /** + * Stop a previously started recording. + */ + void (*stop_recording)(struct camera_device *); + + /** + * Returns true if recording is enabled. + */ + int (*recording_enabled)(struct camera_device *); + + /** + * Release a record frame previously returned by CAMERA_MSG_VIDEO_FRAME. + * + * It is camera HAL client's responsibility to release video recording + * frames sent out by the camera HAL before the camera HAL receives a call + * to disableMsgType(CAMERA_MSG_VIDEO_FRAME). After it receives the call to + * disableMsgType(CAMERA_MSG_VIDEO_FRAME), it is the camera HAL's + * responsibility to manage the life-cycle of the video recording frames. + */ + void (*release_recording_frame)(struct camera_device *, + const void *opaque); + + /** + * Start auto focus, the notification callback routine is called with + * CAMERA_MSG_FOCUS once when focusing is complete. autoFocus() will be + * called again if another auto focus is needed. + */ + int (*auto_focus)(struct camera_device *); + + /** + * Cancels auto-focus function. If the auto-focus is still in progress, + * this function will cancel it. Whether the auto-focus is in progress or + * not, this function will return the focus position to the default. If + * the camera does not support auto-focus, this is a no-op. + */ + int (*cancel_auto_focus)(struct camera_device *); + + /** + * Take a picture. + */ + int (*take_picture)(struct camera_device *); + + /** + * Cancel a picture that was started with takePicture. Calling this method + * when no picture is being taken is a no-op. + */ + int (*cancel_picture)(struct camera_device *); + + /** + * Set the camera parameters. This returns BAD_VALUE if any parameter is + * invalid or not supported. + */ + int (*set_parameters)(struct camera_device *, const char *parms); + + /** Retrieve the camera parameters. The buffer returned by the camera HAL + must be returned back to it with put_parameters, if put_parameters + is not NULL. + */ + char *(*get_parameters)(struct camera_device *); + + /** The camera HAL uses its own memory to pass us the parameters when we + call get_parameters. Use this function to return the memory back to + the camera HAL, if put_parameters is not NULL. If put_parameters + is NULL, then you have to use free() to release the memory. + */ + void (*put_parameters)(struct camera_device *, char *); + + /** + * Send command to camera driver. + */ + int (*send_command)(struct camera_device *, + int32_t cmd, int32_t arg1, int32_t arg2); + + /** + * Release the hardware resources owned by this object. Note that this is + * *not* done in the destructor. + */ + void (*release)(struct camera_device *); + + /** + * Dump state of the camera hardware + */ + int (*dump)(struct camera_device *, int fd); +} camera_device_ops_t; + +typedef struct camera_device { + /** + * camera_device.common.version must be in the range + * HARDWARE_DEVICE_API_VERSION(0,0)-(1,FF). CAMERA_DEVICE_API_VERSION_1_0 is + * recommended. + */ + hw_device_t common; + camera_device_ops_t *ops; + void *priv; +} camera_device_t; + +__END_DECLS + +#endif /* #ifdef ANDROID_INCLUDE_CAMERA_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/camera2.h b/phonelibs/android_hardware_libhardware/include/hardware/camera2.h new file mode 100644 index 0000000000..d920d4b65c --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/camera2.h @@ -0,0 +1,839 @@ +/* + * 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_INCLUDE_CAMERA2_H +#define ANDROID_INCLUDE_CAMERA2_H + +#include "camera_common.h" +#include "system/camera_metadata.h" + +/** + * Camera device HAL 2.1 [ CAMERA_DEVICE_API_VERSION_2_0, CAMERA_DEVICE_API_VERSION_2_1 ] + * + * DEPRECATED. New devices should use Camera HAL v3.2 or newer. + * + * Supports the android.hardware.Camera API, and the android.hardware.camera2 + * API in legacy mode only. + * + * Camera devices that support this version of the HAL must return + * CAMERA_DEVICE_API_VERSION_2_1 in camera_device_t.common.version and in + * camera_info_t.device_version (from camera_module_t.get_camera_info). + * + * Camera modules that may contain version 2.x devices must implement at least + * version 2.0 of the camera module interface (as defined by + * camera_module_t.common.module_api_version). + * + * See camera_common.h for more versioning details. + * + * Version history: + * + * 2.0: CAMERA_DEVICE_API_VERSION_2_0. Initial release (Android 4.2): + * - Sufficient for implementing existing android.hardware.Camera API. + * - Allows for ZSL queue in camera service layer + * - Not tested for any new features such manual capture control, + * Bayer RAW capture, reprocessing of RAW data. + * + * 2.1: CAMERA_DEVICE_API_VERSION_2_1. Support per-device static metadata: + * - Add get_instance_metadata() method to retrieve metadata that is fixed + * after device open, but may be variable between open() calls. + */ + +__BEGIN_DECLS + +struct camera2_device; + +/********************************************************************** + * + * Input/output stream buffer queue interface definitions + * + */ + +/** + * Output image stream queue interface. A set of these methods is provided to + * the HAL device in allocate_stream(), and are used to interact with the + * gralloc buffer queue for that stream. They may not be called until after + * allocate_stream returns. + */ +typedef struct camera2_stream_ops { + /** + * Get a buffer to fill from the queue. The size and format of the buffer + * are fixed for a given stream (defined in allocate_stream), and the stride + * should be queried from the platform gralloc module. The gralloc buffer + * will have been allocated based on the usage flags provided by + * allocate_stream, and will be locked for use. + */ + int (*dequeue_buffer)(const struct camera2_stream_ops* w, + buffer_handle_t** buffer); + + /** + * Push a filled buffer to the stream to be used by the consumer. + * + * The timestamp represents the time at start of exposure of the first row + * of the image; it must be from a monotonic clock, and is measured in + * nanoseconds. The timestamps do not need to be comparable between + * different cameras, or consecutive instances of the same camera. However, + * they must be comparable between streams from the same camera. If one + * capture produces buffers for multiple streams, each stream must have the + * same timestamp for that buffer, and that timestamp must match the + * timestamp in the output frame metadata. + */ + int (*enqueue_buffer)(const struct camera2_stream_ops* w, + int64_t timestamp, + buffer_handle_t* buffer); + /** + * Return a buffer to the queue without marking it as filled. + */ + int (*cancel_buffer)(const struct camera2_stream_ops* w, + buffer_handle_t* buffer); + /** + * Set the crop window for subsequently enqueued buffers. The parameters are + * measured in pixels relative to the buffer width and height. + */ + int (*set_crop)(const struct camera2_stream_ops *w, + int left, int top, int right, int bottom); + +} camera2_stream_ops_t; + +/** + * Temporary definition during transition. + * + * These formats will be removed and replaced with + * HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED. To maximize forward compatibility, + * HAL implementations are strongly recommended to treat FORMAT_OPAQUE and + * FORMAT_ZSL as equivalent to HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, and + * return HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED in the format_actual output + * parameter of allocate_stream, allowing the gralloc module to select the + * specific format based on the usage flags from the camera and the stream + * consumer. + */ +enum { + CAMERA2_HAL_PIXEL_FORMAT_OPAQUE = HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, + CAMERA2_HAL_PIXEL_FORMAT_ZSL = -1 +}; + +/** + * Transport header for compressed JPEG buffers in output streams. + * + * To capture JPEG images, a stream is created using the pixel format + * HAL_PIXEL_FORMAT_BLOB, and the static metadata field android.jpeg.maxSize is + * used as the buffer size. Since compressed JPEG images are of variable size, + * the HAL needs to include the final size of the compressed image using this + * structure inside the output stream buffer. The JPEG blob ID field must be set + * to CAMERA2_JPEG_BLOB_ID. + * + * Transport header should be at the end of the JPEG output stream buffer. That + * means the jpeg_blob_id must start at byte[android.jpeg.maxSize - + * sizeof(camera2_jpeg_blob)]. Any HAL using this transport header must + * account for it in android.jpeg.maxSize. The JPEG data itself starts at + * byte[0] and should be jpeg_size bytes long. + */ +typedef struct camera2_jpeg_blob { + uint16_t jpeg_blob_id; + uint32_t jpeg_size; +}; + +enum { + CAMERA2_JPEG_BLOB_ID = 0x00FF +}; + +/** + * Input reprocess stream queue management. A set of these methods is provided + * to the HAL device in allocate_reprocess_stream(); they are used to interact + * with the reprocess stream's input gralloc buffer queue. + */ +typedef struct camera2_stream_in_ops { + /** + * Get the next buffer of image data to reprocess. The width, height, and + * format of the buffer is fixed in allocate_reprocess_stream(), and the + * stride and other details should be queried from the platform gralloc + * module as needed. The buffer will already be locked for use. + */ + int (*acquire_buffer)(const struct camera2_stream_in_ops *w, + buffer_handle_t** buffer); + /** + * Return a used buffer to the buffer queue for reuse. + */ + int (*release_buffer)(const struct camera2_stream_in_ops *w, + buffer_handle_t* buffer); + +} camera2_stream_in_ops_t; + +/********************************************************************** + * + * Metadata queue management, used for requests sent to HAL module, and for + * frames produced by the HAL. + * + */ + +enum { + CAMERA2_REQUEST_QUEUE_IS_BOTTOMLESS = -1 +}; + +/** + * Request input queue protocol: + * + * The framework holds the queue and its contents. At start, the queue is empty. + * + * 1. When the first metadata buffer is placed into the queue, the framework + * signals the device by calling notify_request_queue_not_empty(). + * + * 2. After receiving notify_request_queue_not_empty, the device must call + * dequeue() once it's ready to handle the next buffer. + * + * 3. Once the device has processed a buffer, and is ready for the next buffer, + * it must call dequeue() again instead of waiting for a notification. If + * there are no more buffers available, dequeue() will return NULL. After + * this point, when a buffer becomes available, the framework must call + * notify_request_queue_not_empty() again. If the device receives a NULL + * return from dequeue, it does not need to query the queue again until a + * notify_request_queue_not_empty() call is received from the source. + * + * 4. If the device calls buffer_count() and receives 0, this does not mean that + * the framework will provide a notify_request_queue_not_empty() call. The + * framework will only provide such a notification after the device has + * received a NULL from dequeue, or on initial startup. + * + * 5. The dequeue() call in response to notify_request_queue_not_empty() may be + * on the same thread as the notify_request_queue_not_empty() call, and may + * be performed from within the notify call. + * + * 6. All dequeued request buffers must be returned to the framework by calling + * free_request, including when errors occur, a device flush is requested, or + * when the device is shutting down. + */ +typedef struct camera2_request_queue_src_ops { + /** + * Get the count of request buffers pending in the queue. May return + * CAMERA2_REQUEST_QUEUE_IS_BOTTOMLESS if a repeating request (stream + * request) is currently configured. Calling this method has no effect on + * whether the notify_request_queue_not_empty() method will be called by the + * framework. + */ + int (*request_count)(const struct camera2_request_queue_src_ops *q); + + /** + * Get a metadata buffer from the framework. Returns OK if there is no + * error. If the queue is empty, returns NULL in buffer. In that case, the + * device must wait for a notify_request_queue_not_empty() message before + * attempting to dequeue again. Buffers obtained in this way must be + * returned to the framework with free_request(). + */ + int (*dequeue_request)(const struct camera2_request_queue_src_ops *q, + camera_metadata_t **buffer); + /** + * Return a metadata buffer to the framework once it has been used, or if + * an error or shutdown occurs. + */ + int (*free_request)(const struct camera2_request_queue_src_ops *q, + camera_metadata_t *old_buffer); + +} camera2_request_queue_src_ops_t; + +/** + * Frame output queue protocol: + * + * The framework holds the queue and its contents. At start, the queue is empty. + * + * 1. When the device is ready to fill an output metadata frame, it must dequeue + * a metadata buffer of the required size. + * + * 2. It should then fill the metadata buffer, and place it on the frame queue + * using enqueue_frame. The framework takes ownership of the frame. + * + * 3. In case of an error, a request to flush the pipeline, or shutdown, the + * device must return any affected dequeued frames to the framework by + * calling cancel_frame. + */ +typedef struct camera2_frame_queue_dst_ops { + /** + * Get an empty metadata buffer to fill from the framework. The new metadata + * buffer will have room for entries number of metadata entries, plus + * data_bytes worth of extra storage. Frames dequeued here must be returned + * to the framework with either cancel_frame or enqueue_frame. + */ + int (*dequeue_frame)(const struct camera2_frame_queue_dst_ops *q, + size_t entries, size_t data_bytes, + camera_metadata_t **buffer); + + /** + * Return a dequeued metadata buffer to the framework for reuse; do not mark it as + * filled. Use when encountering errors, or flushing the internal request queue. + */ + int (*cancel_frame)(const struct camera2_frame_queue_dst_ops *q, + camera_metadata_t *buffer); + + /** + * Place a completed metadata frame on the frame output queue. + */ + int (*enqueue_frame)(const struct camera2_frame_queue_dst_ops *q, + camera_metadata_t *buffer); + +} camera2_frame_queue_dst_ops_t; + +/********************************************************************** + * + * Notification callback and message definition, and trigger definitions + * + */ + +/** + * Asynchronous notification callback from the HAL, fired for various + * reasons. Only for information independent of frame capture, or that require + * specific timing. The user pointer must be the same one that was passed to the + * device in set_notify_callback(). + */ +typedef void (*camera2_notify_callback)(int32_t msg_type, + int32_t ext1, + int32_t ext2, + int32_t ext3, + void *user); + +/** + * Possible message types for camera2_notify_callback + */ +enum { + /** + * An error has occurred. Argument ext1 contains the error code, and + * ext2 and ext3 contain any error-specific information. + */ + CAMERA2_MSG_ERROR = 0x0001, + /** + * The exposure of a given request has begun. Argument ext1 contains the + * frame number, and ext2 and ext3 contain the low-order and high-order + * bytes of the timestamp for when exposure began. + * (timestamp = (ext3 << 32 | ext2)) + */ + CAMERA2_MSG_SHUTTER = 0x0010, + /** + * The autofocus routine has changed state. Argument ext1 contains the new + * state; the values are the same as those for the metadata field + * android.control.afState. Ext2 contains the latest trigger ID passed to + * trigger_action(CAMERA2_TRIGGER_AUTOFOCUS) or + * trigger_action(CAMERA2_TRIGGER_CANCEL_AUTOFOCUS), or 0 if trigger has not + * been called with either of those actions. + */ + CAMERA2_MSG_AUTOFOCUS = 0x0020, + /** + * The autoexposure routine has changed state. Argument ext1 contains the + * new state; the values are the same as those for the metadata field + * android.control.aeState. Ext2 contains the latest trigger ID value passed to + * trigger_action(CAMERA2_TRIGGER_PRECAPTURE_METERING), or 0 if that method + * has not been called. + */ + CAMERA2_MSG_AUTOEXPOSURE = 0x0021, + /** + * The auto-whitebalance routine has changed state. Argument ext1 contains + * the new state; the values are the same as those for the metadata field + * android.control.awbState. Ext2 contains the latest trigger ID passed to + * trigger_action(CAMERA2_TRIGGER_PRECAPTURE_METERING), or 0 if that method + * has not been called. + */ + CAMERA2_MSG_AUTOWB = 0x0022 +}; + +/** + * Error codes for CAMERA_MSG_ERROR + */ +enum { + /** + * A serious failure occured. Camera device may not work without reboot, and + * no further frames or buffer streams will be produced by the + * device. Device should be treated as closed. + */ + CAMERA2_MSG_ERROR_HARDWARE = 0x0001, + /** + * A serious failure occured. No further frames or buffer streams will be + * produced by the device. Device should be treated as closed. The client + * must reopen the device to use it again. + */ + CAMERA2_MSG_ERROR_DEVICE, + /** + * An error has occurred in processing a request. No output (metadata or + * buffers) will be produced for this request. ext2 contains the frame + * number of the request. Subsequent requests are unaffected, and the device + * remains operational. + */ + CAMERA2_MSG_ERROR_REQUEST, + /** + * An error has occurred in producing an output frame metadata buffer for a + * request, but image buffers for it will still be available. Subsequent + * requests are unaffected, and the device remains operational. ext2 + * contains the frame number of the request. + */ + CAMERA2_MSG_ERROR_FRAME, + /** + * An error has occurred in placing an output buffer into a stream for a + * request. The frame metadata and other buffers may still be + * available. Subsequent requests are unaffected, and the device remains + * operational. ext2 contains the frame number of the request, and ext3 + * contains the stream id. + */ + CAMERA2_MSG_ERROR_STREAM, + /** + * Number of error types + */ + CAMERA2_MSG_NUM_ERRORS +}; + +/** + * Possible trigger ids for trigger_action() + */ +enum { + /** + * Trigger an autofocus cycle. The effect of the trigger depends on the + * autofocus mode in effect when the trigger is received, which is the mode + * listed in the latest capture request to be dequeued by the HAL. If the + * mode is OFF, EDOF, or FIXED, the trigger has no effect. In AUTO, MACRO, + * or CONTINUOUS_* modes, see below for the expected behavior. The state of + * the autofocus cycle can be tracked in android.control.afMode and the + * corresponding notifications. + * + ** + * In AUTO or MACRO mode, the AF state transitions (and notifications) + * when calling with trigger ID = N with the previous ID being K are: + * + * Initial state Transitions + * INACTIVE (K) -> ACTIVE_SCAN (N) -> AF_FOCUSED (N) or AF_NOT_FOCUSED (N) + * AF_FOCUSED (K) -> ACTIVE_SCAN (N) -> AF_FOCUSED (N) or AF_NOT_FOCUSED (N) + * AF_NOT_FOCUSED (K) -> ACTIVE_SCAN (N) -> AF_FOCUSED (N) or AF_NOT_FOCUSED (N) + * ACTIVE_SCAN (K) -> AF_FOCUSED(N) or AF_NOT_FOCUSED(N) + * PASSIVE_SCAN (K) Not used in AUTO/MACRO mode + * PASSIVE_FOCUSED (K) Not used in AUTO/MACRO mode + * + ** + * In CONTINUOUS_PICTURE mode, triggering AF must lock the AF to the current + * lens position and transition the AF state to either AF_FOCUSED or + * NOT_FOCUSED. If a passive scan is underway, that scan must complete and + * then lock the lens position and change AF state. TRIGGER_CANCEL_AUTOFOCUS + * will allow the AF to restart its operation. + * + * Initial state Transitions + * INACTIVE (K) -> immediate AF_FOCUSED (N) or AF_NOT_FOCUSED (N) + * PASSIVE_FOCUSED (K) -> immediate AF_FOCUSED (N) or AF_NOT_FOCUSED (N) + * PASSIVE_SCAN (K) -> AF_FOCUSED (N) or AF_NOT_FOCUSED (N) + * AF_FOCUSED (K) no effect except to change next notification ID to N + * AF_NOT_FOCUSED (K) no effect except to change next notification ID to N + * + ** + * In CONTINUOUS_VIDEO mode, triggering AF must lock the AF to the current + * lens position and transition the AF state to either AF_FOCUSED or + * NOT_FOCUSED. If a passive scan is underway, it must immediately halt, in + * contrast with CONTINUOUS_PICTURE mode. TRIGGER_CANCEL_AUTOFOCUS will + * allow the AF to restart its operation. + * + * Initial state Transitions + * INACTIVE (K) -> immediate AF_FOCUSED (N) or AF_NOT_FOCUSED (N) + * PASSIVE_FOCUSED (K) -> immediate AF_FOCUSED (N) or AF_NOT_FOCUSED (N) + * PASSIVE_SCAN (K) -> immediate AF_FOCUSED (N) or AF_NOT_FOCUSED (N) + * AF_FOCUSED (K) no effect except to change next notification ID to N + * AF_NOT_FOCUSED (K) no effect except to change next notification ID to N + * + * Ext1 is an ID that must be returned in subsequent auto-focus state change + * notifications through camera2_notify_callback() and stored in + * android.control.afTriggerId. + */ + CAMERA2_TRIGGER_AUTOFOCUS = 0x0001, + /** + * Send a cancel message to the autofocus algorithm. The effect of the + * cancellation depends on the autofocus mode in effect when the trigger is + * received, which is the mode listed in the latest capture request to be + * dequeued by the HAL. If the AF mode is OFF or EDOF, the cancel has no + * effect. For other modes, the lens should return to its default position, + * any current autofocus scan must be canceled, and the AF state should be + * set to INACTIVE. + * + * The state of the autofocus cycle can be tracked in android.control.afMode + * and the corresponding notification. Continuous autofocus modes may resume + * focusing operations thereafter exactly as if the camera had just been set + * to a continuous AF mode. + * + * Ext1 is an ID that must be returned in subsequent auto-focus state change + * notifications through camera2_notify_callback() and stored in + * android.control.afTriggerId. + */ + CAMERA2_TRIGGER_CANCEL_AUTOFOCUS, + /** + * Trigger a pre-capture metering cycle, which may include firing the flash + * to determine proper capture parameters. Typically, this trigger would be + * fired for a half-depress of a camera shutter key, or before a snapshot + * capture in general. The state of the metering cycle can be tracked in + * android.control.aeMode and the corresponding notification. If the + * auto-exposure mode is OFF, the trigger does nothing. + * + * Ext1 is an ID that must be returned in subsequent + * auto-exposure/auto-white balance state change notifications through + * camera2_notify_callback() and stored in android.control.aePrecaptureId. + */ + CAMERA2_TRIGGER_PRECAPTURE_METERING +}; + +/** + * Possible template types for construct_default_request() + */ +enum { + /** + * Standard camera preview operation with 3A on auto. + */ + CAMERA2_TEMPLATE_PREVIEW = 1, + /** + * Standard camera high-quality still capture with 3A and flash on auto. + */ + CAMERA2_TEMPLATE_STILL_CAPTURE, + /** + * Standard video recording plus preview with 3A on auto, torch off. + */ + CAMERA2_TEMPLATE_VIDEO_RECORD, + /** + * High-quality still capture while recording video. Application will + * include preview, video record, and full-resolution YUV or JPEG streams in + * request. Must not cause stuttering on video stream. 3A on auto. + */ + CAMERA2_TEMPLATE_VIDEO_SNAPSHOT, + /** + * Zero-shutter-lag mode. Application will request preview and + * full-resolution data for each frame, and reprocess it to JPEG when a + * still image is requested by user. Settings should provide highest-quality + * full-resolution images without compromising preview frame rate. 3A on + * auto. + */ + CAMERA2_TEMPLATE_ZERO_SHUTTER_LAG, + + /* Total number of templates */ + CAMERA2_TEMPLATE_COUNT +}; + + +/********************************************************************** + * + * Camera device operations + * + */ +typedef struct camera2_device_ops { + + /********************************************************************** + * Request and frame queue setup and management methods + */ + + /** + * Pass in input request queue interface methods. + */ + int (*set_request_queue_src_ops)(const struct camera2_device *, + const camera2_request_queue_src_ops_t *request_src_ops); + + /** + * Notify device that the request queue is no longer empty. Must only be + * called when the first buffer is added a new queue, or after the source + * has returned NULL in response to a dequeue call. + */ + int (*notify_request_queue_not_empty)(const struct camera2_device *); + + /** + * Pass in output frame queue interface methods + */ + int (*set_frame_queue_dst_ops)(const struct camera2_device *, + const camera2_frame_queue_dst_ops_t *frame_dst_ops); + + /** + * Number of camera requests being processed by the device at the moment + * (captures/reprocesses that have had their request dequeued, but have not + * yet been enqueued onto output pipeline(s) ). No streams may be released + * by the framework until the in-progress count is 0. + */ + int (*get_in_progress_count)(const struct camera2_device *); + + /** + * Flush all in-progress captures. This includes all dequeued requests + * (regular or reprocessing) that have not yet placed any outputs into a + * stream or the frame queue. Partially completed captures must be completed + * normally. No new requests may be dequeued from the request queue until + * the flush completes. + */ + int (*flush_captures_in_progress)(const struct camera2_device *); + + /** + * Create a filled-in default request for standard camera use cases. + * + * The device must return a complete request that is configured to meet the + * requested use case, which must be one of the CAMERA2_TEMPLATE_* + * enums. All request control fields must be included, except for + * android.request.outputStreams. + * + * The metadata buffer returned must be allocated with + * allocate_camera_metadata. The framework takes ownership of the buffer. + */ + int (*construct_default_request)(const struct camera2_device *, + int request_template, + camera_metadata_t **request); + + /********************************************************************** + * Stream management + */ + + /** + * allocate_stream: + * + * Allocate a new output stream for use, defined by the output buffer width, + * height, target, and possibly the pixel format. Returns the new stream's + * ID, gralloc usage flags, minimum queue buffer count, and possibly the + * pixel format, on success. Error conditions: + * + * - Requesting a width/height/format combination not listed as + * supported by the sensor's static characteristics + * + * - Asking for too many streams of a given format type (2 bayer raw + * streams, for example). + * + * Input parameters: + * + * - width, height, format: Specification for the buffers to be sent through + * this stream. Format is a value from the HAL_PIXEL_FORMAT_* list. If + * HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED is used, then the platform + * gralloc module will select a format based on the usage flags provided + * by the camera HAL and the consumer of the stream. The camera HAL should + * inspect the buffers handed to it in the register_stream_buffers call to + * obtain the implementation-specific format if necessary. + * + * - stream_ops: A structure of function pointers for obtaining and queuing + * up buffers for this stream. The underlying stream will be configured + * based on the usage and max_buffers outputs. The methods in this + * structure may not be called until after allocate_stream returns. + * + * Output parameters: + * + * - stream_id: An unsigned integer identifying this stream. This value is + * used in incoming requests to identify the stream, and in releasing the + * stream. + * + * - usage: The gralloc usage mask needed by the HAL device for producing + * the requested type of data. This is used in allocating new gralloc + * buffers for the stream buffer queue. + * + * - max_buffers: The maximum number of buffers the HAL device may need to + * have dequeued at the same time. The device may not dequeue more buffers + * than this value at the same time. + * + */ + int (*allocate_stream)( + const struct camera2_device *, + // inputs + uint32_t width, + uint32_t height, + int format, + const camera2_stream_ops_t *stream_ops, + // outputs + uint32_t *stream_id, + uint32_t *format_actual, // IGNORED, will be removed + uint32_t *usage, + uint32_t *max_buffers); + + /** + * Register buffers for a given stream. This is called after a successful + * allocate_stream call, and before the first request referencing the stream + * is enqueued. This method is intended to allow the HAL device to map or + * otherwise prepare the buffers for later use. num_buffers is guaranteed to + * be at least max_buffers (from allocate_stream), but may be larger. The + * buffers will already be locked for use. At the end of the call, all the + * buffers must be ready to be returned to the queue. If the stream format + * was set to HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, the camera HAL should + * inspect the passed-in buffers here to determine any platform-private + * pixel format information. + */ + int (*register_stream_buffers)( + const struct camera2_device *, + uint32_t stream_id, + int num_buffers, + buffer_handle_t *buffers); + + /** + * Release a stream. Returns an error if called when get_in_progress_count + * is non-zero, or if the stream id is invalid. + */ + int (*release_stream)( + const struct camera2_device *, + uint32_t stream_id); + + /** + * allocate_reprocess_stream: + * + * Allocate a new input stream for use, defined by the output buffer width, + * height, and the pixel format. Returns the new stream's ID, gralloc usage + * flags, and required simultaneously acquirable buffer count, on + * success. Error conditions: + * + * - Requesting a width/height/format combination not listed as + * supported by the sensor's static characteristics + * + * - Asking for too many reprocessing streams to be configured at once. + * + * Input parameters: + * + * - width, height, format: Specification for the buffers to be sent through + * this stream. Format must be a value from the HAL_PIXEL_FORMAT_* list. + * + * - reprocess_stream_ops: A structure of function pointers for acquiring + * and releasing buffers for this stream. The underlying stream will be + * configured based on the usage and max_buffers outputs. + * + * Output parameters: + * + * - stream_id: An unsigned integer identifying this stream. This value is + * used in incoming requests to identify the stream, and in releasing the + * stream. These ids are numbered separately from the input stream ids. + * + * - consumer_usage: The gralloc usage mask needed by the HAL device for + * consuming the requested type of data. This is used in allocating new + * gralloc buffers for the stream buffer queue. + * + * - max_buffers: The maximum number of buffers the HAL device may need to + * have acquired at the same time. The device may not have more buffers + * acquired at the same time than this value. + * + */ + int (*allocate_reprocess_stream)(const struct camera2_device *, + uint32_t width, + uint32_t height, + uint32_t format, + const camera2_stream_in_ops_t *reprocess_stream_ops, + // outputs + uint32_t *stream_id, + uint32_t *consumer_usage, + uint32_t *max_buffers); + + /** + * allocate_reprocess_stream_from_stream: + * + * Allocate a new input stream for use, which will use the buffers allocated + * for an existing output stream. That is, after the HAL enqueues a buffer + * onto the output stream, it may see that same buffer handed to it from + * this input reprocessing stream. After the HAL releases the buffer back to + * the reprocessing stream, it will be returned to the output queue for + * reuse. + * + * Error conditions: + * + * - Using an output stream of unsuitable size/format for the basis of the + * reprocessing stream. + * + * - Attempting to allocatee too many reprocessing streams at once. + * + * Input parameters: + * + * - output_stream_id: The ID of an existing output stream which has + * a size and format suitable for reprocessing. + * + * - reprocess_stream_ops: A structure of function pointers for acquiring + * and releasing buffers for this stream. The underlying stream will use + * the same graphics buffer handles as the output stream uses. + * + * Output parameters: + * + * - stream_id: An unsigned integer identifying this stream. This value is + * used in incoming requests to identify the stream, and in releasing the + * stream. These ids are numbered separately from the input stream ids. + * + * The HAL client must always release the reprocessing stream before it + * releases the output stream it is based on. + * + */ + int (*allocate_reprocess_stream_from_stream)(const struct camera2_device *, + uint32_t output_stream_id, + const camera2_stream_in_ops_t *reprocess_stream_ops, + // outputs + uint32_t *stream_id); + + /** + * Release a reprocessing stream. Returns an error if called when + * get_in_progress_count is non-zero, or if the stream id is not + * valid. + */ + int (*release_reprocess_stream)( + const struct camera2_device *, + uint32_t stream_id); + + /********************************************************************** + * Miscellaneous methods + */ + + /** + * Trigger asynchronous activity. This is used for triggering special + * behaviors of the camera 3A routines when they are in use. See the + * documentation for CAMERA2_TRIGGER_* above for details of the trigger ids + * and their arguments. + */ + int (*trigger_action)(const struct camera2_device *, + uint32_t trigger_id, + int32_t ext1, + int32_t ext2); + + /** + * Notification callback setup + */ + int (*set_notify_callback)(const struct camera2_device *, + camera2_notify_callback notify_cb, + void *user); + + /** + * Get methods to query for vendor extension metadata tag infomation. May + * set ops to NULL if no vendor extension tags are defined. + */ + int (*get_metadata_vendor_tag_ops)(const struct camera2_device*, + vendor_tag_query_ops_t **ops); + + /** + * Dump state of the camera hardware + */ + int (*dump)(const struct camera2_device *, int fd); + + /** + * Get device-instance-specific metadata. This metadata must be constant for + * a single instance of the camera device, but may be different between + * open() calls. The returned camera_metadata pointer must be valid until + * the device close() method is called. + * + * Version information: + * + * CAMERA_DEVICE_API_VERSION_2_0: + * + * Not available. Framework may not access this function pointer. + * + * CAMERA_DEVICE_API_VERSION_2_1: + * + * Valid. Can be called by the framework. + * + */ + int (*get_instance_metadata)(const struct camera2_device *, + camera_metadata **instance_metadata); + +} camera2_device_ops_t; + +/********************************************************************** + * + * Camera device definition + * + */ +typedef struct camera2_device { + /** + * common.version must equal CAMERA_DEVICE_API_VERSION_2_0 to identify + * this device as implementing version 2.0 of the camera device HAL. + */ + hw_device_t common; + camera2_device_ops_t *ops; + void *priv; +} camera2_device_t; + +__END_DECLS + +#endif /* #ifdef ANDROID_INCLUDE_CAMERA2_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/camera3.h b/phonelibs/android_hardware_libhardware/include/hardware/camera3.h new file mode 100644 index 0000000000..3ef6d6fada --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/camera3.h @@ -0,0 +1,3077 @@ +/* + * 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_INCLUDE_CAMERA3_H +#define ANDROID_INCLUDE_CAMERA3_H + +#include +#include "camera_common.h" + +/** + * Camera device HAL 3.3 [ CAMERA_DEVICE_API_VERSION_3_3 ] + * + * This is the current recommended version of the camera device HAL. + * + * Supports the android.hardware.Camera API, and as of v3.2, the + * android.hardware.camera2 API in LIMITED or FULL modes. + * + * Camera devices that support this version of the HAL must return + * CAMERA_DEVICE_API_VERSION_3_3 in camera_device_t.common.version and in + * camera_info_t.device_version (from camera_module_t.get_camera_info). + * + * CAMERA_DEVICE_API_VERSION_3_3: + * Camera modules that may contain version 3.3 devices must implement at + * least version 2.2 of the camera module interface (as defined by + * camera_module_t.common.module_api_version). + * + * CAMERA_DEVICE_API_VERSION_3_2: + * Camera modules that may contain version 3.2 devices must implement at + * least version 2.2 of the camera module interface (as defined by + * camera_module_t.common.module_api_version). + * + * <= CAMERA_DEVICE_API_VERSION_3_1: + * Camera modules that may contain version 3.1 (or 3.0) devices must + * implement at least version 2.0 of the camera module interface + * (as defined by camera_module_t.common.module_api_version). + * + * See camera_common.h for more versioning details. + * + * Documentation index: + * S1. Version history + * S2. Startup and operation sequencing + * S3. Operational modes + * S4. 3A modes and state machines + * S5. Cropping + * S6. Error management + * S7. Key Performance Indicator (KPI) glossary + * S8. Sample Use Cases + * S9. Notes on Controls and Metadata + * S10. Reprocessing flow and controls + */ + +/** + * S1. Version history: + * + * 1.0: Initial Android camera HAL (Android 4.0) [camera.h]: + * + * - Converted from C++ CameraHardwareInterface abstraction layer. + * + * - Supports android.hardware.Camera API. + * + * 2.0: Initial release of expanded-capability HAL (Android 4.2) [camera2.h]: + * + * - Sufficient for implementing existing android.hardware.Camera API. + * + * - Allows for ZSL queue in camera service layer + * + * - Not tested for any new features such manual capture control, Bayer RAW + * capture, reprocessing of RAW data. + * + * 3.0: First revision of expanded-capability HAL: + * + * - Major version change since the ABI is completely different. No change to + * the required hardware capabilities or operational model from 2.0. + * + * - Reworked input request and stream queue interfaces: Framework calls into + * HAL with next request and stream buffers already dequeued. Sync framework + * support is included, necessary for efficient implementations. + * + * - Moved triggers into requests, most notifications into results. + * + * - Consolidated all callbacks into framework into one structure, and all + * setup methods into a single initialize() call. + * + * - Made stream configuration into a single call to simplify stream + * management. Bidirectional streams replace STREAM_FROM_STREAM construct. + * + * - Limited mode semantics for older/limited hardware devices. + * + * 3.1: Minor revision of expanded-capability HAL: + * + * - configure_streams passes consumer usage flags to the HAL. + * + * - flush call to drop all in-flight requests/buffers as fast as possible. + * + * 3.2: Minor revision of expanded-capability HAL: + * + * - Deprecates get_metadata_vendor_tag_ops. Please use get_vendor_tag_ops + * in camera_common.h instead. + * + * - register_stream_buffers deprecated. All gralloc buffers provided + * by framework to HAL in process_capture_request may be new at any time. + * + * - add partial result support. process_capture_result may be called + * multiple times with a subset of the available result before the full + * result is available. + * + * - add manual template to camera3_request_template. The applications may + * use this template to control the capture settings directly. + * + * - Rework the bidirectional and input stream specifications. + * + * - change the input buffer return path. The buffer is returned in + * process_capture_result instead of process_capture_request. + * + * 3.3: Minor revision of expanded-capability HAL: + * + * - OPAQUE and YUV reprocessing API updates. + * + * - Basic support for depth output buffers. + * + * - Addition of data_space field to camera3_stream_t. + * + * - Addition of rotation field to camera3_stream_t. + * + * - Addition of camera3 stream configuration operation mode to camera3_stream_configuration_t + * + */ + +/** + * S2. Startup and general expected operation sequence: + * + * 1. Framework calls camera_module_t->common.open(), which returns a + * hardware_device_t structure. + * + * 2. Framework inspects the hardware_device_t->version field, and instantiates + * the appropriate handler for that version of the camera hardware device. In + * case the version is CAMERA_DEVICE_API_VERSION_3_0, the device is cast to + * a camera3_device_t. + * + * 3. Framework calls camera3_device_t->ops->initialize() with the framework + * callback function pointers. This will only be called this one time after + * open(), before any other functions in the ops structure are called. + * + * 4. The framework calls camera3_device_t->ops->configure_streams() with a list + * of input/output streams to the HAL device. + * + * 5. <= CAMERA_DEVICE_API_VERSION_3_1: + * + * The framework allocates gralloc buffers and calls + * camera3_device_t->ops->register_stream_buffers() for at least one of the + * output streams listed in configure_streams. The same stream is registered + * only once. + * + * >= CAMERA_DEVICE_API_VERSION_3_2: + * + * camera3_device_t->ops->register_stream_buffers() is not called and must + * be NULL. + * + * 6. The framework requests default settings for some number of use cases with + * calls to camera3_device_t->ops->construct_default_request_settings(). This + * may occur any time after step 3. + * + * 7. The framework constructs and sends the first capture request to the HAL, + * with settings based on one of the sets of default settings, and with at + * least one output stream, which has been registered earlier by the + * framework. This is sent to the HAL with + * camera3_device_t->ops->process_capture_request(). The HAL must block the + * return of this call until it is ready for the next request to be sent. + * + * >= CAMERA_DEVICE_API_VERSION_3_2: + * + * The buffer_handle_t provided in the camera3_stream_buffer_t array + * in the camera3_capture_request_t may be new and never-before-seen + * by the HAL on any given new request. + * + * 8. The framework continues to submit requests, and call + * construct_default_request_settings to get default settings buffers for + * other use cases. + * + * <= CAMERA_DEVICE_API_VERSION_3_1: + * + * The framework may call register_stream_buffers() at this time for + * not-yet-registered streams. + * + * 9. When the capture of a request begins (sensor starts exposing for the + * capture) or processing a reprocess request begins, the HAL + * calls camera3_callback_ops_t->notify() with the SHUTTER event, including + * the frame number and the timestamp for start of exposure. For a reprocess + * request, the timestamp must be the start of exposure of the input image + * which can be looked up with android.sensor.timestamp from + * camera3_capture_request_t.settings when process_capture_request() is + * called. + * + * <= CAMERA_DEVICE_API_VERSION_3_1: + * + * This notify call must be made before the first call to + * process_capture_result() for that frame number. + * + * >= CAMERA_DEVICE_API_VERSION_3_2: + * + * The camera3_callback_ops_t->notify() call with the SHUTTER event should + * be made as early as possible since the framework will be unable to + * deliver gralloc buffers to the application layer (for that frame) until + * it has a valid timestamp for the start of exposure (or the input image's + * start of exposure for a reprocess request). + * + * Both partial metadata results and the gralloc buffers may be sent to the + * framework at any time before or after the SHUTTER event. + * + * 10. After some pipeline delay, the HAL begins to return completed captures to + * the framework with camera3_callback_ops_t->process_capture_result(). These + * are returned in the same order as the requests were submitted. Multiple + * requests can be in flight at once, depending on the pipeline depth of the + * camera HAL device. + * + * >= CAMERA_DEVICE_API_VERSION_3_2: + * + * Once a buffer is returned by process_capture_result as part of the + * camera3_stream_buffer_t array, and the fence specified by release_fence + * has been signaled (this is a no-op for -1 fences), the ownership of that + * buffer is considered to be transferred back to the framework. After that, + * the HAL must no longer retain that particular buffer, and the + * framework may clean up the memory for it immediately. + * + * process_capture_result may be called multiple times for a single frame, + * each time with a new disjoint piece of metadata and/or set of gralloc + * buffers. The framework will accumulate these partial metadata results + * into one result. + * + * In particular, it is legal for a process_capture_result to be called + * simultaneously for both a frame N and a frame N+1 as long as the + * above rule holds for gralloc buffers (both input and output). + * + * 11. After some time, the framework may stop submitting new requests, wait for + * the existing captures to complete (all buffers filled, all results + * returned), and then call configure_streams() again. This resets the camera + * hardware and pipeline for a new set of input/output streams. Some streams + * may be reused from the previous configuration; if these streams' buffers + * had already been registered with the HAL, they will not be registered + * again. The framework then continues from step 7, if at least one + * registered output stream remains (otherwise, step 5 is required first). + * + * 12. Alternatively, the framework may call camera3_device_t->common->close() + * to end the camera session. This may be called at any time when no other + * calls from the framework are active, although the call may block until all + * in-flight captures have completed (all results returned, all buffers + * filled). After the close call returns, no more calls to the + * camera3_callback_ops_t functions are allowed from the HAL. Once the + * close() call is underway, the framework may not call any other HAL device + * functions. + * + * 13. In case of an error or other asynchronous event, the HAL must call + * camera3_callback_ops_t->notify() with the appropriate error/event + * message. After returning from a fatal device-wide error notification, the + * HAL should act as if close() had been called on it. However, the HAL must + * either cancel or complete all outstanding captures before calling + * notify(), so that once notify() is called with a fatal error, the + * framework will not receive further callbacks from the device. Methods + * besides close() should return -ENODEV or NULL after the notify() method + * returns from a fatal error message. + */ + +/** + * S3. Operational modes: + * + * The camera 3 HAL device can implement one of two possible operational modes; + * limited and full. Full support is expected from new higher-end + * devices. Limited mode has hardware requirements roughly in line with those + * for a camera HAL device v1 implementation, and is expected from older or + * inexpensive devices. Full is a strict superset of limited, and they share the + * same essential operational flow, as documented above. + * + * The HAL must indicate its level of support with the + * android.info.supportedHardwareLevel static metadata entry, with 0 indicating + * limited mode, and 1 indicating full mode support. + * + * Roughly speaking, limited-mode devices do not allow for application control + * of capture settings (3A control only), high-rate capture of high-resolution + * images, raw sensor readout, or support for YUV output streams above maximum + * recording resolution (JPEG only for large images). + * + * ** Details of limited mode behavior: + * + * - Limited-mode devices do not need to implement accurate synchronization + * between capture request settings and the actual image data + * captured. Instead, changes to settings may take effect some time in the + * future, and possibly not for the same output frame for each settings + * entry. Rapid changes in settings may result in some settings never being + * used for a capture. However, captures that include high-resolution output + * buffers ( > 1080p ) have to use the settings as specified (but see below + * for processing rate). + * + * - Limited-mode devices do not need to support most of the + * settings/result/static info metadata. Specifically, only the following settings + * are expected to be consumed or produced by a limited-mode HAL device: + * + * android.control.aeAntibandingMode (controls and dynamic) + * android.control.aeExposureCompensation (controls and dynamic) + * android.control.aeLock (controls and dynamic) + * android.control.aeMode (controls and dynamic) + * android.control.aeRegions (controls and dynamic) + * android.control.aeTargetFpsRange (controls and dynamic) + * android.control.aePrecaptureTrigger (controls and dynamic) + * android.control.afMode (controls and dynamic) + * android.control.afRegions (controls and dynamic) + * android.control.awbLock (controls and dynamic) + * android.control.awbMode (controls and dynamic) + * android.control.awbRegions (controls and dynamic) + * android.control.captureIntent (controls and dynamic) + * android.control.effectMode (controls and dynamic) + * android.control.mode (controls and dynamic) + * android.control.sceneMode (controls and dynamic) + * android.control.videoStabilizationMode (controls and dynamic) + * android.control.aeAvailableAntibandingModes (static) + * android.control.aeAvailableModes (static) + * android.control.aeAvailableTargetFpsRanges (static) + * android.control.aeCompensationRange (static) + * android.control.aeCompensationStep (static) + * android.control.afAvailableModes (static) + * android.control.availableEffects (static) + * android.control.availableSceneModes (static) + * android.control.availableVideoStabilizationModes (static) + * android.control.awbAvailableModes (static) + * android.control.maxRegions (static) + * android.control.sceneModeOverrides (static) + * android.control.aeState (dynamic) + * android.control.afState (dynamic) + * android.control.awbState (dynamic) + * + * android.flash.mode (controls and dynamic) + * android.flash.info.available (static) + * + * android.info.supportedHardwareLevel (static) + * + * android.jpeg.gpsCoordinates (controls and dynamic) + * android.jpeg.gpsProcessingMethod (controls and dynamic) + * android.jpeg.gpsTimestamp (controls and dynamic) + * android.jpeg.orientation (controls and dynamic) + * android.jpeg.quality (controls and dynamic) + * android.jpeg.thumbnailQuality (controls and dynamic) + * android.jpeg.thumbnailSize (controls and dynamic) + * android.jpeg.availableThumbnailSizes (static) + * android.jpeg.maxSize (static) + * + * android.lens.info.minimumFocusDistance (static) + * + * android.request.id (controls and dynamic) + * + * android.scaler.cropRegion (controls and dynamic) + * android.scaler.availableStreamConfigurations (static) + * android.scaler.availableMinFrameDurations (static) + * android.scaler.availableStallDurations (static) + * android.scaler.availableMaxDigitalZoom (static) + * android.scaler.maxDigitalZoom (static) + * android.scaler.croppingType (static) + * + * android.sensor.orientation (static) + * android.sensor.timestamp (dynamic) + * + * android.statistics.faceDetectMode (controls and dynamic) + * android.statistics.info.availableFaceDetectModes (static) + * android.statistics.faceIds (dynamic) + * android.statistics.faceLandmarks (dynamic) + * android.statistics.faceRectangles (dynamic) + * android.statistics.faceScores (dynamic) + * + * android.sync.frameNumber (dynamic) + * android.sync.maxLatency (static) + * + * - Captures in limited mode that include high-resolution (> 1080p) output + * buffers may block in process_capture_request() until all the output buffers + * have been filled. A full-mode HAL device must process sequences of + * high-resolution requests at the rate indicated in the static metadata for + * that pixel format. The HAL must still call process_capture_result() to + * provide the output; the framework must simply be prepared for + * process_capture_request() to block until after process_capture_result() for + * that request completes for high-resolution captures for limited-mode + * devices. + * + * - Full-mode devices must support below additional capabilities: + * - 30fps at maximum resolution is preferred, more than 20fps is required. + * - Per frame control (android.sync.maxLatency == PER_FRAME_CONTROL). + * - Sensor manual control metadata. See MANUAL_SENSOR defined in + * android.request.availableCapabilities. + * - Post-processing manual control metadata. See MANUAL_POST_PROCESSING defined + * in android.request.availableCapabilities. + * + */ + +/** + * S4. 3A modes and state machines: + * + * While the actual 3A algorithms are up to the HAL implementation, a high-level + * state machine description is defined by the HAL interface, to allow the HAL + * device and the framework to communicate about the current state of 3A, and to + * trigger 3A events. + * + * When the device is opened, all the individual 3A states must be + * STATE_INACTIVE. Stream configuration does not reset 3A. For example, locked + * focus must be maintained across the configure() call. + * + * Triggering a 3A action involves simply setting the relevant trigger entry in + * the settings for the next request to indicate start of trigger. For example, + * the trigger for starting an autofocus scan is setting the entry + * ANDROID_CONTROL_AF_TRIGGER to ANDROID_CONTROL_AF_TRIGGER_START for one + * request, and cancelling an autofocus scan is triggered by setting + * ANDROID_CONTROL_AF_TRIGGER to ANDROID_CONTRL_AF_TRIGGER_CANCEL. Otherwise, + * the entry will not exist, or be set to ANDROID_CONTROL_AF_TRIGGER_IDLE. Each + * request with a trigger entry set to a non-IDLE value will be treated as an + * independent triggering event. + * + * At the top level, 3A is controlled by the ANDROID_CONTROL_MODE setting, which + * selects between no 3A (ANDROID_CONTROL_MODE_OFF), normal AUTO mode + * (ANDROID_CONTROL_MODE_AUTO), and using the scene mode setting + * (ANDROID_CONTROL_USE_SCENE_MODE). + * + * - In OFF mode, each of the individual AE/AF/AWB modes are effectively OFF, + * and none of the capture controls may be overridden by the 3A routines. + * + * - In AUTO mode, Auto-focus, auto-exposure, and auto-whitebalance all run + * their own independent algorithms, and have their own mode, state, and + * trigger metadata entries, as listed in the next section. + * + * - In USE_SCENE_MODE, the value of the ANDROID_CONTROL_SCENE_MODE entry must + * be used to determine the behavior of 3A routines. In SCENE_MODEs other than + * FACE_PRIORITY, the HAL must override the values of + * ANDROId_CONTROL_AE/AWB/AF_MODE to be the mode it prefers for the selected + * SCENE_MODE. For example, the HAL may prefer SCENE_MODE_NIGHT to use + * CONTINUOUS_FOCUS AF mode. Any user selection of AE/AWB/AF_MODE when scene + * must be ignored for these scene modes. + * + * - For SCENE_MODE_FACE_PRIORITY, the AE/AWB/AF_MODE controls work as in + * ANDROID_CONTROL_MODE_AUTO, but the 3A routines must bias toward metering + * and focusing on any detected faces in the scene. + * + * S4.1. Auto-focus settings and result entries: + * + * Main metadata entries: + * + * ANDROID_CONTROL_AF_MODE: Control for selecting the current autofocus + * mode. Set by the framework in the request settings. + * + * AF_MODE_OFF: AF is disabled; the framework/app directly controls lens + * position. + * + * AF_MODE_AUTO: Single-sweep autofocus. No lens movement unless AF is + * triggered. + * + * AF_MODE_MACRO: Single-sweep up-close autofocus. No lens movement unless + * AF is triggered. + * + * AF_MODE_CONTINUOUS_VIDEO: Smooth continuous focusing, for recording + * video. Triggering immediately locks focus in current + * position. Canceling resumes cotinuous focusing. + * + * AF_MODE_CONTINUOUS_PICTURE: Fast continuous focusing, for + * zero-shutter-lag still capture. Triggering locks focus once currently + * active sweep concludes. Canceling resumes continuous focusing. + * + * AF_MODE_EDOF: Advanced extended depth of field focusing. There is no + * autofocus scan, so triggering one or canceling one has no effect. + * Images are focused automatically by the HAL. + * + * ANDROID_CONTROL_AF_STATE: Dynamic metadata describing the current AF + * algorithm state, reported by the HAL in the result metadata. + * + * AF_STATE_INACTIVE: No focusing has been done, or algorithm was + * reset. Lens is not moving. Always the state for MODE_OFF or MODE_EDOF. + * When the device is opened, it must start in this state. + * + * AF_STATE_PASSIVE_SCAN: A continuous focus algorithm is currently scanning + * for good focus. The lens is moving. + * + * AF_STATE_PASSIVE_FOCUSED: A continuous focus algorithm believes it is + * well focused. The lens is not moving. The HAL may spontaneously leave + * this state. + * + * AF_STATE_PASSIVE_UNFOCUSED: A continuous focus algorithm believes it is + * not well focused. The lens is not moving. The HAL may spontaneously + * leave this state. + * + * AF_STATE_ACTIVE_SCAN: A scan triggered by the user is underway. + * + * AF_STATE_FOCUSED_LOCKED: The AF algorithm believes it is focused. The + * lens is not moving. + * + * AF_STATE_NOT_FOCUSED_LOCKED: The AF algorithm has been unable to + * focus. The lens is not moving. + * + * ANDROID_CONTROL_AF_TRIGGER: Control for starting an autofocus scan, the + * meaning of which is mode- and state- dependent. Set by the framework in + * the request settings. + * + * AF_TRIGGER_IDLE: No current trigger. + * + * AF_TRIGGER_START: Trigger start of AF scan. Effect is mode and state + * dependent. + * + * AF_TRIGGER_CANCEL: Cancel current AF scan if any, and reset algorithm to + * default. + * + * Additional metadata entries: + * + * ANDROID_CONTROL_AF_REGIONS: Control for selecting the regions of the FOV + * that should be used to determine good focus. This applies to all AF + * modes that scan for focus. Set by the framework in the request + * settings. + * + * S4.2. Auto-exposure settings and result entries: + * + * Main metadata entries: + * + * ANDROID_CONTROL_AE_MODE: Control for selecting the current auto-exposure + * mode. Set by the framework in the request settings. + * + * AE_MODE_OFF: Autoexposure is disabled; the user controls exposure, gain, + * frame duration, and flash. + * + * AE_MODE_ON: Standard autoexposure, with flash control disabled. User may + * set flash to fire or to torch mode. + * + * AE_MODE_ON_AUTO_FLASH: Standard autoexposure, with flash on at HAL's + * discretion for precapture and still capture. User control of flash + * disabled. + * + * AE_MODE_ON_ALWAYS_FLASH: Standard autoexposure, with flash always fired + * for capture, and at HAL's discretion for precapture.. User control of + * flash disabled. + * + * AE_MODE_ON_AUTO_FLASH_REDEYE: Standard autoexposure, with flash on at + * HAL's discretion for precapture and still capture. Use a flash burst + * at end of precapture sequence to reduce redeye in the final + * picture. User control of flash disabled. + * + * ANDROID_CONTROL_AE_STATE: Dynamic metadata describing the current AE + * algorithm state, reported by the HAL in the result metadata. + * + * AE_STATE_INACTIVE: Initial AE state after mode switch. When the device is + * opened, it must start in this state. + * + * AE_STATE_SEARCHING: AE is not converged to a good value, and is adjusting + * exposure parameters. + * + * AE_STATE_CONVERGED: AE has found good exposure values for the current + * scene, and the exposure parameters are not changing. HAL may + * spontaneously leave this state to search for better solution. + * + * AE_STATE_LOCKED: AE has been locked with the AE_LOCK control. Exposure + * values are not changing. + * + * AE_STATE_FLASH_REQUIRED: The HAL has converged exposure, but believes + * flash is required for a sufficiently bright picture. Used for + * determining if a zero-shutter-lag frame can be used. + * + * AE_STATE_PRECAPTURE: The HAL is in the middle of a precapture + * sequence. Depending on AE mode, this mode may involve firing the + * flash for metering, or a burst of flash pulses for redeye reduction. + * + * ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER: Control for starting a metering + * sequence before capturing a high-quality image. Set by the framework in + * the request settings. + * + * PRECAPTURE_TRIGGER_IDLE: No current trigger. + * + * PRECAPTURE_TRIGGER_START: Start a precapture sequence. The HAL should + * use the subsequent requests to measure good exposure/white balance + * for an upcoming high-resolution capture. + * + * Additional metadata entries: + * + * ANDROID_CONTROL_AE_LOCK: Control for locking AE controls to their current + * values + * + * ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION: Control for adjusting AE + * algorithm target brightness point. + * + * ANDROID_CONTROL_AE_TARGET_FPS_RANGE: Control for selecting the target frame + * rate range for the AE algorithm. The AE routine cannot change the frame + * rate to be outside these bounds. + * + * ANDROID_CONTROL_AE_REGIONS: Control for selecting the regions of the FOV + * that should be used to determine good exposure levels. This applies to + * all AE modes besides OFF. + * + * S4.3. Auto-whitebalance settings and result entries: + * + * Main metadata entries: + * + * ANDROID_CONTROL_AWB_MODE: Control for selecting the current white-balance + * mode. + * + * AWB_MODE_OFF: Auto-whitebalance is disabled. User controls color matrix. + * + * AWB_MODE_AUTO: Automatic white balance is enabled; 3A controls color + * transform, possibly using more complex transforms than a simple + * matrix. + * + * AWB_MODE_INCANDESCENT: Fixed white balance settings good for indoor + * incandescent (tungsten) lighting, roughly 2700K. + * + * AWB_MODE_FLUORESCENT: Fixed white balance settings good for fluorescent + * lighting, roughly 5000K. + * + * AWB_MODE_WARM_FLUORESCENT: Fixed white balance settings good for + * fluorescent lighting, roughly 3000K. + * + * AWB_MODE_DAYLIGHT: Fixed white balance settings good for daylight, + * roughly 5500K. + * + * AWB_MODE_CLOUDY_DAYLIGHT: Fixed white balance settings good for clouded + * daylight, roughly 6500K. + * + * AWB_MODE_TWILIGHT: Fixed white balance settings good for + * near-sunset/sunrise, roughly 15000K. + * + * AWB_MODE_SHADE: Fixed white balance settings good for areas indirectly + * lit by the sun, roughly 7500K. + * + * ANDROID_CONTROL_AWB_STATE: Dynamic metadata describing the current AWB + * algorithm state, reported by the HAL in the result metadata. + * + * AWB_STATE_INACTIVE: Initial AWB state after mode switch. When the device + * is opened, it must start in this state. + * + * AWB_STATE_SEARCHING: AWB is not converged to a good value, and is + * changing color adjustment parameters. + * + * AWB_STATE_CONVERGED: AWB has found good color adjustment values for the + * current scene, and the parameters are not changing. HAL may + * spontaneously leave this state to search for better solution. + * + * AWB_STATE_LOCKED: AWB has been locked with the AWB_LOCK control. Color + * adjustment values are not changing. + * + * Additional metadata entries: + * + * ANDROID_CONTROL_AWB_LOCK: Control for locking AWB color adjustments to + * their current values. + * + * ANDROID_CONTROL_AWB_REGIONS: Control for selecting the regions of the FOV + * that should be used to determine good color balance. This applies only + * to auto-WB mode. + * + * S4.4. General state machine transition notes + * + * Switching between AF, AE, or AWB modes always resets the algorithm's state + * to INACTIVE. Similarly, switching between CONTROL_MODE or + * CONTROL_SCENE_MODE if CONTROL_MODE == USE_SCENE_MODE resets all the + * algorithm states to INACTIVE. + * + * The tables below are per-mode. + * + * S4.5. AF state machines + * + * when enabling AF or changing AF mode + *| state | trans. cause | new state | notes | + *+--------------------+---------------+--------------------+------------------+ + *| Any | AF mode change| INACTIVE | | + *+--------------------+---------------+--------------------+------------------+ + * + * mode = AF_MODE_OFF or AF_MODE_EDOF + *| state | trans. cause | new state | notes | + *+--------------------+---------------+--------------------+------------------+ + *| INACTIVE | | INACTIVE | Never changes | + *+--------------------+---------------+--------------------+------------------+ + * + * mode = AF_MODE_AUTO or AF_MODE_MACRO + *| state | trans. cause | new state | notes | + *+--------------------+---------------+--------------------+------------------+ + *| INACTIVE | AF_TRIGGER | ACTIVE_SCAN | Start AF sweep | + *| | | | Lens now moving | + *+--------------------+---------------+--------------------+------------------+ + *| ACTIVE_SCAN | AF sweep done | FOCUSED_LOCKED | If AF successful | + *| | | | Lens now locked | + *+--------------------+---------------+--------------------+------------------+ + *| ACTIVE_SCAN | AF sweep done | NOT_FOCUSED_LOCKED | If AF successful | + *| | | | Lens now locked | + *+--------------------+---------------+--------------------+------------------+ + *| ACTIVE_SCAN | AF_CANCEL | INACTIVE | Cancel/reset AF | + *| | | | Lens now locked | + *+--------------------+---------------+--------------------+------------------+ + *| FOCUSED_LOCKED | AF_CANCEL | INACTIVE | Cancel/reset AF | + *+--------------------+---------------+--------------------+------------------+ + *| FOCUSED_LOCKED | AF_TRIGGER | ACTIVE_SCAN | Start new sweep | + *| | | | Lens now moving | + *+--------------------+---------------+--------------------+------------------+ + *| NOT_FOCUSED_LOCKED | AF_CANCEL | INACTIVE | Cancel/reset AF | + *+--------------------+---------------+--------------------+------------------+ + *| NOT_FOCUSED_LOCKED | AF_TRIGGER | ACTIVE_SCAN | Start new sweep | + *| | | | Lens now moving | + *+--------------------+---------------+--------------------+------------------+ + *| All states | mode change | INACTIVE | | + *+--------------------+---------------+--------------------+------------------+ + * + * mode = AF_MODE_CONTINUOUS_VIDEO + *| state | trans. cause | new state | notes | + *+--------------------+---------------+--------------------+------------------+ + *| INACTIVE | HAL initiates | PASSIVE_SCAN | Start AF scan | + *| | new scan | | Lens now moving | + *+--------------------+---------------+--------------------+------------------+ + *| INACTIVE | AF_TRIGGER | NOT_FOCUSED_LOCKED | AF state query | + *| | | | Lens now locked | + *+--------------------+---------------+--------------------+------------------+ + *| PASSIVE_SCAN | HAL completes | PASSIVE_FOCUSED | End AF scan | + *| | current scan | | Lens now locked | + *+--------------------+---------------+--------------------+------------------+ + *| PASSIVE_SCAN | HAL fails | PASSIVE_UNFOCUSED | End AF scan | + *| | current scan | | Lens now locked | + *+--------------------+---------------+--------------------+------------------+ + *| PASSIVE_SCAN | AF_TRIGGER | FOCUSED_LOCKED | Immediate trans. | + *| | | | if focus is good | + *| | | | Lens now locked | + *+--------------------+---------------+--------------------+------------------+ + *| PASSIVE_SCAN | AF_TRIGGER | NOT_FOCUSED_LOCKED | Immediate trans. | + *| | | | if focus is bad | + *| | | | Lens now locked | + *+--------------------+---------------+--------------------+------------------+ + *| PASSIVE_SCAN | AF_CANCEL | INACTIVE | Reset lens | + *| | | | position | + *| | | | Lens now locked | + *+--------------------+---------------+--------------------+------------------+ + *| PASSIVE_FOCUSED | HAL initiates | PASSIVE_SCAN | Start AF scan | + *| | new scan | | Lens now moving | + *+--------------------+---------------+--------------------+------------------+ + *| PASSIVE_UNFOCUSED | HAL initiates | PASSIVE_SCAN | Start AF scan | + *| | new scan | | Lens now moving | + *+--------------------+---------------+--------------------+------------------+ + *| PASSIVE_FOCUSED | AF_TRIGGER | FOCUSED_LOCKED | Immediate trans. | + *| | | | Lens now locked | + *+--------------------+---------------+--------------------+------------------+ + *| PASSIVE_UNFOCUSED | AF_TRIGGER | NOT_FOCUSED_LOCKED | Immediate trans. | + *| | | | Lens now locked | + *+--------------------+---------------+--------------------+------------------+ + *| FOCUSED_LOCKED | AF_TRIGGER | FOCUSED_LOCKED | No effect | + *+--------------------+---------------+--------------------+------------------+ + *| FOCUSED_LOCKED | AF_CANCEL | INACTIVE | Restart AF scan | + *+--------------------+---------------+--------------------+------------------+ + *| NOT_FOCUSED_LOCKED | AF_TRIGGER | NOT_FOCUSED_LOCKED | No effect | + *+--------------------+---------------+--------------------+------------------+ + *| NOT_FOCUSED_LOCKED | AF_CANCEL | INACTIVE | Restart AF scan | + *+--------------------+---------------+--------------------+------------------+ + * + * mode = AF_MODE_CONTINUOUS_PICTURE + *| state | trans. cause | new state | notes | + *+--------------------+---------------+--------------------+------------------+ + *| INACTIVE | HAL initiates | PASSIVE_SCAN | Start AF scan | + *| | new scan | | Lens now moving | + *+--------------------+---------------+--------------------+------------------+ + *| INACTIVE | AF_TRIGGER | NOT_FOCUSED_LOCKED | AF state query | + *| | | | Lens now locked | + *+--------------------+---------------+--------------------+------------------+ + *| PASSIVE_SCAN | HAL completes | PASSIVE_FOCUSED | End AF scan | + *| | current scan | | Lens now locked | + *+--------------------+---------------+--------------------+------------------+ + *| PASSIVE_SCAN | HAL fails | PASSIVE_UNFOCUSED | End AF scan | + *| | current scan | | Lens now locked | + *+--------------------+---------------+--------------------+------------------+ + *| PASSIVE_SCAN | AF_TRIGGER | FOCUSED_LOCKED | Eventual trans. | + *| | | | once focus good | + *| | | | Lens now locked | + *+--------------------+---------------+--------------------+------------------+ + *| PASSIVE_SCAN | AF_TRIGGER | NOT_FOCUSED_LOCKED | Eventual trans. | + *| | | | if cannot focus | + *| | | | Lens now locked | + *+--------------------+---------------+--------------------+------------------+ + *| PASSIVE_SCAN | AF_CANCEL | INACTIVE | Reset lens | + *| | | | position | + *| | | | Lens now locked | + *+--------------------+---------------+--------------------+------------------+ + *| PASSIVE_FOCUSED | HAL initiates | PASSIVE_SCAN | Start AF scan | + *| | new scan | | Lens now moving | + *+--------------------+---------------+--------------------+------------------+ + *| PASSIVE_UNFOCUSED | HAL initiates | PASSIVE_SCAN | Start AF scan | + *| | new scan | | Lens now moving | + *+--------------------+---------------+--------------------+------------------+ + *| PASSIVE_FOCUSED | AF_TRIGGER | FOCUSED_LOCKED | Immediate trans. | + *| | | | Lens now locked | + *+--------------------+---------------+--------------------+------------------+ + *| PASSIVE_UNFOCUSED | AF_TRIGGER | NOT_FOCUSED_LOCKED | Immediate trans. | + *| | | | Lens now locked | + *+--------------------+---------------+--------------------+------------------+ + *| FOCUSED_LOCKED | AF_TRIGGER | FOCUSED_LOCKED | No effect | + *+--------------------+---------------+--------------------+------------------+ + *| FOCUSED_LOCKED | AF_CANCEL | INACTIVE | Restart AF scan | + *+--------------------+---------------+--------------------+------------------+ + *| NOT_FOCUSED_LOCKED | AF_TRIGGER | NOT_FOCUSED_LOCKED | No effect | + *+--------------------+---------------+--------------------+------------------+ + *| NOT_FOCUSED_LOCKED | AF_CANCEL | INACTIVE | Restart AF scan | + *+--------------------+---------------+--------------------+------------------+ + * + * S4.6. AE and AWB state machines + * + * The AE and AWB state machines are mostly identical. AE has additional + * FLASH_REQUIRED and PRECAPTURE states. So rows below that refer to those two + * states should be ignored for the AWB state machine. + * + * when enabling AE/AWB or changing AE/AWB mode + *| state | trans. cause | new state | notes | + *+--------------------+---------------+--------------------+------------------+ + *| Any | mode change | INACTIVE | | + *+--------------------+---------------+--------------------+------------------+ + * + * mode = AE_MODE_OFF / AWB mode not AUTO + *| state | trans. cause | new state | notes | + *+--------------------+---------------+--------------------+------------------+ + *| INACTIVE | | INACTIVE | AE/AWB disabled | + *+--------------------+---------------+--------------------+------------------+ + * + * mode = AE_MODE_ON_* / AWB_MODE_AUTO + *| state | trans. cause | new state | notes | + *+--------------------+---------------+--------------------+------------------+ + *| INACTIVE | HAL initiates | SEARCHING | | + *| | AE/AWB scan | | | + *+--------------------+---------------+--------------------+------------------+ + *| INACTIVE | AE/AWB_LOCK | LOCKED | values locked | + *| | on | | | + *+--------------------+---------------+--------------------+------------------+ + *| SEARCHING | HAL finishes | CONVERGED | good values, not | + *| | AE/AWB scan | | changing | + *+--------------------+---------------+--------------------+------------------+ + *| SEARCHING | HAL finishes | FLASH_REQUIRED | converged but too| + *| | AE scan | | dark w/o flash | + *+--------------------+---------------+--------------------+------------------+ + *| SEARCHING | AE/AWB_LOCK | LOCKED | values locked | + *| | on | | | + *+--------------------+---------------+--------------------+------------------+ + *| CONVERGED | HAL initiates | SEARCHING | values locked | + *| | AE/AWB scan | | | + *+--------------------+---------------+--------------------+------------------+ + *| CONVERGED | AE/AWB_LOCK | LOCKED | values locked | + *| | on | | | + *+--------------------+---------------+--------------------+------------------+ + *| FLASH_REQUIRED | HAL initiates | SEARCHING | values locked | + *| | AE/AWB scan | | | + *+--------------------+---------------+--------------------+------------------+ + *| FLASH_REQUIRED | AE/AWB_LOCK | LOCKED | values locked | + *| | on | | | + *+--------------------+---------------+--------------------+------------------+ + *| LOCKED | AE/AWB_LOCK | SEARCHING | values not good | + *| | off | | after unlock | + *+--------------------+---------------+--------------------+------------------+ + *| LOCKED | AE/AWB_LOCK | CONVERGED | values good | + *| | off | | after unlock | + *+--------------------+---------------+--------------------+------------------+ + *| LOCKED | AE_LOCK | FLASH_REQUIRED | exposure good, | + *| | off | | but too dark | + *+--------------------+---------------+--------------------+------------------+ + *| All AE states | PRECAPTURE_ | PRECAPTURE | Start precapture | + *| | START | | sequence | + *+--------------------+---------------+--------------------+------------------+ + *| PRECAPTURE | Sequence done.| CONVERGED | Ready for high- | + *| | AE_LOCK off | | quality capture | + *+--------------------+---------------+--------------------+------------------+ + *| PRECAPTURE | Sequence done.| LOCKED | Ready for high- | + *| | AE_LOCK on | | quality capture | + *+--------------------+---------------+--------------------+------------------+ + * + */ + +/** + * S5. Cropping: + * + * Cropping of the full pixel array (for digital zoom and other use cases where + * a smaller FOV is desirable) is communicated through the + * ANDROID_SCALER_CROP_REGION setting. This is a per-request setting, and can + * change on a per-request basis, which is critical for implementing smooth + * digital zoom. + * + * The region is defined as a rectangle (x, y, width, height), with (x, y) + * describing the top-left corner of the rectangle. The rectangle is defined on + * the coordinate system of the sensor active pixel array, with (0,0) being the + * top-left pixel of the active pixel array. Therefore, the width and height + * cannot be larger than the dimensions reported in the + * ANDROID_SENSOR_ACTIVE_PIXEL_ARRAY static info field. The minimum allowed + * width and height are reported by the HAL through the + * ANDROID_SCALER_MAX_DIGITAL_ZOOM static info field, which describes the + * maximum supported zoom factor. Therefore, the minimum crop region width and + * height are: + * + * {width, height} = + * { floor(ANDROID_SENSOR_ACTIVE_PIXEL_ARRAY[0] / + * ANDROID_SCALER_MAX_DIGITAL_ZOOM), + * floor(ANDROID_SENSOR_ACTIVE_PIXEL_ARRAY[1] / + * ANDROID_SCALER_MAX_DIGITAL_ZOOM) } + * + * If the crop region needs to fulfill specific requirements (for example, it + * needs to start on even coordinates, and its width/height needs to be even), + * the HAL must do the necessary rounding and write out the final crop region + * used in the output result metadata. Similarly, if the HAL implements video + * stabilization, it must adjust the result crop region to describe the region + * actually included in the output after video stabilization is applied. In + * general, a camera-using application must be able to determine the field of + * view it is receiving based on the crop region, the dimensions of the image + * sensor, and the lens focal length. + * + * It is assumed that the cropping is applied after raw to other color space + * conversion. Raw streams (RAW16 and RAW_OPAQUE) don't have this conversion stage, + * and are not croppable. Therefore, the crop region must be ignored by the HAL + * for raw streams. + * + * Since the crop region applies to all non-raw streams, which may have different aspect + * ratios than the crop region, the exact sensor region used for each stream may + * be smaller than the crop region. Specifically, each stream should maintain + * square pixels and its aspect ratio by minimally further cropping the defined + * crop region. If the stream's aspect ratio is wider than the crop region, the + * stream should be further cropped vertically, and if the stream's aspect ratio + * is narrower than the crop region, the stream should be further cropped + * horizontally. + * + * In all cases, the stream crop must be centered within the full crop region, + * and each stream is only either cropped horizontally or vertical relative to + * the full crop region, never both. + * + * For example, if two streams are defined, a 640x480 stream (4:3 aspect), and a + * 1280x720 stream (16:9 aspect), below demonstrates the expected output regions + * for each stream for a few sample crop regions, on a hypothetical 3 MP (2000 x + * 1500 pixel array) sensor. + * + * Crop region: (500, 375, 1000, 750) (4:3 aspect ratio) + * + * 640x480 stream crop: (500, 375, 1000, 750) (equal to crop region) + * 1280x720 stream crop: (500, 469, 1000, 562) (marked with =) + * + * 0 1000 2000 + * +---------+---------+---------+----------+ + * | Active pixel array | + * | | + * | | + * + +-------------------+ + 375 + * | | | | + * | O===================O | + * | I 1280x720 stream I | + * + I I + 750 + * | I I | + * | O===================O | + * | | | | + * + +-------------------+ + 1125 + * | Crop region, 640x480 stream | + * | | + * | | + * +---------+---------+---------+----------+ 1500 + * + * Crop region: (500, 375, 1333, 750) (16:9 aspect ratio) + * + * 640x480 stream crop: (666, 375, 1000, 750) (marked with =) + * 1280x720 stream crop: (500, 375, 1333, 750) (equal to crop region) + * + * 0 1000 2000 + * +---------+---------+---------+----------+ + * | Active pixel array | + * | | + * | | + * + +---O==================O---+ + 375 + * | | I 640x480 stream I | | + * | | I I | | + * | | I I | | + * + | I I | + 750 + * | | I I | | + * | | I I | | + * | | I I | | + * + +---O==================O---+ + 1125 + * | Crop region, 1280x720 stream | + * | | + * | | + * +---------+---------+---------+----------+ 1500 + * + * Crop region: (500, 375, 750, 750) (1:1 aspect ratio) + * + * 640x480 stream crop: (500, 469, 750, 562) (marked with =) + * 1280x720 stream crop: (500, 543, 750, 414) (marged with #) + * + * 0 1000 2000 + * +---------+---------+---------+----------+ + * | Active pixel array | + * | | + * | | + * + +--------------+ + 375 + * | O==============O | + * | ################ | + * | # # | + * + # # + 750 + * | # # | + * | ################ 1280x720 | + * | O==============O 640x480 | + * + +--------------+ + 1125 + * | Crop region | + * | | + * | | + * +---------+---------+---------+----------+ 1500 + * + * And a final example, a 1024x1024 square aspect ratio stream instead of the + * 480p stream: + * + * Crop region: (500, 375, 1000, 750) (4:3 aspect ratio) + * + * 1024x1024 stream crop: (625, 375, 750, 750) (marked with #) + * 1280x720 stream crop: (500, 469, 1000, 562) (marked with =) + * + * 0 1000 2000 + * +---------+---------+---------+----------+ + * | Active pixel array | + * | | + * | 1024x1024 stream | + * + +--###############--+ + 375 + * | | # # | | + * | O===================O | + * | I 1280x720 stream I | + * + I I + 750 + * | I I | + * | O===================O | + * | | # # | | + * + +--###############--+ + 1125 + * | Crop region | + * | | + * | | + * +---------+---------+---------+----------+ 1500 + * + */ + +/** + * S6. Error management: + * + * Camera HAL device ops functions that have a return value will all return + * -ENODEV / NULL in case of a serious error. This means the device cannot + * continue operation, and must be closed by the framework. Once this error is + * returned by some method, or if notify() is called with ERROR_DEVICE, only + * the close() method can be called successfully. All other methods will return + * -ENODEV / NULL. + * + * If a device op is called in the wrong sequence, for example if the framework + * calls configure_streams() is called before initialize(), the device must + * return -ENOSYS from the call, and do nothing. + * + * Transient errors in image capture must be reported through notify() as follows: + * + * - The failure of an entire capture to occur must be reported by the HAL by + * calling notify() with ERROR_REQUEST. Individual errors for the result + * metadata or the output buffers must not be reported in this case. + * + * - If the metadata for a capture cannot be produced, but some image buffers + * were filled, the HAL must call notify() with ERROR_RESULT. + * + * - If an output image buffer could not be filled, but either the metadata was + * produced or some other buffers were filled, the HAL must call notify() with + * ERROR_BUFFER for each failed buffer. + * + * In each of these transient failure cases, the HAL must still call + * process_capture_result, with valid output and input (if an input buffer was + * submitted) buffer_handle_t. If the result metadata could not be produced, it + * should be NULL. If some buffers could not be filled, they must be returned with + * process_capture_result in the error state, their release fences must be set to + * the acquire fences passed by the framework, or -1 if they have been waited on by + * the HAL already. + * + * Invalid input arguments result in -EINVAL from the appropriate methods. In + * that case, the framework must act as if that call had never been made. + * + */ + +/** + * S7. Key Performance Indicator (KPI) glossary: + * + * This includes some critical definitions that are used by KPI metrics. + * + * Pipeline Latency: + * For a given capture request, the duration from the framework calling + * process_capture_request to the HAL sending capture result and all buffers + * back by process_capture_result call. To make the Pipeline Latency measure + * independent of frame rate, it is measured by frame count. + * + * For example, when frame rate is 30 (fps), the frame duration (time interval + * between adjacent frame capture time) is 33 (ms). + * If it takes 5 frames for framework to get the result and buffers back for + * a given request, then the Pipeline Latency is 5 (frames), instead of + * 5 x 33 = 165 (ms). + * + * The Pipeline Latency is determined by android.request.pipelineDepth and + * android.request.pipelineMaxDepth, see their definitions for more details. + * + */ + +/** + * S8. Sample Use Cases: + * + * This includes some typical use case examples the camera HAL may support. + * + * S8.1 Zero Shutter Lag (ZSL) with CAMERA3_STREAM_BIDIRECTIONAL stream. + * + * For this use case, the bidirectional stream will be used by the framework as follows: + * + * 1. The framework includes a buffer from this stream as output buffer in a + * request as normal. + * + * 2. Once the HAL device returns a filled output buffer to the framework, + * the framework may do one of two things with the filled buffer: + * + * 2. a. The framework uses the filled data, and returns the now-used buffer + * to the stream queue for reuse. This behavior exactly matches the + * OUTPUT type of stream. + * + * 2. b. The framework wants to reprocess the filled data, and uses the + * buffer as an input buffer for a request. Once the HAL device has + * used the reprocessing buffer, it then returns it to the + * framework. The framework then returns the now-used buffer to the + * stream queue for reuse. + * + * 3. The HAL device will be given the buffer again as an output buffer for + * a request at some future point. + * + * For ZSL use case, the pixel format for bidirectional stream will be + * HAL_PIXEL_FORMAT_RAW_OPAQUE or HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED if it + * is listed in android.scaler.availableInputOutputFormatsMap. When + * HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED is used, the gralloc + * usage flags for the consumer endpoint will be set to GRALLOC_USAGE_HW_CAMERA_ZSL. + * A configuration stream list that has BIDIRECTIONAL stream used as input, will + * usually also have a distinct OUTPUT stream to get the reprocessing data. For example, + * for the ZSL use case, the stream list might be configured with the following: + * + * - A HAL_PIXEL_FORMAT_RAW_OPAQUE bidirectional stream is used + * as input. + * - And a HAL_PIXEL_FORMAT_BLOB (JPEG) output stream. + * + * S8.2 ZSL (OPAQUE) reprocessing with CAMERA3_STREAM_INPUT stream. + * + * CAMERA_DEVICE_API_VERSION_3_3: + * When OPAQUE_REPROCESSING capability is supported by the camera device, the INPUT stream + * can be used for application/framework implemented use case like Zero Shutter Lag (ZSL). + * This kind of stream will be used by the framework as follows: + * + * 1. Application/framework configures an opaque (RAW or YUV based) format output stream that is + * used to produce the ZSL output buffers. The stream pixel format will be + * HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED. + * + * 2. Application/framework configures an opaque format input stream that is used to + * send the reprocessing ZSL buffers to the HAL. The stream pixel format will + * also be HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED. + * + * 3. Application/framework configures a YUV/JPEG output stream that is used to receive the + * reprocessed data. The stream pixel format will be YCbCr_420/HAL_PIXEL_FORMAT_BLOB. + * + * 4. Application/framework picks a ZSL buffer from the ZSL output stream when a ZSL capture is + * issued by the application, and sends the data back as an input buffer in a + * reprocessing request, then sends to the HAL for reprocessing. + * + * 5. The HAL sends back the output YUV/JPEG result to framework. + * + * The HAL can select the actual opaque buffer format and configure the ISP pipeline + * appropriately based on the HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED format and + * the gralloc usage flag GRALLOC_USAGE_HW_CAMERA_ZSL. + + * S8.3 YUV reprocessing with CAMERA3_STREAM_INPUT stream. + * + * When YUV reprocessing is supported by the HAL, the INPUT stream + * can be used for the YUV reprocessing use cases like lucky-shot and image fusion. + * This kind of stream will be used by the framework as follows: + * + * 1. Application/framework configures an YCbCr_420 format output stream that is + * used to produce the output buffers. + * + * 2. Application/framework configures an YCbCr_420 format input stream that is used to + * send the reprocessing YUV buffers to the HAL. + * + * 3. Application/framework configures a YUV/JPEG output stream that is used to receive the + * reprocessed data. The stream pixel format will be YCbCr_420/HAL_PIXEL_FORMAT_BLOB. + * + * 4. Application/framework processes the output buffers (could be as simple as picking + * an output buffer directly) from the output stream when a capture is issued, and sends + * the data back as an input buffer in a reprocessing request, then sends to the HAL + * for reprocessing. + * + * 5. The HAL sends back the output YUV/JPEG result to framework. + * + */ + +/** + * S9. Notes on Controls and Metadata + * + * This section contains notes about the interpretation and usage of various metadata tags. + * + * S9.1 HIGH_QUALITY and FAST modes. + * + * Many camera post-processing blocks may be listed as having HIGH_QUALITY, + * FAST, and OFF operating modes. These blocks will typically also have an + * 'available modes' tag representing which of these operating modes are + * available on a given device. The general policy regarding implementing + * these modes is as follows: + * + * 1. Operating mode controls of hardware blocks that cannot be disabled + * must not list OFF in their corresponding 'available modes' tags. + * + * 2. OFF will always be included in their corresponding 'available modes' + * tag if it is possible to disable that hardware block. + * + * 3. FAST must always be included in the 'available modes' tags for all + * post-processing blocks supported on the device. If a post-processing + * block also has a slower and higher quality operating mode that does + * not meet the framerate requirements for FAST mode, HIGH_QUALITY should + * be included in the 'available modes' tag to represent this operating + * mode. + */ + +/** + * S10. Reprocessing flow and controls + * + * This section describes the OPAQUE and YUV reprocessing flow and controls. OPAQUE reprocessing + * uses an opaque format that is not directly application-visible, and the application can + * only select some of the output buffers and send back to HAL for reprocessing, while YUV + * reprocessing gives the application opportunity to process the buffers before reprocessing. + * + * S8 gives the stream configurations for the typical reprocessing uses cases, + * this section specifies the buffer flow and controls in more details. + * + * S10.1 OPAQUE (typically for ZSL use case) reprocessing flow and controls + * + * For OPAQUE reprocessing (e.g. ZSL) use case, after the application creates the specific + * output and input streams, runtime buffer flow and controls are specified as below: + * + * 1. Application starts output streaming by sending repeating requests for output + * opaque buffers and preview. The buffers are held by an application + * maintained circular buffer. The requests are based on CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG + * capture template, which should have all necessary settings that guarantee output + * frame rate is not slowed down relative to sensor output frame rate. + * + * 2. When a capture is issued, the application selects one output buffer based + * on application buffer selection logic, e.g. good AE and AF statistics etc. + * Application then creates an reprocess request based on the capture result associated + * with this selected buffer. The selected output buffer is now added to this reprocess + * request as an input buffer, the output buffer of this reprocess request should be + * either JPEG output buffer or YUV output buffer, or both, depending on the application + * choice. + * + * 3. Application then alters the reprocess settings to get best image quality. The HAL must + * support and only support below controls if the HAL support OPAQUE_REPROCESSING capability: + * - android.jpeg.* (if JPEG buffer is included as one of the output) + * - android.noiseReduction.mode (change to HIGH_QUALITY if it is supported) + * - android.edge.mode (change to HIGH_QUALITY if it is supported) + * All other controls must be ignored by the HAL. + * 4. HAL processed the input buffer and return the output buffers in the capture results + * as normal. + * + * S10.2 YUV reprocessing flow and controls + * + * The YUV reprocessing buffer flow is similar as OPAQUE reprocessing, with below difference: + * + * 1. Application may want to have finer granularity control of the intermediate YUV images + * (before reprocessing). For example, application may choose + * - android.noiseReduction.mode == MINIMAL + * to make sure the no YUV domain noise reduction has applied to the output YUV buffers, + * then it can do its own advanced noise reduction on them. For OPAQUE reprocessing case, this + * doesn't matter, as long as the final reprocessed image has the best quality. + * 2. Application may modify the YUV output buffer data. For example, for image fusion use + * case, where multiple output images are merged together to improve the signal-to-noise + * ratio (SNR). The input buffer may be generated from multiple buffers by the application. + * To avoid excessive amount of noise reduction and insufficient amount of edge enhancement + * being applied to the input buffer, the application can hint the HAL how much effective + * exposure time improvement has been done by the application, then the HAL can adjust the + * noise reduction and edge enhancement paramters to get best reprocessed image quality. + * Below tag can be used for this purpose: + * - android.reprocess.effectiveExposureFactor + * The value would be exposure time increase factor applied to the original output image, + * for example, if there are N image merged, the exposure time increase factor would be up + * to sqrt(N). See this tag spec for more details. + * + * S10.3 Reprocessing pipeline characteristics + * + * Reprocessing pipeline has below different characteristics comparing with normal output + * pipeline: + * + * 1. The reprocessing result can be returned ahead of the pending normal output results. But + * the FIFO ordering must be maintained for all reprocessing results. For example, there are + * below requests (A stands for output requests, B stands for reprocessing requests) + * being processed by the HAL: + * A1, A2, A3, A4, B1, A5, B2, A6... + * result of B1 can be returned before A1-A4, but result of B2 must be returned after B1. + * 2. Single input rule: For a given reprocessing request, all output buffers must be from the + * input buffer, rather than sensor output. For example, if a reprocess request include both + * JPEG and preview buffers, all output buffers must be produced from the input buffer + * included by the reprocessing request, rather than sensor. The HAL must not output preview + * buffers from sensor, while output JPEG buffer from the input buffer. + * 3. Input buffer will be from camera output directly (ZSL case) or indirectly(image fusion + * case). For the case where buffer is modified, the size will remain same. The HAL can + * notify CAMERA3_MSG_ERROR_REQUEST if buffer from unknown source is sent. + * 4. Result as reprocessing request: The HAL can expect that a reprocessing request is a copy + * of one of the output results with minor allowed setting changes. The HAL can notify + * CAMERA3_MSG_ERROR_REQUEST if a request from unknown source is issued. + * 5. Output buffers may not be used as inputs across the configure stream boundary, This is + * because an opaque stream like the ZSL output stream may have different actual image size + * inside of the ZSL buffer to save power and bandwidth for smaller resolution JPEG capture. + * The HAL may notify CAMERA3_MSG_ERROR_REQUEST if this case occurs. + * 6. HAL Reprocess requests error reporting during flush should follow the same rule specified + * by flush() method. + * + */ + +__BEGIN_DECLS + +struct camera3_device; + +/********************************************************************** + * + * Camera3 stream and stream buffer definitions. + * + * These structs and enums define the handles and contents of the input and + * output streams connecting the HAL to various framework and application buffer + * consumers. Each stream is backed by a gralloc buffer queue. + * + */ + +/** + * camera3_stream_type_t: + * + * The type of the camera stream, which defines whether the camera HAL device is + * the producer or the consumer for that stream, and how the buffers of the + * stream relate to the other streams. + */ +typedef enum camera3_stream_type { + /** + * This stream is an output stream; the camera HAL device will be + * responsible for filling buffers from this stream with newly captured or + * reprocessed image data. + */ + CAMERA3_STREAM_OUTPUT = 0, + + /** + * This stream is an input stream; the camera HAL device will be responsible + * for reading buffers from this stream and sending them through the camera + * processing pipeline, as if the buffer was a newly captured image from the + * imager. + * + * The pixel format for input stream can be any format reported by + * android.scaler.availableInputOutputFormatsMap. The pixel format of the + * output stream that is used to produce the reprocessing data may be any + * format reported by android.scaler.availableStreamConfigurations. The + * supported input/output stream combinations depends the camera device + * capabilities, see android.scaler.availableInputOutputFormatsMap for + * stream map details. + * + * This kind of stream is generally used to reprocess data into higher + * quality images (that otherwise would cause a frame rate performance + * loss), or to do off-line reprocessing. + * + * CAMERA_DEVICE_API_VERSION_3_3: + * The typical use cases are OPAQUE (typically ZSL) and YUV reprocessing, + * see S8.2, S8.3 and S10 for more details. + */ + CAMERA3_STREAM_INPUT = 1, + + /** + * This stream can be used for input and output. Typically, the stream is + * used as an output stream, but occasionally one already-filled buffer may + * be sent back to the HAL device for reprocessing. + * + * This kind of stream is meant generally for Zero Shutter Lag (ZSL) + * features, where copying the captured image from the output buffer to the + * reprocessing input buffer would be expensive. See S8.1 for more details. + * + * Note that the HAL will always be reprocessing data it produced. + * + */ + CAMERA3_STREAM_BIDIRECTIONAL = 2, + + /** + * Total number of framework-defined stream types + */ + CAMERA3_NUM_STREAM_TYPES + +} camera3_stream_type_t; + +/** + * camera3_stream_rotation_t: + * + * The required counterclockwise rotation of camera stream. + */ +typedef enum camera3_stream_rotation { + /* No rotation */ + CAMERA3_STREAM_ROTATION_0 = 0, + + /* Rotate by 90 degree counterclockwise */ + CAMERA3_STREAM_ROTATION_90 = 1, + + /* Rotate by 180 degree counterclockwise */ + CAMERA3_STREAM_ROTATION_180 = 2, + + /* Rotate by 270 degree counterclockwise */ + CAMERA3_STREAM_ROTATION_270 = 3 +} camera3_stream_rotation_t; + +/** + * camera3_stream_configuration_mode_t: + * + * This defines the general operation mode for the HAL (for a given stream configuration), where + * modes besides NORMAL have different semantics, and usually limit the generality of the API in + * exchange for higher performance in some particular area. + */ +typedef enum camera3_stream_configuration_mode { + /** + * Normal stream configuration operation mode. This is the default camera operation mode, + * where all semantics of HAL APIs and metadata controls apply. + */ + CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE = 0, + + /** + * Special constrained high speed operation mode for devices that can not support high + * speed output in NORMAL mode. All streams in this configuration are operating at high speed + * mode and have different characteristics and limitations to achieve high speed output. + * The NORMAL mode can still be used for high speed output if the HAL can support high speed + * output while satisfying all the semantics of HAL APIs and metadata controls. It is + * recommended for the HAL to support high speed output in NORMAL mode (by advertising the high + * speed FPS ranges in android.control.aeAvailableTargetFpsRanges) if possible. + * + * This mode has below limitations/requirements: + * + * 1. The HAL must support up to 2 streams with sizes reported by + * android.control.availableHighSpeedVideoConfigurations. + * 2. In this mode, the HAL is expected to output up to 120fps or higher. This mode must + * support the targeted FPS range and size configurations reported by + * android.control.availableHighSpeedVideoConfigurations. + * 3. The HAL must support HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED output stream format. + * 4. To achieve efficient high speed streaming, the HAL may have to aggregate + * multiple frames together and send to camera device for processing where the request + * controls are same for all the frames in this batch (batch mode). The HAL must support + * max batch size and the max batch size requirements defined by + * android.control.availableHighSpeedVideoConfigurations. + * 5. In this mode, the HAL must override aeMode, awbMode, and afMode to ON, ON, and + * CONTINUOUS_VIDEO, respectively. All post-processing block mode controls must be + * overridden to be FAST. Therefore, no manual control of capture and post-processing + * parameters is possible. All other controls operate the same as when + * android.control.mode == AUTO. This means that all other android.control.* fields + * must continue to work, such as + * + * android.control.aeTargetFpsRange + * android.control.aeExposureCompensation + * android.control.aeLock + * android.control.awbLock + * android.control.effectMode + * android.control.aeRegions + * android.control.afRegions + * android.control.awbRegions + * android.control.afTrigger + * android.control.aePrecaptureTrigger + * + * Outside of android.control.*, the following controls must work: + * + * android.flash.mode (TORCH mode only, automatic flash for still capture will not work + * since aeMode is ON) + * android.lens.opticalStabilizationMode (if it is supported) + * android.scaler.cropRegion + * android.statistics.faceDetectMode (if it is supported) + * + * For more details about high speed stream requirements, see + * android.control.availableHighSpeedVideoConfigurations and CONSTRAINED_HIGH_SPEED_VIDEO + * capability defined in android.request.availableCapabilities. + * + * This mode only needs to be supported by HALs that include CONSTRAINED_HIGH_SPEED_VIDEO in + * the android.request.availableCapabilities static metadata. + */ + CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE = 1, + + /** + * First value for vendor-defined stream configuration modes. + */ + CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START = 0x8000 +} camera3_stream_configuration_mode_t; + +/** + * camera3_stream_t: + * + * A handle to a single camera input or output stream. A stream is defined by + * the framework by its buffer resolution and format, and additionally by the + * HAL with the gralloc usage flags and the maximum in-flight buffer count. + * + * The stream structures are owned by the framework, but pointers to a + * camera3_stream passed into the HAL by configure_streams() are valid until the + * end of the first subsequent configure_streams() call that _does not_ include + * that camera3_stream as an argument, or until the end of the close() call. + * + * All camera3_stream framework-controlled members are immutable once the + * camera3_stream is passed into configure_streams(). The HAL may only change + * the HAL-controlled parameters during a configure_streams() call, except for + * the contents of the private pointer. + * + * If a configure_streams() call returns a non-fatal error, all active streams + * remain valid as if configure_streams() had not been called. + * + * The endpoint of the stream is not visible to the camera HAL device. + * In DEVICE_API_VERSION_3_1, this was changed to share consumer usage flags + * on streams where the camera is a producer (OUTPUT and BIDIRECTIONAL stream + * types) see the usage field below. + */ +typedef struct camera3_stream { + + /***** + * Set by framework before configure_streams() + */ + + /** + * The type of the stream, one of the camera3_stream_type_t values. + */ + int stream_type; + + /** + * The width in pixels of the buffers in this stream + */ + uint32_t width; + + /** + * The height in pixels of the buffers in this stream + */ + uint32_t height; + + /** + * The pixel format for the buffers in this stream. Format is a value from + * the HAL_PIXEL_FORMAT_* list in system/core/include/system/graphics.h, or + * from device-specific headers. + * + * If HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED is used, then the platform + * gralloc module will select a format based on the usage flags provided by + * the camera device and the other endpoint of the stream. + * + * <= CAMERA_DEVICE_API_VERSION_3_1: + * + * The camera HAL device must inspect the buffers handed to it in the + * subsequent register_stream_buffers() call to obtain the + * implementation-specific format details, if necessary. + * + * >= CAMERA_DEVICE_API_VERSION_3_2: + * + * register_stream_buffers() won't be called by the framework, so the HAL + * should configure the ISP and sensor pipeline based purely on the sizes, + * usage flags, and formats for the configured streams. + */ + int format; + + /***** + * Set by HAL during configure_streams(). + */ + + /** + * The gralloc usage flags for this stream, as needed by the HAL. The usage + * flags are defined in gralloc.h (GRALLOC_USAGE_*), or in device-specific + * headers. + * + * For output streams, these are the HAL's producer usage flags. For input + * streams, these are the HAL's consumer usage flags. The usage flags from + * the producer and the consumer will be combined together and then passed + * to the platform gralloc HAL module for allocating the gralloc buffers for + * each stream. + * + * Version information: + * + * == CAMERA_DEVICE_API_VERSION_3_0: + * + * No initial value guaranteed when passed via configure_streams(). + * HAL may not use this field as input, and must write over this field + * with its usage flags. + * + * >= CAMERA_DEVICE_API_VERSION_3_1: + * + * For stream_type OUTPUT and BIDIRECTIONAL, when passed via + * configure_streams(), the initial value of this is the consumer's + * usage flags. The HAL may use these consumer flags to decide stream + * configuration. + * For stream_type INPUT, when passed via configure_streams(), the initial + * value of this is 0. + * For all streams passed via configure_streams(), the HAL must write + * over this field with its usage flags. + */ + uint32_t usage; + + /** + * The maximum number of buffers the HAL device may need to have dequeued at + * the same time. The HAL device may not have more buffers in-flight from + * this stream than this value. + */ + uint32_t max_buffers; + + /** + * A handle to HAL-private information for the stream. Will not be inspected + * by the framework code. + */ + void *priv; + + /** + * A field that describes the contents of the buffer. The format and buffer + * dimensions define the memory layout and structure of the stream buffers, + * while dataSpace defines the meaning of the data within the buffer. + * + * For most formats, dataSpace defines the color space of the image data. + * In addition, for some formats, dataSpace indicates whether image- or + * depth-based data is requested. See system/core/include/system/graphics.h + * for details of formats and valid dataSpace values for each format. + * + * Version information: + * + * < CAMERA_DEVICE_API_VERSION_3_3: + * + * Not defined and should not be accessed. dataSpace should be assumed to + * be HAL_DATASPACE_UNKNOWN, and the appropriate color space, etc, should + * be determined from the usage flags and the format. + * + * >= CAMERA_DEVICE_API_VERSION_3_3: + * + * Always set by the camera service. HAL must use this dataSpace to + * configure the stream to the correct colorspace, or to select between + * color and depth outputs if supported. + */ + android_dataspace_t data_space; + + /** + * The required output rotation of the stream, one of + * the camera3_stream_rotation_t values. This must be inspected by HAL along + * with stream width and height. For example, if the rotation is 90 degree + * and the stream width and height is 720 and 1280 respectively, camera service + * will supply buffers of size 720x1280, and HAL should capture a 1280x720 image + * and rotate the image by 90 degree counterclockwise. The rotation field is + * no-op when the stream type is input. Camera HAL must ignore the rotation + * field for an input stream. + * + * <= CAMERA_DEVICE_API_VERSION_3_2: + * + * Not defined and must not be accessed. HAL must not apply any rotation + * on output images. + * + * >= CAMERA_DEVICE_API_VERSION_3_3: + * + * Always set by camera service. HAL must inspect this field during stream + * configuration and returns -EINVAL if HAL cannot perform such rotation. + * HAL must always support CAMERA3_STREAM_ROTATION_0, so a + * configure_streams() call must not fail for unsupported rotation if + * rotation field of all streams is CAMERA3_STREAM_ROTATION_0. + * + */ + int rotation; + + /* reserved for future use */ + void *reserved[7]; + +} camera3_stream_t; + +/** + * camera3_stream_configuration_t: + * + * A structure of stream definitions, used by configure_streams(). This + * structure defines all the output streams and the reprocessing input + * stream for the current camera use case. + */ +typedef struct camera3_stream_configuration { + /** + * The total number of streams requested by the framework. This includes + * both input and output streams. The number of streams will be at least 1, + * and there will be at least one output-capable stream. + */ + uint32_t num_streams; + + /** + * An array of camera stream pointers, defining the input/output + * configuration for the camera HAL device. + * + * At most one input-capable stream may be defined (INPUT or BIDIRECTIONAL) + * in a single configuration. + * + * At least one output-capable stream must be defined (OUTPUT or + * BIDIRECTIONAL). + */ + camera3_stream_t **streams; + + /** + * >= CAMERA_DEVICE_API_VERSION_3_3: + * + * The operation mode of streams in this configuration, one of the value defined in + * camera3_stream_configuration_mode_t. + * The HAL can use this mode as an indicator to set the stream property (e.g., + * camera3_stream->max_buffers) appropriately. For example, if the configuration is + * CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE, the HAL may want to set aside more + * buffers for batch mode operation (see android.control.availableHighSpeedVideoConfigurations + * for batch mode definition). + * + */ + uint32_t operation_mode; +} camera3_stream_configuration_t; + +/** + * camera3_buffer_status_t: + * + * The current status of a single stream buffer. + */ +typedef enum camera3_buffer_status { + /** + * The buffer is in a normal state, and can be used after waiting on its + * sync fence. + */ + CAMERA3_BUFFER_STATUS_OK = 0, + + /** + * The buffer does not contain valid data, and the data in it should not be + * used. The sync fence must still be waited on before reusing the buffer. + */ + CAMERA3_BUFFER_STATUS_ERROR = 1 + +} camera3_buffer_status_t; + +/** + * camera3_stream_buffer_t: + * + * A single buffer from a camera3 stream. It includes a handle to its parent + * stream, the handle to the gralloc buffer itself, and sync fences + * + * The buffer does not specify whether it is to be used for input or output; + * that is determined by its parent stream type and how the buffer is passed to + * the HAL device. + */ +typedef struct camera3_stream_buffer { + /** + * The handle of the stream this buffer is associated with + */ + camera3_stream_t *stream; + + /** + * The native handle to the buffer + */ + buffer_handle_t *buffer; + + /** + * Current state of the buffer, one of the camera3_buffer_status_t + * values. The framework will not pass buffers to the HAL that are in an + * error state. In case a buffer could not be filled by the HAL, it must + * have its status set to CAMERA3_BUFFER_STATUS_ERROR when returned to the + * framework with process_capture_result(). + */ + int status; + + /** + * The acquire sync fence for this buffer. The HAL must wait on this fence + * fd before attempting to read from or write to this buffer. + * + * The framework may be set to -1 to indicate that no waiting is necessary + * for this buffer. + * + * When the HAL returns an output buffer to the framework with + * process_capture_result(), the acquire_fence must be set to -1. If the HAL + * never waits on the acquire_fence due to an error in filling a buffer, + * when calling process_capture_result() the HAL must set the release_fence + * of the buffer to be the acquire_fence passed to it by the framework. This + * will allow the framework to wait on the fence before reusing the buffer. + * + * For input buffers, the HAL must not change the acquire_fence field during + * the process_capture_request() call. + * + * >= CAMERA_DEVICE_API_VERSION_3_2: + * + * When the HAL returns an input buffer to the framework with + * process_capture_result(), the acquire_fence must be set to -1. If the HAL + * never waits on input buffer acquire fence due to an error, the sync + * fences should be handled similarly to the way they are handled for output + * buffers. + */ + int acquire_fence; + + /** + * The release sync fence for this buffer. The HAL must set this fence when + * returning buffers to the framework, or write -1 to indicate that no + * waiting is required for this buffer. + * + * For the output buffers, the fences must be set in the output_buffers + * array passed to process_capture_result(). + * + * <= CAMERA_DEVICE_API_VERSION_3_1: + * + * For the input buffer, the release fence must be set by the + * process_capture_request() call. + * + * >= CAMERA_DEVICE_API_VERSION_3_2: + * + * For the input buffer, the fences must be set in the input_buffer + * passed to process_capture_result(). + * + * After signaling the release_fence for this buffer, the HAL + * should not make any further attempts to access this buffer as the + * ownership has been fully transferred back to the framework. + * + * If a fence of -1 was specified then the ownership of this buffer + * is transferred back immediately upon the call of process_capture_result. + */ + int release_fence; + +} camera3_stream_buffer_t; + +/** + * camera3_stream_buffer_set_t: + * + * The complete set of gralloc buffers for a stream. This structure is given to + * register_stream_buffers() to allow the camera HAL device to register/map/etc + * newly allocated stream buffers. + * + * >= CAMERA_DEVICE_API_VERSION_3_2: + * + * Deprecated (and not used). In particular, + * register_stream_buffers is also deprecated and will never be invoked. + * + */ +typedef struct camera3_stream_buffer_set { + /** + * The stream handle for the stream these buffers belong to + */ + camera3_stream_t *stream; + + /** + * The number of buffers in this stream. It is guaranteed to be at least + * stream->max_buffers. + */ + uint32_t num_buffers; + + /** + * The array of gralloc buffer handles for this stream. If the stream format + * is set to HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, the camera HAL device + * should inspect the passed-in buffers to determine any platform-private + * pixel format information. + */ + buffer_handle_t **buffers; + +} camera3_stream_buffer_set_t; + +/** + * camera3_jpeg_blob: + * + * Transport header for compressed JPEG buffers in output streams. + * + * To capture JPEG images, a stream is created using the pixel format + * HAL_PIXEL_FORMAT_BLOB. The buffer size for the stream is calculated by the + * framework, based on the static metadata field android.jpeg.maxSize. Since + * compressed JPEG images are of variable size, the HAL needs to include the + * final size of the compressed image using this structure inside the output + * stream buffer. The JPEG blob ID field must be set to CAMERA3_JPEG_BLOB_ID. + * + * Transport header should be at the end of the JPEG output stream buffer. That + * means the jpeg_blob_id must start at byte[buffer_size - + * sizeof(camera3_jpeg_blob)], where the buffer_size is the size of gralloc buffer. + * Any HAL using this transport header must account for it in android.jpeg.maxSize + * The JPEG data itself starts at the beginning of the buffer and should be + * jpeg_size bytes long. + */ +typedef struct camera3_jpeg_blob { + uint16_t jpeg_blob_id; + uint32_t jpeg_size; +} camera3_jpeg_blob_t; + +enum { + CAMERA3_JPEG_BLOB_ID = 0x00FF +}; + +/********************************************************************** + * + * Message definitions for the HAL notify() callback. + * + * These definitions are used for the HAL notify callback, to signal + * asynchronous events from the HAL device to the Android framework. + * + */ + +/** + * camera3_msg_type: + * + * Indicates the type of message sent, which specifies which member of the + * message union is valid. + * + */ +typedef enum camera3_msg_type { + /** + * An error has occurred. camera3_notify_msg.message.error contains the + * error information. + */ + CAMERA3_MSG_ERROR = 1, + + /** + * The exposure of a given request or processing a reprocess request has + * begun. camera3_notify_msg.message.shutter contains the information + * the capture. + */ + CAMERA3_MSG_SHUTTER = 2, + + /** + * Number of framework message types + */ + CAMERA3_NUM_MESSAGES + +} camera3_msg_type_t; + +/** + * Defined error codes for CAMERA_MSG_ERROR + */ +typedef enum camera3_error_msg_code { + /** + * A serious failure occured. No further frames or buffer streams will + * be produced by the device. Device should be treated as closed. The + * client must reopen the device to use it again. The frame_number field + * is unused. + */ + CAMERA3_MSG_ERROR_DEVICE = 1, + + /** + * An error has occurred in processing a request. No output (metadata or + * buffers) will be produced for this request. The frame_number field + * specifies which request has been dropped. Subsequent requests are + * unaffected, and the device remains operational. + */ + CAMERA3_MSG_ERROR_REQUEST = 2, + + /** + * An error has occurred in producing an output result metadata buffer + * for a request, but output stream buffers for it will still be + * available. Subsequent requests are unaffected, and the device remains + * operational. The frame_number field specifies the request for which + * result metadata won't be available. + */ + CAMERA3_MSG_ERROR_RESULT = 3, + + /** + * An error has occurred in placing an output buffer into a stream for a + * request. The frame metadata and other buffers may still be + * available. Subsequent requests are unaffected, and the device remains + * operational. The frame_number field specifies the request for which the + * buffer was dropped, and error_stream contains a pointer to the stream + * that dropped the frame.u + */ + CAMERA3_MSG_ERROR_BUFFER = 4, + + /** + * Number of error types + */ + CAMERA3_MSG_NUM_ERRORS + +} camera3_error_msg_code_t; + +/** + * camera3_error_msg_t: + * + * Message contents for CAMERA3_MSG_ERROR + */ +typedef struct camera3_error_msg { + /** + * Frame number of the request the error applies to. 0 if the frame number + * isn't applicable to the error. + */ + uint32_t frame_number; + + /** + * Pointer to the stream that had a failure. NULL if the stream isn't + * applicable to the error. + */ + camera3_stream_t *error_stream; + + /** + * The code for this error; one of the CAMERA_MSG_ERROR enum values. + */ + int error_code; + +} camera3_error_msg_t; + +/** + * camera3_shutter_msg_t: + * + * Message contents for CAMERA3_MSG_SHUTTER + */ +typedef struct camera3_shutter_msg { + /** + * Frame number of the request that has begun exposure or reprocessing. + */ + uint32_t frame_number; + + /** + * Timestamp for the start of capture. For a reprocess request, this must + * be input image's start of capture. This must match the capture result + * metadata's sensor exposure start timestamp. + */ + uint64_t timestamp; + +} camera3_shutter_msg_t; + +/** + * camera3_notify_msg_t: + * + * The message structure sent to camera3_callback_ops_t.notify() + */ +typedef struct camera3_notify_msg { + + /** + * The message type. One of camera3_notify_msg_type, or a private extension. + */ + int type; + + union { + /** + * Error message contents. Valid if type is CAMERA3_MSG_ERROR + */ + camera3_error_msg_t error; + + /** + * Shutter message contents. Valid if type is CAMERA3_MSG_SHUTTER + */ + camera3_shutter_msg_t shutter; + + /** + * Generic message contents. Used to ensure a minimum size for custom + * message types. + */ + uint8_t generic[32]; + } message; + +} camera3_notify_msg_t; + +/********************************************************************** + * + * Capture request/result definitions for the HAL process_capture_request() + * method, and the process_capture_result() callback. + * + */ + +/** + * camera3_request_template_t: + * + * Available template types for + * camera3_device_ops.construct_default_request_settings() + */ +typedef enum camera3_request_template { + /** + * Standard camera preview operation with 3A on auto. + */ + CAMERA3_TEMPLATE_PREVIEW = 1, + + /** + * Standard camera high-quality still capture with 3A and flash on auto. + */ + CAMERA3_TEMPLATE_STILL_CAPTURE = 2, + + /** + * Standard video recording plus preview with 3A on auto, torch off. + */ + CAMERA3_TEMPLATE_VIDEO_RECORD = 3, + + /** + * High-quality still capture while recording video. Application will + * include preview, video record, and full-resolution YUV or JPEG streams in + * request. Must not cause stuttering on video stream. 3A on auto. + */ + CAMERA3_TEMPLATE_VIDEO_SNAPSHOT = 4, + + /** + * Zero-shutter-lag mode. Application will request preview and + * full-resolution data for each frame, and reprocess it to JPEG when a + * still image is requested by user. Settings should provide highest-quality + * full-resolution images without compromising preview frame rate. 3A on + * auto. + */ + CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG = 5, + + /** + * A basic template for direct application control of capture + * parameters. All automatic control is disabled (auto-exposure, auto-white + * balance, auto-focus), and post-processing parameters are set to preview + * quality. The manual capture parameters (exposure, sensitivity, etc.) + * are set to reasonable defaults, but should be overridden by the + * application depending on the intended use case. + */ + CAMERA3_TEMPLATE_MANUAL = 6, + + /* Total number of templates */ + CAMERA3_TEMPLATE_COUNT, + + /** + * First value for vendor-defined request templates + */ + CAMERA3_VENDOR_TEMPLATE_START = 0x40000000 + +} camera3_request_template_t; + +/** + * camera3_capture_request_t: + * + * A single request for image capture/buffer reprocessing, sent to the Camera + * HAL device by the framework in process_capture_request(). + * + * The request contains the settings to be used for this capture, and the set of + * output buffers to write the resulting image data in. It may optionally + * contain an input buffer, in which case the request is for reprocessing that + * input buffer instead of capturing a new image with the camera sensor. The + * capture is identified by the frame_number. + * + * In response, the camera HAL device must send a camera3_capture_result + * structure asynchronously to the framework, using the process_capture_result() + * callback. + */ +typedef struct camera3_capture_request { + /** + * The frame number is an incrementing integer set by the framework to + * uniquely identify this capture. It needs to be returned in the result + * call, and is also used to identify the request in asynchronous + * notifications sent to camera3_callback_ops_t.notify(). + */ + uint32_t frame_number; + + /** + * The settings buffer contains the capture and processing parameters for + * the request. As a special case, a NULL settings buffer indicates that the + * settings are identical to the most-recently submitted capture request. A + * NULL buffer cannot be used as the first submitted request after a + * configure_streams() call. + */ + const camera_metadata_t *settings; + + /** + * The input stream buffer to use for this request, if any. + * + * If input_buffer is NULL, then the request is for a new capture from the + * imager. If input_buffer is valid, the request is for reprocessing the + * image contained in input_buffer. + * + * In the latter case, the HAL must set the release_fence of the + * input_buffer to a valid sync fence, or to -1 if the HAL does not support + * sync, before process_capture_request() returns. + * + * The HAL is required to wait on the acquire sync fence of the input buffer + * before accessing it. + * + * <= CAMERA_DEVICE_API_VERSION_3_1: + * + * Any input buffer included here will have been registered with the HAL + * through register_stream_buffers() before its inclusion in a request. + * + * >= CAMERA_DEVICE_API_VERSION_3_2: + * + * The buffers will not have been pre-registered with the HAL. + * Subsequent requests may reuse buffers, or provide entirely new buffers. + */ + camera3_stream_buffer_t *input_buffer; + + /** + * The number of output buffers for this capture request. Must be at least + * 1. + */ + uint32_t num_output_buffers; + + /** + * An array of num_output_buffers stream buffers, to be filled with image + * data from this capture/reprocess. The HAL must wait on the acquire fences + * of each stream buffer before writing to them. + * + * The HAL takes ownership of the actual buffer_handle_t entries in + * output_buffers; the framework does not access them until they are + * returned in a camera3_capture_result_t. + * + * <= CAMERA_DEVICE_API_VERSION_3_1: + * + * All the buffers included here will have been registered with the HAL + * through register_stream_buffers() before their inclusion in a request. + * + * >= CAMERA_DEVICE_API_VERSION_3_2: + * + * Any or all of the buffers included here may be brand new in this + * request (having never before seen by the HAL). + */ + const camera3_stream_buffer_t *output_buffers; + +} camera3_capture_request_t; + +/** + * camera3_capture_result_t: + * + * The result of a single capture/reprocess by the camera HAL device. This is + * sent to the framework asynchronously with process_capture_result(), in + * response to a single capture request sent to the HAL with + * process_capture_request(). Multiple process_capture_result() calls may be + * performed by the HAL for each request. + * + * Each call, all with the same frame + * number, may contain some subset of the output buffers, and/or the result + * metadata. The metadata may only be provided once for a given frame number; + * all other calls must set the result metadata to NULL. + * + * The result structure contains the output metadata from this capture, and the + * set of output buffers that have been/will be filled for this capture. Each + * output buffer may come with a release sync fence that the framework will wait + * on before reading, in case the buffer has not yet been filled by the HAL. + * + * >= CAMERA_DEVICE_API_VERSION_3_2: + * + * The metadata may be provided multiple times for a single frame number. The + * framework will accumulate together the final result set by combining each + * partial result together into the total result set. + * + * If an input buffer is given in a request, the HAL must return it in one of + * the process_capture_result calls, and the call may be to just return the input + * buffer, without metadata and output buffers; the sync fences must be handled + * the same way they are done for output buffers. + * + * + * Performance considerations: + * + * Applications will also receive these partial results immediately, so sending + * partial results is a highly recommended performance optimization to avoid + * the total pipeline latency before sending the results for what is known very + * early on in the pipeline. + * + * A typical use case might be calculating the AF state halfway through the + * pipeline; by sending the state back to the framework immediately, we get a + * 50% performance increase and perceived responsiveness of the auto-focus. + * + */ +typedef struct camera3_capture_result { + /** + * The frame number is an incrementing integer set by the framework in the + * submitted request to uniquely identify this capture. It is also used to + * identify the request in asynchronous notifications sent to + * camera3_callback_ops_t.notify(). + */ + uint32_t frame_number; + + /** + * The result metadata for this capture. This contains information about the + * final capture parameters, the state of the capture and post-processing + * hardware, the state of the 3A algorithms, if enabled, and the output of + * any enabled statistics units. + * + * Only one call to process_capture_result() with a given frame_number may + * include the result metadata. All other calls for the same frame_number + * must set this to NULL. + * + * If there was an error producing the result metadata, result must be an + * empty metadata buffer, and notify() must be called with ERROR_RESULT. + * + * >= CAMERA_DEVICE_API_VERSION_3_2: + * + * Multiple calls to process_capture_result() with a given frame_number + * may include the result metadata. + * + * Partial metadata submitted should not include any metadata key returned + * in a previous partial result for a given frame. Each new partial result + * for that frame must also set a distinct partial_result value. + * + * If notify has been called with ERROR_RESULT, all further partial + * results for that frame are ignored by the framework. + */ + const camera_metadata_t *result; + + /** + * The number of output buffers returned in this result structure. Must be + * less than or equal to the matching capture request's count. If this is + * less than the buffer count in the capture request, at least one more call + * to process_capture_result with the same frame_number must be made, to + * return the remaining output buffers to the framework. This may only be + * zero if the structure includes valid result metadata or an input buffer + * is returned in this result. + */ + uint32_t num_output_buffers; + + /** + * The handles for the output stream buffers for this capture. They may not + * yet be filled at the time the HAL calls process_capture_result(); the + * framework will wait on the release sync fences provided by the HAL before + * reading the buffers. + * + * The HAL must set the stream buffer's release sync fence to a valid sync + * fd, or to -1 if the buffer has already been filled. + * + * If the HAL encounters an error while processing the buffer, and the + * buffer is not filled, the buffer's status field must be set to + * CAMERA3_BUFFER_STATUS_ERROR. If the HAL did not wait on the acquire fence + * before encountering the error, the acquire fence should be copied into + * the release fence, to allow the framework to wait on the fence before + * reusing the buffer. + * + * The acquire fence must be set to -1 for all output buffers. If + * num_output_buffers is zero, this may be NULL. In that case, at least one + * more process_capture_result call must be made by the HAL to provide the + * output buffers. + * + * When process_capture_result is called with a new buffer for a frame, + * all previous frames' buffers for that corresponding stream must have been + * already delivered (the fences need not have yet been signaled). + * + * >= CAMERA_DEVICE_API_VERSION_3_2: + * + * Gralloc buffers for a frame may be sent to framework before the + * corresponding SHUTTER-notify. + * + * Performance considerations: + * + * Buffers delivered to the framework will not be dispatched to the + * application layer until a start of exposure timestamp has been received + * via a SHUTTER notify() call. It is highly recommended to + * dispatch that call as early as possible. + */ + const camera3_stream_buffer_t *output_buffers; + + /** + * >= CAMERA_DEVICE_API_VERSION_3_2: + * + * The handle for the input stream buffer for this capture. It may not + * yet be consumed at the time the HAL calls process_capture_result(); the + * framework will wait on the release sync fences provided by the HAL before + * reusing the buffer. + * + * The HAL should handle the sync fences the same way they are done for + * output_buffers. + * + * Only one input buffer is allowed to be sent per request. Similarly to + * output buffers, the ordering of returned input buffers must be + * maintained by the HAL. + * + * Performance considerations: + * + * The input buffer should be returned as early as possible. If the HAL + * supports sync fences, it can call process_capture_result to hand it back + * with sync fences being set appropriately. If the sync fences are not + * supported, the buffer can only be returned when it is consumed, which + * may take long time; the HAL may choose to copy this input buffer to make + * the buffer return sooner. + */ + const camera3_stream_buffer_t *input_buffer; + + /** + * >= CAMERA_DEVICE_API_VERSION_3_2: + * + * In order to take advantage of partial results, the HAL must set the + * static metadata android.request.partialResultCount to the number of + * partial results it will send for each frame. + * + * Each new capture result with a partial result must set + * this field (partial_result) to a distinct inclusive value between + * 1 and android.request.partialResultCount. + * + * HALs not wishing to take advantage of this feature must not + * set an android.request.partialResultCount or partial_result to a value + * other than 1. + * + * This value must be set to 0 when a capture result contains buffers only + * and no metadata. + */ + uint32_t partial_result; + +} camera3_capture_result_t; + +/********************************************************************** + * + * Callback methods for the HAL to call into the framework. + * + * These methods are used to return metadata and image buffers for a completed + * or failed captures, and to notify the framework of asynchronous events such + * as errors. + * + * The framework will not call back into the HAL from within these callbacks, + * and these calls will not block for extended periods. + * + */ +typedef struct camera3_callback_ops { + + /** + * process_capture_result: + * + * Send results from a completed capture to the framework. + * process_capture_result() may be invoked multiple times by the HAL in + * response to a single capture request. This allows, for example, the + * metadata and low-resolution buffers to be returned in one call, and + * post-processed JPEG buffers in a later call, once it is available. Each + * call must include the frame number of the request it is returning + * metadata or buffers for. + * + * A component (buffer or metadata) of the complete result may only be + * included in one process_capture_result call. A buffer for each stream, + * and the result metadata, must be returned by the HAL for each request in + * one of the process_capture_result calls, even in case of errors producing + * some of the output. A call to process_capture_result() with neither + * output buffers or result metadata is not allowed. + * + * The order of returning metadata and buffers for a single result does not + * matter, but buffers for a given stream must be returned in FIFO order. So + * the buffer for request 5 for stream A must always be returned before the + * buffer for request 6 for stream A. This also applies to the result + * metadata; the metadata for request 5 must be returned before the metadata + * for request 6. + * + * However, different streams are independent of each other, so it is + * acceptable and expected that the buffer for request 5 for stream A may be + * returned after the buffer for request 6 for stream B is. And it is + * acceptable that the result metadata for request 6 for stream B is + * returned before the buffer for request 5 for stream A is. + * + * The HAL retains ownership of result structure, which only needs to be + * valid to access during this call. The framework will copy whatever it + * needs before this call returns. + * + * The output buffers do not need to be filled yet; the framework will wait + * on the stream buffer release sync fence before reading the buffer + * data. Therefore, this method should be called by the HAL as soon as + * possible, even if some or all of the output buffers are still in + * being filled. The HAL must include valid release sync fences into each + * output_buffers stream buffer entry, or -1 if that stream buffer is + * already filled. + * + * If the result buffer cannot be constructed for a request, the HAL should + * return an empty metadata buffer, but still provide the output buffers and + * their sync fences. In addition, notify() must be called with an + * ERROR_RESULT message. + * + * If an output buffer cannot be filled, its status field must be set to + * STATUS_ERROR. In addition, notify() must be called with a ERROR_BUFFER + * message. + * + * If the entire capture has failed, then this method still needs to be + * called to return the output buffers to the framework. All the buffer + * statuses should be STATUS_ERROR, and the result metadata should be an + * empty buffer. In addition, notify() must be called with a ERROR_REQUEST + * message. In this case, individual ERROR_RESULT/ERROR_BUFFER messages + * should not be sent. + * + * Performance requirements: + * + * This is a non-blocking call. The framework will return this call in 5ms. + * + * The pipeline latency (see S7 for definition) should be less than or equal to + * 4 frame intervals, and must be less than or equal to 8 frame intervals. + * + */ + void (*process_capture_result)(const struct camera3_callback_ops *, + const camera3_capture_result_t *result); + + /** + * notify: + * + * Asynchronous notification callback from the HAL, fired for various + * reasons. Only for information independent of frame capture, or that + * require specific timing. The ownership of the message structure remains + * with the HAL, and the msg only needs to be valid for the duration of this + * call. + * + * Multiple threads may call notify() simultaneously. + * + * <= CAMERA_DEVICE_API_VERSION_3_1: + * + * The notification for the start of exposure for a given request must be + * sent by the HAL before the first call to process_capture_result() for + * that request is made. + * + * >= CAMERA_DEVICE_API_VERSION_3_2: + * + * Buffers delivered to the framework will not be dispatched to the + * application layer until a start of exposure timestamp (or input image's + * start of exposure timestamp for a reprocess request) has been received + * via a SHUTTER notify() call. It is highly recommended to dispatch this + * call as early as possible. + * + * ------------------------------------------------------------------------ + * Performance requirements: + * + * This is a non-blocking call. The framework will return this call in 5ms. + */ + void (*notify)(const struct camera3_callback_ops *, + const camera3_notify_msg_t *msg); + +} camera3_callback_ops_t; + +/********************************************************************** + * + * Camera device operations + * + */ +typedef struct camera3_device_ops { + + /** + * initialize: + * + * One-time initialization to pass framework callback function pointers to + * the HAL. Will be called once after a successful open() call, before any + * other functions are called on the camera3_device_ops structure. + * + * Performance requirements: + * + * This should be a non-blocking call. The HAL should return from this call + * in 5ms, and must return from this call in 10ms. + * + * Return values: + * + * 0: On successful initialization + * + * -ENODEV: If initialization fails. Only close() can be called successfully + * by the framework after this. + */ + int (*initialize)(const struct camera3_device *, + const camera3_callback_ops_t *callback_ops); + + /********************************************************************** + * Stream management + */ + + /** + * configure_streams: + * + * CAMERA_DEVICE_API_VERSION_3_0 only: + * + * Reset the HAL camera device processing pipeline and set up new input and + * output streams. This call replaces any existing stream configuration with + * the streams defined in the stream_list. This method will be called at + * least once after initialize() before a request is submitted with + * process_capture_request(). + * + * The stream_list must contain at least one output-capable stream, and may + * not contain more than one input-capable stream. + * + * The stream_list may contain streams that are also in the currently-active + * set of streams (from the previous call to configure_stream()). These + * streams will already have valid values for usage, max_buffers, and the + * private pointer. + * + * If such a stream has already had its buffers registered, + * register_stream_buffers() will not be called again for the stream, and + * buffers from the stream can be immediately included in input requests. + * + * If the HAL needs to change the stream configuration for an existing + * stream due to the new configuration, it may rewrite the values of usage + * and/or max_buffers during the configure call. + * + * The framework will detect such a change, and will then reallocate the + * stream buffers, and call register_stream_buffers() again before using + * buffers from that stream in a request. + * + * If a currently-active stream is not included in stream_list, the HAL may + * safely remove any references to that stream. It will not be reused in a + * later configure() call by the framework, and all the gralloc buffers for + * it will be freed after the configure_streams() call returns. + * + * The stream_list structure is owned by the framework, and may not be + * accessed once this call completes. The address of an individual + * camera3_stream_t structure will remain valid for access by the HAL until + * the end of the first configure_stream() call which no longer includes + * that camera3_stream_t in the stream_list argument. The HAL may not change + * values in the stream structure outside of the private pointer, except for + * the usage and max_buffers members during the configure_streams() call + * itself. + * + * If the stream is new, the usage, max_buffer, and private pointer fields + * of the stream structure will all be set to 0. The HAL device must set + * these fields before the configure_streams() call returns. These fields + * are then used by the framework and the platform gralloc module to + * allocate the gralloc buffers for each stream. + * + * Before such a new stream can have its buffers included in a capture + * request, the framework will call register_stream_buffers() with that + * stream. However, the framework is not required to register buffers for + * _all_ streams before submitting a request. This allows for quick startup + * of (for example) a preview stream, with allocation for other streams + * happening later or concurrently. + * + * ------------------------------------------------------------------------ + * CAMERA_DEVICE_API_VERSION_3_1 only: + * + * Reset the HAL camera device processing pipeline and set up new input and + * output streams. This call replaces any existing stream configuration with + * the streams defined in the stream_list. This method will be called at + * least once after initialize() before a request is submitted with + * process_capture_request(). + * + * The stream_list must contain at least one output-capable stream, and may + * not contain more than one input-capable stream. + * + * The stream_list may contain streams that are also in the currently-active + * set of streams (from the previous call to configure_stream()). These + * streams will already have valid values for usage, max_buffers, and the + * private pointer. + * + * If such a stream has already had its buffers registered, + * register_stream_buffers() will not be called again for the stream, and + * buffers from the stream can be immediately included in input requests. + * + * If the HAL needs to change the stream configuration for an existing + * stream due to the new configuration, it may rewrite the values of usage + * and/or max_buffers during the configure call. + * + * The framework will detect such a change, and will then reallocate the + * stream buffers, and call register_stream_buffers() again before using + * buffers from that stream in a request. + * + * If a currently-active stream is not included in stream_list, the HAL may + * safely remove any references to that stream. It will not be reused in a + * later configure() call by the framework, and all the gralloc buffers for + * it will be freed after the configure_streams() call returns. + * + * The stream_list structure is owned by the framework, and may not be + * accessed once this call completes. The address of an individual + * camera3_stream_t structure will remain valid for access by the HAL until + * the end of the first configure_stream() call which no longer includes + * that camera3_stream_t in the stream_list argument. The HAL may not change + * values in the stream structure outside of the private pointer, except for + * the usage and max_buffers members during the configure_streams() call + * itself. + * + * If the stream is new, max_buffer, and private pointer fields of the + * stream structure will all be set to 0. The usage will be set to the + * consumer usage flags. The HAL device must set these fields before the + * configure_streams() call returns. These fields are then used by the + * framework and the platform gralloc module to allocate the gralloc + * buffers for each stream. + * + * Before such a new stream can have its buffers included in a capture + * request, the framework will call register_stream_buffers() with that + * stream. However, the framework is not required to register buffers for + * _all_ streams before submitting a request. This allows for quick startup + * of (for example) a preview stream, with allocation for other streams + * happening later or concurrently. + * + * ------------------------------------------------------------------------ + * >= CAMERA_DEVICE_API_VERSION_3_2: + * + * Reset the HAL camera device processing pipeline and set up new input and + * output streams. This call replaces any existing stream configuration with + * the streams defined in the stream_list. This method will be called at + * least once after initialize() before a request is submitted with + * process_capture_request(). + * + * The stream_list must contain at least one output-capable stream, and may + * not contain more than one input-capable stream. + * + * The stream_list may contain streams that are also in the currently-active + * set of streams (from the previous call to configure_stream()). These + * streams will already have valid values for usage, max_buffers, and the + * private pointer. + * + * If the HAL needs to change the stream configuration for an existing + * stream due to the new configuration, it may rewrite the values of usage + * and/or max_buffers during the configure call. + * + * The framework will detect such a change, and may then reallocate the + * stream buffers before using buffers from that stream in a request. + * + * If a currently-active stream is not included in stream_list, the HAL may + * safely remove any references to that stream. It will not be reused in a + * later configure() call by the framework, and all the gralloc buffers for + * it will be freed after the configure_streams() call returns. + * + * The stream_list structure is owned by the framework, and may not be + * accessed once this call completes. The address of an individual + * camera3_stream_t structure will remain valid for access by the HAL until + * the end of the first configure_stream() call which no longer includes + * that camera3_stream_t in the stream_list argument. The HAL may not change + * values in the stream structure outside of the private pointer, except for + * the usage and max_buffers members during the configure_streams() call + * itself. + * + * If the stream is new, max_buffer, and private pointer fields of the + * stream structure will all be set to 0. The usage will be set to the + * consumer usage flags. The HAL device must set these fields before the + * configure_streams() call returns. These fields are then used by the + * framework and the platform gralloc module to allocate the gralloc + * buffers for each stream. + * + * Newly allocated buffers may be included in a capture request at any time + * by the framework. Once a gralloc buffer is returned to the framework + * with process_capture_result (and its respective release_fence has been + * signaled) the framework may free or reuse it at any time. + * + * ------------------------------------------------------------------------ + * + * Preconditions: + * + * The framework will only call this method when no captures are being + * processed. That is, all results have been returned to the framework, and + * all in-flight input and output buffers have been returned and their + * release sync fences have been signaled by the HAL. The framework will not + * submit new requests for capture while the configure_streams() call is + * underway. + * + * Postconditions: + * + * The HAL device must configure itself to provide maximum possible output + * frame rate given the sizes and formats of the output streams, as + * documented in the camera device's static metadata. + * + * Performance requirements: + * + * This call is expected to be heavyweight and possibly take several hundred + * milliseconds to complete, since it may require resetting and + * reconfiguring the image sensor and the camera processing pipeline. + * Nevertheless, the HAL device should attempt to minimize the + * reconfiguration delay to minimize the user-visible pauses during + * application operational mode changes (such as switching from still + * capture to video recording). + * + * The HAL should return from this call in 500ms, and must return from this + * call in 1000ms. + * + * Return values: + * + * 0: On successful stream configuration + * + * -EINVAL: If the requested stream configuration is invalid. Some examples + * of invalid stream configurations include: + * + * - Including more than 1 input-capable stream (INPUT or + * BIDIRECTIONAL) + * + * - Not including any output-capable streams (OUTPUT or + * BIDIRECTIONAL) + * + * - Including streams with unsupported formats, or an unsupported + * size for that format. + * + * - Including too many output streams of a certain format. + * + * - Unsupported rotation configuration (only applies to + * devices with version >= CAMERA_DEVICE_API_VERSION_3_3) + * + * - Stream sizes/formats don't satisfy the + * camera3_stream_configuration_t->operation_mode requirements for non-NORMAL mode, + * or the requested operation_mode is not supported by the HAL. + * (only applies to devices with version >= CAMERA_DEVICE_API_VERSION_3_3) + * + * Note that the framework submitting an invalid stream + * configuration is not normal operation, since stream + * configurations are checked before configure. An invalid + * configuration means that a bug exists in the framework code, or + * there is a mismatch between the HAL's static metadata and the + * requirements on streams. + * + * -ENODEV: If there has been a fatal error and the device is no longer + * operational. Only close() can be called successfully by the + * framework after this error is returned. + */ + int (*configure_streams)(const struct camera3_device *, + camera3_stream_configuration_t *stream_list); + + /** + * register_stream_buffers: + * + * >= CAMERA_DEVICE_API_VERSION_3_2: + * + * DEPRECATED. This will not be called and must be set to NULL. + * + * <= CAMERA_DEVICE_API_VERSION_3_1: + * + * Register buffers for a given stream with the HAL device. This method is + * called by the framework after a new stream is defined by + * configure_streams, and before buffers from that stream are included in a + * capture request. If the same stream is listed in a subsequent + * configure_streams() call, register_stream_buffers will _not_ be called + * again for that stream. + * + * The framework does not need to register buffers for all configured + * streams before it submits the first capture request. This allows quick + * startup for preview (or similar use cases) while other streams are still + * being allocated. + * + * This method is intended to allow the HAL device to map or otherwise + * prepare the buffers for later use. The buffers passed in will already be + * locked for use. At the end of the call, all the buffers must be ready to + * be returned to the stream. The buffer_set argument is only valid for the + * duration of this call. + * + * If the stream format was set to HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, + * the camera HAL should inspect the passed-in buffers here to determine any + * platform-private pixel format information. + * + * Performance requirements: + * + * This should be a non-blocking call. The HAL should return from this call + * in 1ms, and must return from this call in 5ms. + * + * Return values: + * + * 0: On successful registration of the new stream buffers + * + * -EINVAL: If the stream_buffer_set does not refer to a valid active + * stream, or if the buffers array is invalid. + * + * -ENOMEM: If there was a failure in registering the buffers. The framework + * must consider all the stream buffers to be unregistered, and can + * try to register again later. + * + * -ENODEV: If there is a fatal error, and the device is no longer + * operational. Only close() can be called successfully by the + * framework after this error is returned. + */ + int (*register_stream_buffers)(const struct camera3_device *, + const camera3_stream_buffer_set_t *buffer_set); + + /********************************************************************** + * Request creation and submission + */ + + /** + * construct_default_request_settings: + * + * Create capture settings for standard camera use cases. + * + * The device must return a settings buffer that is configured to meet the + * requested use case, which must be one of the CAMERA3_TEMPLATE_* + * enums. All request control fields must be included. + * + * The HAL retains ownership of this structure, but the pointer to the + * structure must be valid until the device is closed. The framework and the + * HAL may not modify the buffer once it is returned by this call. The same + * buffer may be returned for subsequent calls for the same template, or for + * other templates. + * + * Performance requirements: + * + * This should be a non-blocking call. The HAL should return from this call + * in 1ms, and must return from this call in 5ms. + * + * Return values: + * + * Valid metadata: On successful creation of a default settings + * buffer. + * + * NULL: In case of a fatal error. After this is returned, only + * the close() method can be called successfully by the + * framework. + */ + const camera_metadata_t* (*construct_default_request_settings)( + const struct camera3_device *, + int type); + + /** + * process_capture_request: + * + * Send a new capture request to the HAL. The HAL should not return from + * this call until it is ready to accept the next request to process. Only + * one call to process_capture_request() will be made at a time by the + * framework, and the calls will all be from the same thread. The next call + * to process_capture_request() will be made as soon as a new request and + * its associated buffers are available. In a normal preview scenario, this + * means the function will be called again by the framework almost + * instantly. + * + * The actual request processing is asynchronous, with the results of + * capture being returned by the HAL through the process_capture_result() + * call. This call requires the result metadata to be available, but output + * buffers may simply provide sync fences to wait on. Multiple requests are + * expected to be in flight at once, to maintain full output frame rate. + * + * The framework retains ownership of the request structure. It is only + * guaranteed to be valid during this call. The HAL device must make copies + * of the information it needs to retain for the capture processing. The HAL + * is responsible for waiting on and closing the buffers' fences and + * returning the buffer handles to the framework. + * + * The HAL must write the file descriptor for the input buffer's release + * sync fence into input_buffer->release_fence, if input_buffer is not + * NULL. If the HAL returns -1 for the input buffer release sync fence, the + * framework is free to immediately reuse the input buffer. Otherwise, the + * framework will wait on the sync fence before refilling and reusing the + * input buffer. + * + * >= CAMERA_DEVICE_API_VERSION_3_2: + * + * The input/output buffers provided by the framework in each request + * may be brand new (having never before seen by the HAL). + * + * ------------------------------------------------------------------------ + * Performance considerations: + * + * Handling a new buffer should be extremely lightweight and there should be + * no frame rate degradation or frame jitter introduced. + * + * This call must return fast enough to ensure that the requested frame + * rate can be sustained, especially for streaming cases (post-processing + * quality settings set to FAST). The HAL should return this call in 1 + * frame interval, and must return from this call in 4 frame intervals. + * + * Return values: + * + * 0: On a successful start to processing the capture request + * + * -EINVAL: If the input is malformed (the settings are NULL when not + * allowed, there are 0 output buffers, etc) and capture processing + * cannot start. Failures during request processing should be + * handled by calling camera3_callback_ops_t.notify(). In case of + * this error, the framework will retain responsibility for the + * stream buffers' fences and the buffer handles; the HAL should + * not close the fences or return these buffers with + * process_capture_result. + * + * -ENODEV: If the camera device has encountered a serious error. After this + * error is returned, only the close() method can be successfully + * called by the framework. + * + */ + int (*process_capture_request)(const struct camera3_device *, + camera3_capture_request_t *request); + + /********************************************************************** + * Miscellaneous methods + */ + + /** + * get_metadata_vendor_tag_ops: + * + * Get methods to query for vendor extension metadata tag information. The + * HAL should fill in all the vendor tag operation methods, or leave ops + * unchanged if no vendor tags are defined. + * + * The definition of vendor_tag_query_ops_t can be found in + * system/media/camera/include/system/camera_metadata.h. + * + * >= CAMERA_DEVICE_API_VERSION_3_2: + * DEPRECATED. This function has been deprecated and should be set to + * NULL by the HAL. Please implement get_vendor_tag_ops in camera_common.h + * instead. + */ + void (*get_metadata_vendor_tag_ops)(const struct camera3_device*, + vendor_tag_query_ops_t* ops); + + /** + * dump: + * + * Print out debugging state for the camera device. This will be called by + * the framework when the camera service is asked for a debug dump, which + * happens when using the dumpsys tool, or when capturing a bugreport. + * + * The passed-in file descriptor can be used to write debugging text using + * dprintf() or write(). The text should be in ASCII encoding only. + * + * Performance requirements: + * + * This must be a non-blocking call. The HAL should return from this call + * in 1ms, must return from this call in 10ms. This call must avoid + * deadlocks, as it may be called at any point during camera operation. + * Any synchronization primitives used (such as mutex locks or semaphores) + * should be acquired with a timeout. + */ + void (*dump)(const struct camera3_device *, int fd); + + /** + * flush: + * + * Flush all currently in-process captures and all buffers in the pipeline + * on the given device. The framework will use this to dump all state as + * quickly as possible in order to prepare for a configure_streams() call. + * + * No buffers are required to be successfully returned, so every buffer + * held at the time of flush() (whether successfully filled or not) may be + * returned with CAMERA3_BUFFER_STATUS_ERROR. Note the HAL is still allowed + * to return valid (CAMERA3_BUFFER_STATUS_OK) buffers during this call, + * provided they are successfully filled. + * + * All requests currently in the HAL are expected to be returned as soon as + * possible. Not-in-process requests should return errors immediately. Any + * interruptible hardware blocks should be stopped, and any uninterruptible + * blocks should be waited on. + * + * flush() may be called concurrently to process_capture_request(), with the expectation that + * process_capture_request will return quickly and the request submitted in that + * process_capture_request call is treated like all other in-flight requests. Due to + * concurrency issues, it is possible that from the HAL's point of view, a + * process_capture_request() call may be started after flush has been invoked but has not + * returned yet. If such a call happens before flush() returns, the HAL should treat the new + * capture request like other in-flight pending requests (see #4 below). + * + * More specifically, the HAL must follow below requirements for various cases: + * + * 1. For captures that are too late for the HAL to cancel/stop, and will be + * completed normally by the HAL; i.e. the HAL can send shutter/notify and + * process_capture_result and buffers as normal. + * + * 2. For pending requests that have not done any processing, the HAL must call notify + * CAMERA3_MSG_ERROR_REQUEST, and return all the output buffers with + * process_capture_result in the error state (CAMERA3_BUFFER_STATUS_ERROR). + * The HAL must not place the release fence into an error state, instead, + * the release fences must be set to the acquire fences passed by the framework, + * or -1 if they have been waited on by the HAL already. This is also the path + * to follow for any captures for which the HAL already called notify() with + * CAMERA3_MSG_SHUTTER but won't be producing any metadata/valid buffers for. + * After CAMERA3_MSG_ERROR_REQUEST, for a given frame, only process_capture_results with + * buffers in CAMERA3_BUFFER_STATUS_ERROR are allowed. No further notifys or + * process_capture_result with non-null metadata is allowed. + * + * 3. For partially completed pending requests that will not have all the output + * buffers or perhaps missing metadata, the HAL should follow below: + * + * 3.1. Call notify with CAMERA3_MSG_ERROR_RESULT if some of the expected result + * metadata (i.e. one or more partial metadata) won't be available for the capture. + * + * 3.2. Call notify with CAMERA3_MSG_ERROR_BUFFER for every buffer that won't + * be produced for the capture. + * + * 3.3 Call notify with CAMERA3_MSG_SHUTTER with the capture timestamp before + * any buffers/metadata are returned with process_capture_result. + * + * 3.4 For captures that will produce some results, the HAL must not call + * CAMERA3_MSG_ERROR_REQUEST, since that indicates complete failure. + * + * 3.5. Valid buffers/metadata should be passed to the framework as normal. + * + * 3.6. Failed buffers should be returned to the framework as described for case 2. + * But failed buffers do not have to follow the strict ordering valid buffers do, + * and may be out-of-order with respect to valid buffers. For example, if buffers + * A, B, C, D, E are sent, D and E are failed, then A, E, B, D, C is an acceptable + * return order. + * + * 3.7. For fully-missing metadata, calling CAMERA3_MSG_ERROR_RESULT is sufficient, no + * need to call process_capture_result with NULL metadata or equivalent. + * + * 4. If a flush() is invoked while a process_capture_request() invocation is active, that + * process call should return as soon as possible. In addition, if a process_capture_request() + * call is made after flush() has been invoked but before flush() has returned, the + * capture request provided by the late process_capture_request call should be treated like + * a pending request in case #2 above. + * + * flush() should only return when there are no more outstanding buffers or + * requests left in the HAL. The framework may call configure_streams (as + * the HAL state is now quiesced) or may issue new requests. + * + * Note that it's sufficient to only support fully-succeeded and fully-failed result cases. + * However, it is highly desirable to support the partial failure cases as well, as it + * could help improve the flush call overall performance. + * + * Performance requirements: + * + * The HAL should return from this call in 100ms, and must return from this + * call in 1000ms. And this call must not be blocked longer than pipeline + * latency (see S7 for definition). + * + * Version information: + * + * only available if device version >= CAMERA_DEVICE_API_VERSION_3_1. + * + * Return values: + * + * 0: On a successful flush of the camera HAL. + * + * -EINVAL: If the input is malformed (the device is not valid). + * + * -ENODEV: If the camera device has encountered a serious error. After this + * error is returned, only the close() method can be successfully + * called by the framework. + */ + int (*flush)(const struct camera3_device *); + + /* reserved for future use */ + void *reserved[8]; +} camera3_device_ops_t; + +/********************************************************************** + * + * Camera device definition + * + */ +typedef struct camera3_device { + /** + * common.version must equal CAMERA_DEVICE_API_VERSION_3_0 to identify this + * device as implementing version 3.0 of the camera device HAL. + * + * Performance requirements: + * + * Camera open (common.module->common.methods->open) should return in 200ms, and must return + * in 500ms. + * Camera close (common.close) should return in 200ms, and must return in 500ms. + * + */ + hw_device_t common; + camera3_device_ops_t *ops; + void *priv; +} camera3_device_t; + +__END_DECLS + +#endif /* #ifdef ANDROID_INCLUDE_CAMERA3_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/camera_common.h b/phonelibs/android_hardware_libhardware/include/hardware/camera_common.h new file mode 100644 index 0000000000..7658dd4062 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/camera_common.h @@ -0,0 +1,916 @@ +/* + * 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. + */ + +// FIXME: add well-defined names for cameras + +#ifndef ANDROID_INCLUDE_CAMERA_COMMON_H +#define ANDROID_INCLUDE_CAMERA_COMMON_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +__BEGIN_DECLS + +/** + * The id of this module + */ +#define CAMERA_HARDWARE_MODULE_ID "camera" + +/** + * Module versioning information for the Camera hardware module, based on + * camera_module_t.common.module_api_version. The two most significant hex + * digits represent the major version, and the two least significant represent + * the minor version. + * + ******************************************************************************* + * Versions: 0.X - 1.X [CAMERA_MODULE_API_VERSION_1_0] + * + * Camera modules that report these version numbers implement the initial + * camera module HAL interface. All camera devices openable through this + * module support only version 1 of the camera device HAL. The device_version + * and static_camera_characteristics fields of camera_info are not valid. Only + * the android.hardware.Camera API can be supported by this module and its + * devices. + * + ******************************************************************************* + * Version: 2.0 [CAMERA_MODULE_API_VERSION_2_0] + * + * Camera modules that report this version number implement the second version + * of the camera module HAL interface. Camera devices openable through this + * module may support either version 1.0 or version 2.0 of the camera device + * HAL interface. The device_version field of camera_info is always valid; the + * static_camera_characteristics field of camera_info is valid if the + * device_version field is 2.0 or higher. + * + ******************************************************************************* + * Version: 2.1 [CAMERA_MODULE_API_VERSION_2_1] + * + * This camera module version adds support for asynchronous callbacks to the + * framework from the camera HAL module, which is used to notify the framework + * about changes to the camera module state. Modules that provide a valid + * set_callbacks() method must report at least this version number. + * + ******************************************************************************* + * Version: 2.2 [CAMERA_MODULE_API_VERSION_2_2] + * + * This camera module version adds vendor tag support from the module, and + * deprecates the old vendor_tag_query_ops that were previously only + * accessible with a device open. + * + ******************************************************************************* + * Version: 2.3 [CAMERA_MODULE_API_VERSION_2_3] + * + * This camera module version adds open legacy camera HAL device support. + * Framework can use it to open the camera device as lower device HAL version + * HAL device if the same device can support multiple device API versions. + * The standard hardware module open call (common.methods->open) continues + * to open the camera device with the latest supported version, which is + * also the version listed in camera_info_t.device_version. + * + ******************************************************************************* + * Version: 2.4 [CAMERA_MODULE_API_VERSION_2_4] + * + * This camera module version adds below API changes: + * + * 1. Torch mode support. The framework can use it to turn on torch mode for + * any camera device that has a flash unit, without opening a camera device. The + * camera device has a higher priority accessing the flash unit than the camera + * module; opening a camera device will turn off the torch if it had been enabled + * through the module interface. When there are any resource conflicts, such as + * open() is called to open a camera device, the camera HAL module must notify the + * framework through the torch mode status callback that the torch mode has been + * turned off. + * + * 2. External camera (e.g. USB hot-plug camera) support. The API updates specify that + * the camera static info is only available when camera is connected and ready to + * use for external hot-plug cameras. Calls to get static info will be invalid + * calls when camera status is not CAMERA_DEVICE_STATUS_PRESENT. The frameworks + * will only count on device status change callbacks to manage the available external + * camera list. + * + * 3. Camera arbitration hints. This module version adds support for explicitly + * indicating the number of camera devices that can be simultaneously opened and used. + * To specify valid combinations of devices, the resource_cost and conflicting_devices + * fields should always be set in the camera_info structure returned by the + * get_camera_info call. + * + * 4. Module initialization method. This will be called by the camera service + * right after the HAL module is loaded, to allow for one-time initialization + * of the HAL. It is called before any other module methods are invoked. + */ + +/** + * Predefined macros for currently-defined version numbers + */ + +/** + * All module versions <= HARDWARE_MODULE_API_VERSION(1, 0xFF) must be treated + * as CAMERA_MODULE_API_VERSION_1_0 + */ +#define CAMERA_MODULE_API_VERSION_1_0 HARDWARE_MODULE_API_VERSION(1, 0) +#define CAMERA_MODULE_API_VERSION_2_0 HARDWARE_MODULE_API_VERSION(2, 0) +#define CAMERA_MODULE_API_VERSION_2_1 HARDWARE_MODULE_API_VERSION(2, 1) +#define CAMERA_MODULE_API_VERSION_2_2 HARDWARE_MODULE_API_VERSION(2, 2) +#define CAMERA_MODULE_API_VERSION_2_3 HARDWARE_MODULE_API_VERSION(2, 3) +#define CAMERA_MODULE_API_VERSION_2_4 HARDWARE_MODULE_API_VERSION(2, 4) + +#define CAMERA_MODULE_API_VERSION_CURRENT CAMERA_MODULE_API_VERSION_2_4 + +/** + * All device versions <= HARDWARE_DEVICE_API_VERSION(1, 0xFF) must be treated + * as CAMERA_DEVICE_API_VERSION_1_0 + */ +#define CAMERA_DEVICE_API_VERSION_1_0 HARDWARE_DEVICE_API_VERSION(1, 0) +#define CAMERA_DEVICE_API_VERSION_2_0 HARDWARE_DEVICE_API_VERSION(2, 0) +#define CAMERA_DEVICE_API_VERSION_2_1 HARDWARE_DEVICE_API_VERSION(2, 1) +#define CAMERA_DEVICE_API_VERSION_3_0 HARDWARE_DEVICE_API_VERSION(3, 0) +#define CAMERA_DEVICE_API_VERSION_3_1 HARDWARE_DEVICE_API_VERSION(3, 1) +#define CAMERA_DEVICE_API_VERSION_3_2 HARDWARE_DEVICE_API_VERSION(3, 2) +#define CAMERA_DEVICE_API_VERSION_3_3 HARDWARE_DEVICE_API_VERSION(3, 3) + +// Device version 3.3 is current, older HAL camera device versions are not +// recommended for new devices. +#define CAMERA_DEVICE_API_VERSION_CURRENT CAMERA_DEVICE_API_VERSION_3_3 + +/** + * Defined in /system/media/camera/include/system/camera_metadata.h + */ +typedef struct camera_metadata camera_metadata_t; + +typedef struct camera_info { + /** + * The direction that the camera faces to. See system/core/include/system/camera.h + * for camera facing definitions. + * + * Version information (based on camera_module_t.common.module_api_version): + * + * CAMERA_MODULE_API_VERSION_2_3 or lower: + * + * It should be CAMERA_FACING_BACK or CAMERA_FACING_FRONT. + * + * CAMERA_MODULE_API_VERSION_2_4 or higher: + * + * It should be CAMERA_FACING_BACK, CAMERA_FACING_FRONT or + * CAMERA_FACING_EXTERNAL. + */ + int facing; + + /** + * The orientation of the camera image. The value is the angle that the + * camera image needs to be rotated clockwise so it shows correctly on the + * display in its natural orientation. It should be 0, 90, 180, or 270. + * + * For example, suppose a device has a naturally tall screen. The + * back-facing camera sensor is mounted in landscape. You are looking at the + * screen. If the top side of the camera sensor is aligned with the right + * edge of the screen in natural orientation, the value should be 90. If the + * top side of a front-facing camera sensor is aligned with the right of the + * screen, the value should be 270. + * + * Version information (based on camera_module_t.common.module_api_version): + * + * CAMERA_MODULE_API_VERSION_2_3 or lower: + * + * Valid in all camera_module versions. + * + * CAMERA_MODULE_API_VERSION_2_4 or higher: + * + * Valid if camera facing is CAMERA_FACING_BACK or CAMERA_FACING_FRONT, + * not valid if camera facing is CAMERA_FACING_EXTERNAL. + */ + int orientation; + + /** + * The value of camera_device_t.common.version. + * + * Version information (based on camera_module_t.common.module_api_version): + * + * CAMERA_MODULE_API_VERSION_1_0: + * + * Not valid. Can be assumed to be CAMERA_DEVICE_API_VERSION_1_0. Do + * not read this field. + * + * CAMERA_MODULE_API_VERSION_2_0 or higher: + * + * Always valid + * + */ + uint32_t device_version; + + /** + * The camera's fixed characteristics, which include all static camera metadata + * specified in system/media/camera/docs/docs.html. This should be a sorted metadata + * buffer, and may not be modified or freed by the caller. The pointer should remain + * valid for the lifetime of the camera module, and values in it may not + * change after it is returned by get_camera_info(). + * + * Version information (based on camera_module_t.common.module_api_version): + * + * CAMERA_MODULE_API_VERSION_1_0: + * + * Not valid. Extra characteristics are not available. Do not read this + * field. + * + * CAMERA_MODULE_API_VERSION_2_0 or higher: + * + * Valid if device_version >= CAMERA_DEVICE_API_VERSION_2_0. Do not read + * otherwise. + * + */ + const camera_metadata_t *static_camera_characteristics; + + /** + * The total resource "cost" of using this camera, represented as an integer + * value in the range [0, 100] where 100 represents total usage of the shared + * resource that is the limiting bottleneck of the camera subsystem. This may + * be a very rough estimate, and is used as a hint to the camera service to + * determine when to disallow multiple applications from simultaneously + * opening different cameras advertised by the camera service. + * + * The camera service must be able to simultaneously open and use any + * combination of camera devices exposed by the HAL where the sum of + * the resource costs of these cameras is <= 100. For determining cost, + * each camera device must be assumed to be configured and operating at + * the maximally resource-consuming framerate and stream size settings + * available in the configuration settings exposed for that device through + * the camera metadata. + * + * The camera service may still attempt to simultaneously open combinations + * of camera devices with a total resource cost > 100. This may succeed or + * fail. If this succeeds, combinations of configurations that are not + * supported due to resource constraints from having multiple open devices + * should fail during the configure calls. If the total resource cost is + * <= 100, open and configure should never fail for any stream configuration + * settings or other device capabilities that would normally succeed for a + * device when it is the only open camera device. + * + * This field will be used to determine whether background applications are + * allowed to use this camera device while other applications are using other + * camera devices. Note: multiple applications will never be allowed by the + * camera service to simultaneously open the same camera device. + * + * Example use cases: + * + * Ex. 1: Camera Device 0 = Back Camera + * Camera Device 1 = Front Camera + * - Using both camera devices causes a large framerate slowdown due to + * limited ISP bandwidth. + * + * Configuration: + * + * Camera Device 0 - resource_cost = 51 + * conflicting_devices = null + * Camera Device 1 - resource_cost = 51 + * conflicting_devices = null + * + * Result: + * + * Since the sum of the resource costs is > 100, if a higher-priority + * application has either device open, no lower-priority applications will be + * allowed by the camera service to open either device. If a lower-priority + * application is using a device that a higher-priority subsequently attempts + * to open, the lower-priority application will be forced to disconnect the + * the device. + * + * If the highest-priority application chooses, it may still attempt to open + * both devices (since these devices are not listed as conflicting in the + * conflicting_devices fields), but usage of these devices may fail in the + * open or configure calls. + * + * Ex. 2: Camera Device 0 = Left Back Camera + * Camera Device 1 = Right Back Camera + * Camera Device 2 = Combined stereo camera using both right and left + * back camera sensors used by devices 0, and 1 + * Camera Device 3 = Front Camera + * - Due to do hardware constraints, up to two cameras may be open at once. The + * combined stereo camera may never be used at the same time as either of the + * two back camera devices (device 0, 1), and typically requires too much + * bandwidth to use at the same time as the front camera (device 3). + * + * Configuration: + * + * Camera Device 0 - resource_cost = 50 + * conflicting_devices = { 2 } + * Camera Device 1 - resource_cost = 50 + * conflicting_devices = { 2 } + * Camera Device 2 - resource_cost = 100 + * conflicting_devices = { 0, 1 } + * Camera Device 3 - resource_cost = 50 + * conflicting_devices = null + * + * Result: + * + * Based on the conflicting_devices fields, the camera service guarantees that + * the following sets of open devices will never be allowed: { 1, 2 }, { 0, 2 }. + * + * Based on the resource_cost fields, if a high-priority foreground application + * is using camera device 0, a background application would be allowed to open + * camera device 1 or 3 (but would be forced to disconnect it again if the + * foreground application opened another device). + * + * The highest priority application may still attempt to simultaneously open + * devices 0, 2, and 3, but the HAL may fail in open or configure calls for + * this combination. + * + * Ex. 3: Camera Device 0 = Back Camera + * Camera Device 1 = Front Camera + * Camera Device 2 = Low-power Front Camera that uses the same + * sensor as device 1, but only exposes image stream + * resolutions that can be used in low-power mode + * - Using both front cameras (device 1, 2) at the same time is impossible due + * a shared physical sensor. Using the back and "high-power" front camera + * (device 1) may be impossible for some stream configurations due to hardware + * limitations, but the "low-power" front camera option may always be used as + * it has special dedicated hardware. + * + * Configuration: + * + * Camera Device 0 - resource_cost = 100 + * conflicting_devices = null + * Camera Device 1 - resource_cost = 100 + * conflicting_devices = { 2 } + * Camera Device 2 - resource_cost = 0 + * conflicting_devices = { 1 } + * Result: + * + * Based on the conflicting_devices fields, the camera service guarantees that + * the following sets of open devices will never be allowed: { 1, 2 }. + * + * Based on the resource_cost fields, only the highest priority application + * may attempt to open both device 0 and 1 at the same time. If a higher-priority + * application is not using device 1 or 2, a low-priority background application + * may open device 2 (but will be forced to disconnect it if a higher-priority + * application subsequently opens device 1 or 2). + * + * Version information (based on camera_module_t.common.module_api_version): + * + * CAMERA_MODULE_API_VERSION_2_3 or lower: + * + * Not valid. Can be assumed to be 100. Do not read this field. + * + * CAMERA_MODULE_API_VERSION_2_4 or higher: + * + * Always valid. + */ + int resource_cost; + + /** + * An array of camera device IDs represented as NULL-terminated strings + * indicating other devices that cannot be simultaneously opened while this + * camera device is in use. + * + * This field is intended to be used to indicate that this camera device + * is a composite of several other camera devices, or otherwise has + * hardware dependencies that prohibit simultaneous usage. If there are no + * dependencies, a NULL may be returned in this field to indicate this. + * + * The camera service will never simultaneously open any of the devices + * in this list while this camera device is open. + * + * The strings pointed to in this field will not be cleaned up by the camera + * service, and must remain while this device is plugged in. + * + * Version information (based on camera_module_t.common.module_api_version): + * + * CAMERA_MODULE_API_VERSION_2_3 or lower: + * + * Not valid. Can be assumed to be NULL. Do not read this field. + * + * CAMERA_MODULE_API_VERSION_2_4 or higher: + * + * Always valid. + */ + char** conflicting_devices; + + /** + * The length of the array given in the conflicting_devices field. + * + * Version information (based on camera_module_t.common.module_api_version): + * + * CAMERA_MODULE_API_VERSION_2_3 or lower: + * + * Not valid. Can be assumed to be 0. Do not read this field. + * + * CAMERA_MODULE_API_VERSION_2_4 or higher: + * + * Always valid. + */ + size_t conflicting_devices_length; + +} camera_info_t; + +/** + * camera_device_status_t: + * + * The current status of the camera device, as provided by the HAL through the + * camera_module_callbacks.camera_device_status_change() call. + * + * At module load time, the framework will assume all camera devices are in the + * CAMERA_DEVICE_STATUS_PRESENT state. The HAL should invoke + * camera_module_callbacks::camera_device_status_change to inform the framework + * of any initially NOT_PRESENT devices. + * + * Allowed transitions: + * PRESENT -> NOT_PRESENT + * NOT_PRESENT -> ENUMERATING + * NOT_PRESENT -> PRESENT + * ENUMERATING -> PRESENT + * ENUMERATING -> NOT_PRESENT + */ +typedef enum camera_device_status { + /** + * The camera device is not currently connected, and opening it will return + * failure. + * + * Version information (based on camera_module_t.common.module_api_version): + * + * CAMERA_MODULE_API_VERSION_2_3 or lower: + * + * Calls to get_camera_info must still succeed, and provide the same information + * it would if the camera were connected. + * + * CAMERA_MODULE_API_VERSION_2_4: + * + * The camera device at this status must return -EINVAL for get_camera_info call, + * as the device is not connected. + */ + CAMERA_DEVICE_STATUS_NOT_PRESENT = 0, + + /** + * The camera device is connected, and opening it will succeed. + * + * CAMERA_MODULE_API_VERSION_2_3 or lower: + * + * The information returned by get_camera_info cannot change due to this status + * change. By default, the framework will assume all devices are in this state. + * + * CAMERA_MODULE_API_VERSION_2_4: + * + * The information returned by get_camera_info will become valid after a device's + * status changes to this. By default, the framework will assume all devices are in + * this state. + */ + CAMERA_DEVICE_STATUS_PRESENT = 1, + + /** + * The camera device is connected, but it is undergoing an enumeration and + * so opening the device will return -EBUSY. + * + * CAMERA_MODULE_API_VERSION_2_3 or lower: + * + * Calls to get_camera_info must still succeed, as if the camera was in the + * PRESENT status. + * + * CAMERA_MODULE_API_VERSION_2_4: + * + * The camera device at this status must return -EINVAL for get_camera_info for call, + * as the device is not ready. + */ + CAMERA_DEVICE_STATUS_ENUMERATING = 2, + +} camera_device_status_t; + +/** + * torch_mode_status_t: + * + * The current status of the torch mode, as provided by the HAL through the + * camera_module_callbacks.torch_mode_status_change() call. + * + * The torch mode status of a camera device is applicable only when the camera + * device is present. The framework will not call set_torch_mode() to turn on + * torch mode of a camera device if the camera device is not present. At module + * load time, the framework will assume torch modes are in the + * TORCH_MODE_STATUS_AVAILABLE_OFF state if the camera device is present and + * android.flash.info.available is reported as true via get_camera_info() call. + * + * The behaviors of the camera HAL module that the framework expects in the + * following situations when a camera device's status changes: + * 1. A previously-disconnected camera device becomes connected. + * After camera_module_callbacks::camera_device_status_change() is invoked + * to inform the framework that the camera device is present, the framework + * will assume the camera device's torch mode is in + * TORCH_MODE_STATUS_AVAILABLE_OFF state. The camera HAL module does not need + * to invoke camera_module_callbacks::torch_mode_status_change() unless the + * flash unit is unavailable to use by set_torch_mode(). + * + * 2. A previously-connected camera becomes disconnected. + * After camera_module_callbacks::camera_device_status_change() is invoked + * to inform the framework that the camera device is not present, the + * framework will not call set_torch_mode() for the disconnected camera + * device until its flash unit becomes available again. The camera HAL + * module does not need to invoke + * camera_module_callbacks::torch_mode_status_change() separately to inform + * that the flash unit has become unavailable. + * + * 3. open() is called to open a camera device. + * The camera HAL module must invoke + * camera_module_callbacks::torch_mode_status_change() for all flash units + * that have entered TORCH_MODE_STATUS_NOT_AVAILABLE state and can not be + * turned on by calling set_torch_mode() anymore due to this open() call. + * open() must not trigger TORCH_MODE_STATUS_AVAILABLE_OFF before + * TORCH_MODE_STATUS_NOT_AVAILABLE for all flash units that have become + * unavailable. + * + * 4. close() is called to close a camera device. + * The camera HAL module must invoke + * camera_module_callbacks::torch_mode_status_change() for all flash units + * that have entered TORCH_MODE_STATUS_AVAILABLE_OFF state and can be turned + * on by calling set_torch_mode() again because of enough resources freed + * up by this close() call. + * + * Note that the framework calling set_torch_mode() successfully must trigger + * TORCH_MODE_STATUS_AVAILABLE_OFF or TORCH_MODE_STATUS_AVAILABLE_ON callback + * for the given camera device. Additionally it must trigger + * TORCH_MODE_STATUS_AVAILABLE_OFF callbacks for other previously-on torch + * modes if HAL cannot keep multiple torch modes on simultaneously. + */ +typedef enum torch_mode_status { + + /** + * The flash unit is no longer available and the torch mode can not be + * turned on by calling set_torch_mode(). If the torch mode is on, it + * will be turned off by HAL before HAL calls torch_mode_status_change(). + */ + TORCH_MODE_STATUS_NOT_AVAILABLE = 0, + + /** + * A torch mode has become off and available to be turned on via + * set_torch_mode(). This may happen in the following + * cases: + * 1. After the resources to turn on the torch mode have become available. + * 2. After set_torch_mode() is called to turn off the torch mode. + * 3. After the framework turned on the torch mode of some other camera + * device and HAL had to turn off the torch modes of any camera devices + * that were previously on. + */ + TORCH_MODE_STATUS_AVAILABLE_OFF = 1, + + /** + * A torch mode has become on and available to be turned off via + * set_torch_mode(). This can happen only after set_torch_mode() is called + * to turn on the torch mode. + */ + TORCH_MODE_STATUS_AVAILABLE_ON = 2, + +} torch_mode_status_t; + +/** + * Callback functions for the camera HAL module to use to inform the framework + * of changes to the camera subsystem. + * + * Version information (based on camera_module_t.common.module_api_version): + * + * Each callback is called only by HAL modules implementing the indicated + * version or higher of the HAL module API interface. + * + * CAMERA_MODULE_API_VERSION_2_1: + * camera_device_status_change() + * + * CAMERA_MODULE_API_VERSION_2_4: + * torch_mode_status_change() + + */ +typedef struct camera_module_callbacks { + + /** + * camera_device_status_change: + * + * Callback to the framework to indicate that the state of a specific camera + * device has changed. At module load time, the framework will assume all + * camera devices are in the CAMERA_DEVICE_STATUS_PRESENT state. The HAL + * must call this method to inform the framework of any initially + * NOT_PRESENT devices. + * + * This callback is added for CAMERA_MODULE_API_VERSION_2_1. + * + * camera_module_callbacks: The instance of camera_module_callbacks_t passed + * to the module with set_callbacks. + * + * camera_id: The ID of the camera device that has a new status. + * + * new_status: The new status code, one of the camera_device_status_t enums, + * or a platform-specific status. + * + */ + void (*camera_device_status_change)(const struct camera_module_callbacks*, + int camera_id, + int new_status); + + /** + * torch_mode_status_change: + * + * Callback to the framework to indicate that the state of the torch mode + * of the flash unit associated with a specific camera device has changed. + * At module load time, the framework will assume the torch modes are in + * the TORCH_MODE_STATUS_AVAILABLE_OFF state if android.flash.info.available + * is reported as true via get_camera_info() call. + * + * This callback is added for CAMERA_MODULE_API_VERSION_2_4. + * + * camera_module_callbacks: The instance of camera_module_callbacks_t + * passed to the module with set_callbacks. + * + * camera_id: The ID of camera device whose flash unit has a new torch mode + * status. + * + * new_status: The new status code, one of the torch_mode_status_t enums. + */ + void (*torch_mode_status_change)(const struct camera_module_callbacks*, + const char* camera_id, + int new_status); + + +} camera_module_callbacks_t; + +typedef struct camera_module { + /** + * Common methods of the camera module. This *must* be the first member of + * camera_module as users of this structure will cast a hw_module_t to + * camera_module pointer in contexts where it's known the hw_module_t + * references a camera_module. + * + * The return values for common.methods->open for camera_module are: + * + * 0: On a successful open of the camera device. + * + * -ENODEV: The camera device cannot be opened due to an internal + * error. + * + * -EINVAL: The input arguments are invalid, i.e. the id is invalid, + * and/or the module is invalid. + * + * -EBUSY: The camera device was already opened for this camera id + * (by using this method or open_legacy), + * regardless of the device HAL version it was opened as. + * + * -EUSERS: The maximal number of camera devices that can be + * opened concurrently were opened already, either by + * this method or the open_legacy method. + * + * All other return values from common.methods->open will be treated as + * -ENODEV. + */ + hw_module_t common; + + /** + * get_number_of_cameras: + * + * Returns the number of camera devices accessible through the camera + * module. The camera devices are numbered 0 through N-1, where N is the + * value returned by this call. The name of the camera device for open() is + * simply the number converted to a string. That is, "0" for camera ID 0, + * "1" for camera ID 1. + * + * Version information (based on camera_module_t.common.module_api_version): + * + * CAMERA_MODULE_API_VERSION_2_3 or lower: + * + * The value here must be static, and cannot change after the first call + * to this method. + * + * CAMERA_MODULE_API_VERSION_2_4 or higher: + * + * The value here must be static, and must count only built-in cameras, + * which have CAMERA_FACING_BACK or CAMERA_FACING_FRONT camera facing values + * (camera_info.facing). The HAL must not include the external cameras + * (camera_info.facing == CAMERA_FACING_EXTERNAL) into the return value + * of this call. Frameworks will use camera_device_status_change callback + * to manage number of external cameras. + */ + int (*get_number_of_cameras)(void); + + /** + * get_camera_info: + * + * Return the static camera information for a given camera device. This + * information may not change for a camera device. + * + * Return values: + * + * 0: On a successful operation + * + * -ENODEV: The information cannot be provided due to an internal + * error. + * + * -EINVAL: The input arguments are invalid, i.e. the id is invalid, + * and/or the module is invalid. + * + * Version information (based on camera_module_t.common.module_api_version): + * + * CAMERA_MODULE_API_VERSION_2_4 or higher: + * + * When a camera is disconnected, its camera id becomes invalid. Calling this + * this method with this invalid camera id will get -EINVAL and NULL camera + * static metadata (camera_info.static_camera_characteristics). + */ + int (*get_camera_info)(int camera_id, struct camera_info *info); + + /** + * set_callbacks: + * + * Provide callback function pointers to the HAL module to inform framework + * of asynchronous camera module events. The framework will call this + * function once after initial camera HAL module load, after the + * get_number_of_cameras() method is called for the first time, and before + * any other calls to the module. + * + * Version information (based on camera_module_t.common.module_api_version): + * + * CAMERA_MODULE_API_VERSION_1_0, CAMERA_MODULE_API_VERSION_2_0: + * + * Not provided by HAL module. Framework may not call this function. + * + * CAMERA_MODULE_API_VERSION_2_1: + * + * Valid to be called by the framework. + * + * Return values: + * + * 0: On a successful operation + * + * -ENODEV: The operation cannot be completed due to an internal + * error. + * + * -EINVAL: The input arguments are invalid, i.e. the callbacks are + * null + */ + int (*set_callbacks)(const camera_module_callbacks_t *callbacks); + + /** + * get_vendor_tag_ops: + * + * Get methods to query for vendor extension metadata tag information. The + * HAL should fill in all the vendor tag operation methods, or leave ops + * unchanged if no vendor tags are defined. + * + * The vendor_tag_ops structure used here is defined in: + * system/media/camera/include/system/vendor_tags.h + * + * Version information (based on camera_module_t.common.module_api_version): + * + * CAMERA_MODULE_API_VERSION_1_x/2_0/2_1: + * Not provided by HAL module. Framework may not call this function. + * + * CAMERA_MODULE_API_VERSION_2_2: + * Valid to be called by the framework. + */ + void (*get_vendor_tag_ops)(vendor_tag_ops_t* ops); + + /** + * open_legacy: + * + * Open a specific legacy camera HAL device if multiple device HAL API + * versions are supported by this camera HAL module. For example, if the + * camera module supports both CAMERA_DEVICE_API_VERSION_1_0 and + * CAMERA_DEVICE_API_VERSION_3_2 device API for the same camera id, + * framework can call this function to open the camera device as + * CAMERA_DEVICE_API_VERSION_1_0 device. + * + * This is an optional method. A Camera HAL module does not need to support + * more than one device HAL version per device, and such modules may return + * -ENOSYS for all calls to this method. For all older HAL device API + * versions that are not supported, it may return -EOPNOTSUPP. When above + * cases occur, The normal open() method (common.methods->open) will be + * used by the framework instead. + * + * Version information (based on camera_module_t.common.module_api_version): + * + * CAMERA_MODULE_API_VERSION_1_x/2_0/2_1/2_2: + * Not provided by HAL module. Framework will not call this function. + * + * CAMERA_MODULE_API_VERSION_2_3: + * Valid to be called by the framework. + * + * Return values: + * + * 0: On a successful open of the camera device. + * + * -ENOSYS This method is not supported. + * + * -EOPNOTSUPP: The requested HAL version is not supported by this method. + * + * -EINVAL: The input arguments are invalid, i.e. the id is invalid, + * and/or the module is invalid. + * + * -EBUSY: The camera device was already opened for this camera id + * (by using this method or common.methods->open method), + * regardless of the device HAL version it was opened as. + * + * -EUSERS: The maximal number of camera devices that can be + * opened concurrently were opened already, either by + * this method or common.methods->open method. + */ + int (*open_legacy)(const struct hw_module_t* module, const char* id, + uint32_t halVersion, struct hw_device_t** device); + + /** + * set_torch_mode: + * + * Turn on or off the torch mode of the flash unit associated with a given + * camera ID. If the operation is successful, HAL must notify the framework + * torch state by invoking + * camera_module_callbacks.torch_mode_status_change() with the new state. + * + * The camera device has a higher priority accessing the flash unit. When + * there are any resource conflicts, such as open() is called to open a + * camera device, HAL module must notify the framework through + * camera_module_callbacks.torch_mode_status_change() that the + * torch mode has been turned off and the torch mode state has become + * TORCH_MODE_STATUS_NOT_AVAILABLE. When resources to turn on torch mode + * become available again, HAL module must notify the framework through + * camera_module_callbacks.torch_mode_status_change() that the torch mode + * state has become TORCH_MODE_STATUS_AVAILABLE_OFF for set_torch_mode() to + * be called. + * + * When the framework calls set_torch_mode() to turn on the torch mode of a + * flash unit, if HAL cannot keep multiple torch modes on simultaneously, + * HAL should turn off the torch mode that was turned on by + * a previous set_torch_mode() call and notify the framework that the torch + * mode state of that flash unit has become TORCH_MODE_STATUS_AVAILABLE_OFF. + * + * Version information (based on camera_module_t.common.module_api_version): + * + * CAMERA_MODULE_API_VERSION_1_x/2_0/2_1/2_2/2_3: + * Not provided by HAL module. Framework will not call this function. + * + * CAMERA_MODULE_API_VERSION_2_4: + * Valid to be called by the framework. + * + * Return values: + * + * 0: On a successful operation. + * + * -ENOSYS: The camera device does not support this operation. It is + * returned if and only if android.flash.info.available is + * false. + * + * -EBUSY: The camera device is already in use. + * + * -EUSERS: The resources needed to turn on the torch mode are not + * available, typically because other camera devices are + * holding the resources to make using the flash unit not + * possible. + * + * -EINVAL: camera_id is invalid. + * + */ + int (*set_torch_mode)(const char* camera_id, bool enabled); + + /** + * init: + * + * This method is called by the camera service before any other methods + * are invoked, right after the camera HAL library has been successfully + * loaded. It may be left as NULL by the HAL module, if no initialization + * in needed. + * + * It can be used by HAL implementations to perform initialization and + * other one-time operations. + * + * Version information (based on camera_module_t.common.module_api_version): + * + * CAMERA_MODULE_API_VERSION_1_x/2_0/2_1/2_2/2_3: + * Not provided by HAL module. Framework will not call this function. + * + * CAMERA_MODULE_API_VERSION_2_4: + * If not NULL, will always be called by the framework once after the HAL + * module is loaded, before any other HAL module method is called. + * + * Return values: + * + * 0: On a successful operation. + * + * -ENODEV: Initialization cannot be completed due to an internal + * error. The HAL must be assumed to be in a nonfunctional + * state. + * + */ + int (*init)(); + + /* reserved for future use */ + void* reserved[5]; +} camera_module_t; + +__END_DECLS + +#endif /* ANDROID_INCLUDE_CAMERA_COMMON_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/consumerir.h b/phonelibs/android_hardware_libhardware/include/hardware/consumerir.h new file mode 100644 index 0000000000..15334c1111 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/consumerir.h @@ -0,0 +1,92 @@ +/* + * 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_INCLUDE_HARDWARE_CONSUMERIR_H +#define ANDROID_INCLUDE_HARDWARE_CONSUMERIR_H + +#include +#include +#include +#include + +#define CONSUMERIR_MODULE_API_VERSION_1_0 HARDWARE_MODULE_API_VERSION(1, 0) +#define CONSUMERIR_HARDWARE_MODULE_ID "consumerir" +#define CONSUMERIR_TRANSMITTER "transmitter" + +typedef struct consumerir_freq_range { + int min; + int max; +} consumerir_freq_range_t; + +typedef struct consumerir_module { + /** + * Common methods of the consumer IR module. This *must* be the first member of + * consumerir_module as users of this structure will cast a hw_module_t to + * consumerir_module pointer in contexts where it's known the hw_module_t references a + * consumerir_module. + */ + struct hw_module_t common; +} consumerir_module_t; + +typedef struct consumerir_device { + /** + * Common methods of the consumer IR device. This *must* be the first member of + * consumerir_device as users of this structure will cast a hw_device_t to + * consumerir_device pointer in contexts where it's known the hw_device_t references a + * consumerir_device. + */ + struct hw_device_t common; + + /* + * (*transmit)() is called to by the ConsumerIrService to send an IR pattern + * at a given carrier_freq. + * + * The pattern is alternating series of carrier on and off periods measured in + * microseconds. The carrier should be turned off at the end of a transmit + * even if there are and odd number of entries in the pattern array. + * + * This call should return when the transmit is complete or encounters an error. + * + * returns: 0 on success. A negative error code on error. + */ + int (*transmit)(struct consumerir_device *dev, int carrier_freq, + const int pattern[], int pattern_len); + + /* + * (*get_num_carrier_freqs)() is called by the ConsumerIrService to get the + * number of carrier freqs to allocate space for, which is then filled by + * a subsequent call to (*get_carrier_freqs)(). + * + * returns: the number of ranges on success. A negative error code on error. + */ + int (*get_num_carrier_freqs)(struct consumerir_device *dev); + + /* + * (*get_carrier_freqs)() is called by the ConsumerIrService to enumerate + * which frequencies the IR transmitter supports. The HAL implementation + * should fill an array of consumerir_freq_range structs with the + * appropriate values for the transmitter, up to len elements. + * + * returns: the number of ranges on success. A negative error code on error. + */ + int (*get_carrier_freqs)(struct consumerir_device *dev, + size_t len, consumerir_freq_range_t *ranges); + + /* Reserved for future use. Must be NULL. */ + void* reserved[8 - 3]; +} consumerir_device_t; + +#endif /* ANDROID_INCLUDE_HARDWARE_CONSUMERIR_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/display_defs.h b/phonelibs/android_hardware_libhardware/include/hardware/display_defs.h new file mode 100644 index 0000000000..669ef78c4e --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/display_defs.h @@ -0,0 +1,67 @@ +/* Copyright (c) 2014-2015, The Linux Foundation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of The Linux Foundation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef ANDROID_INCLUDE_DISPLAY_DEFS_H +#define ANDROID_INCLUDE_DISPLAY_DEFS_H + +#include +#include + +#include + +__BEGIN_DECLS + +/* Will need to update below enums if hwcomposer_defs.h is updated */ + +/* Extended events for hwc_methods::eventControl() */ +enum { + HWC_EVENT_ORIENTATION = HWC_EVENT_VSYNC + 1 +}; + + +/* Extended hwc_layer_t::compositionType values */ +enum { + /* this layer will be handled in the HWC, using a blit engine */ + HWC_BLIT = 0xFF +}; + +/* Extended hwc_layer_t::flags values + * Flags are set by SurfaceFlinger and read by the HAL + */ +enum { + /* + * HWC_SCREENSHOT_ANIMATOR_LAYER is set by surfaceflinger to indicate + * that this layer is a screenshot animating layer. HWC uses this + * info to disable rotation animation on External Display + */ + HWC_SCREENSHOT_ANIMATOR_LAYER = 0x00000004 +}; + +__END_DECLS + +#endif /* ANDROID_INCLUDE_DISPLAY_DEFS_H*/ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/fb.h b/phonelibs/android_hardware_libhardware/include/hardware/fb.h new file mode 100644 index 0000000000..9df94165b9 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/fb.h @@ -0,0 +1,173 @@ +/* + * 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_FB_INTERFACE_H +#define ANDROID_FB_INTERFACE_H + +#include +#include +#include + +#include + +#include + +__BEGIN_DECLS + +#define GRALLOC_HARDWARE_FB0 "fb0" + +/*****************************************************************************/ + + +/*****************************************************************************/ + +typedef struct framebuffer_device_t { + /** + * Common methods of the framebuffer device. This *must* be the first member of + * framebuffer_device_t as users of this structure will cast a hw_device_t to + * framebuffer_device_t pointer in contexts where it's known the hw_device_t references a + * framebuffer_device_t. + */ + struct hw_device_t common; + + /* flags describing some attributes of the framebuffer */ + const uint32_t flags; + + /* dimensions of the framebuffer in pixels */ + const uint32_t width; + const uint32_t height; + + /* frambuffer stride in pixels */ + const int stride; + + /* framebuffer pixel format */ + const int format; + + /* resolution of the framebuffer's display panel in pixel per inch*/ + const float xdpi; + const float ydpi; + + /* framebuffer's display panel refresh rate in frames per second */ + const float fps; + + /* min swap interval supported by this framebuffer */ + const int minSwapInterval; + + /* max swap interval supported by this framebuffer */ + const int maxSwapInterval; + + /* Number of framebuffers supported*/ + const int numFramebuffers; + + int reserved[7]; + + /* + * requests a specific swap-interval (same definition than EGL) + * + * Returns 0 on success or -errno on error. + */ + int (*setSwapInterval)(struct framebuffer_device_t* window, + int interval); + + /* + * This hook is OPTIONAL. + * + * It is non NULL If the framebuffer driver supports "update-on-demand" + * and the given rectangle is the area of the screen that gets + * updated during (*post)(). + * + * This is useful on devices that are able to DMA only a portion of + * the screen to the display panel, upon demand -- as opposed to + * constantly refreshing the panel 60 times per second, for instance. + * + * Only the area defined by this rectangle is guaranteed to be valid, that + * is, the driver is not allowed to post anything outside of this + * rectangle. + * + * The rectangle evaluated during (*post)() and specifies which area + * of the buffer passed in (*post)() shall to be posted. + * + * return -EINVAL if width or height <=0, or if left or top < 0 + */ + int (*setUpdateRect)(struct framebuffer_device_t* window, + int left, int top, int width, int height); + + /* + * Post to the display (display it on the screen) + * The buffer must have been allocated with the + * GRALLOC_USAGE_HW_FB usage flag. + * buffer must be the same width and height as the display and must NOT + * be locked. + * + * The buffer is shown during the next VSYNC. + * + * If the same buffer is posted again (possibly after some other buffer), + * post() will block until the the first post is completed. + * + * Internally, post() is expected to lock the buffer so that a + * subsequent call to gralloc_module_t::(*lock)() with USAGE_RENDER or + * USAGE_*_WRITE will block until it is safe; that is typically once this + * buffer is shown and another buffer has been posted. + * + * Returns 0 on success or -errno on error. + */ + int (*post)(struct framebuffer_device_t* dev, buffer_handle_t buffer); + + + /* + * The (*compositionComplete)() method must be called after the + * compositor has finished issuing GL commands for client buffers. + */ + + int (*compositionComplete)(struct framebuffer_device_t* dev); + + /* + * This hook is OPTIONAL. + * + * If non NULL it will be caused by SurfaceFlinger on dumpsys + */ + void (*dump)(struct framebuffer_device_t* dev, char *buff, int buff_len); + + /* + * (*enableScreen)() is used to either blank (enable=0) or + * unblank (enable=1) the screen this framebuffer is attached to. + * + * Returns 0 on success or -errno on error. + */ + int (*enableScreen)(struct framebuffer_device_t* dev, int enable); + + void* reserved_proc[6]; + +} framebuffer_device_t; + + +/** convenience API for opening and closing a supported device */ + +static inline int framebuffer_open(const struct hw_module_t* module, + struct framebuffer_device_t** device) { + return module->methods->open(module, + GRALLOC_HARDWARE_FB0, (struct hw_device_t**)device); +} + +static inline int framebuffer_close(struct framebuffer_device_t* device) { + return device->common.close(&device->common); +} + + +__END_DECLS + +#endif // ANDROID_FB_INTERFACE_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/fingerprint.h b/phonelibs/android_hardware_libhardware/include/hardware/fingerprint.h new file mode 100644 index 0000000000..ac88c10322 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/fingerprint.h @@ -0,0 +1,266 @@ +/* + * Copyright (C) 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_INCLUDE_HARDWARE_FINGERPRINT_H +#define ANDROID_INCLUDE_HARDWARE_FINGERPRINT_H + +#include + +#define FINGERPRINT_MODULE_API_VERSION_1_0 HARDWARE_MODULE_API_VERSION(1, 0) +#define FINGERPRINT_MODULE_API_VERSION_2_0 HARDWARE_MODULE_API_VERSION(2, 0) +#define FINGERPRINT_HARDWARE_MODULE_ID "fingerprint" + +typedef enum fingerprint_msg_type { + FINGERPRINT_ERROR = -1, + FINGERPRINT_ACQUIRED = 1, + FINGERPRINT_TEMPLATE_ENROLLING = 3, + FINGERPRINT_TEMPLATE_REMOVED = 4, + FINGERPRINT_AUTHENTICATED = 5 +} fingerprint_msg_type_t; + +/* + * Fingerprint errors are meant to tell the framework to terminate the current operation and ask + * for the user to correct the situation. These will almost always result in messaging and user + * interaction to correct the problem. + * + * For example, FINGERPRINT_ERROR_CANCELED should follow any acquisition message that results in + * a situation where the current operation can't continue without user interaction. For example, + * if the sensor is dirty during enrollment and no further enrollment progress can be made, + * send FINGERPRINT_ACQUIRED_IMAGER_DIRTY followed by FINGERPRINT_ERROR_CANCELED. + */ +typedef enum fingerprint_error { + FINGERPRINT_ERROR_HW_UNAVAILABLE = 1, /* The hardware has an error that can't be resolved. */ + FINGERPRINT_ERROR_UNABLE_TO_PROCESS = 2, /* Bad data; operation can't continue */ + FINGERPRINT_ERROR_TIMEOUT = 3, /* The operation has timed out waiting for user input. */ + FINGERPRINT_ERROR_NO_SPACE = 4, /* No space available to store a template */ + FINGERPRINT_ERROR_CANCELED = 5, /* The current operation can't proceed. See above. */ + FINGERPRINT_ERROR_UNABLE_TO_REMOVE = 6, /* fingerprint with given id can't be removed */ + FINGERPRINT_ERROR_VENDOR_BASE = 1000 /* vendor-specific error messages start here */ +} fingerprint_error_t; + +/* + * Fingerprint acquisition info is meant as feedback for the current operation. Anything but + * FINGERPRINT_ACQUIRED_GOOD will be shown to the user as feedback on how to take action on the + * current operation. For example, FINGERPRINT_ACQUIRED_IMAGER_DIRTY can be used to tell the user + * to clean the sensor. If this will cause the current operation to fail, an additional + * FINGERPRINT_ERROR_CANCELED can be sent to stop the operation in progress (e.g. enrollment). + * In general, these messages will result in a "Try again" message. + */ +typedef enum fingerprint_acquired_info { + FINGERPRINT_ACQUIRED_GOOD = 0, + FINGERPRINT_ACQUIRED_PARTIAL = 1, /* sensor needs more data, i.e. longer swipe. */ + FINGERPRINT_ACQUIRED_INSUFFICIENT = 2, /* image doesn't contain enough detail for recognition*/ + FINGERPRINT_ACQUIRED_IMAGER_DIRTY = 3, /* sensor needs to be cleaned */ + FINGERPRINT_ACQUIRED_TOO_SLOW = 4, /* mostly swipe-type sensors; not enough data collected */ + FINGERPRINT_ACQUIRED_TOO_FAST = 5, /* for swipe and area sensors; tell user to slow down*/ + FINGERPRINT_ACQUIRED_VENDOR_BASE = 1000 /* vendor-specific acquisition messages start here */ +} fingerprint_acquired_info_t; + +typedef struct fingerprint_finger_id { + uint32_t gid; + uint32_t fid; +} fingerprint_finger_id_t; + +typedef struct fingerprint_enroll { + fingerprint_finger_id_t finger; + /* samples_remaining goes from N (no data collected, but N scans needed) + * to 0 (no more data is needed to build a template). */ + uint32_t samples_remaining; + uint64_t msg; /* Vendor specific message. Used for user guidance */ +} fingerprint_enroll_t; + +typedef struct fingerprint_removed { + fingerprint_finger_id_t finger; +} fingerprint_removed_t; + +typedef struct fingerprint_acquired { + fingerprint_acquired_info_t acquired_info; /* information about the image */ +} fingerprint_acquired_t; + +typedef struct fingerprint_authenticated { + fingerprint_finger_id_t finger; + hw_auth_token_t hat; +} fingerprint_authenticated_t; + +typedef struct fingerprint_msg { + fingerprint_msg_type_t type; + union { + fingerprint_error_t error; + fingerprint_enroll_t enroll; + fingerprint_removed_t removed; + fingerprint_acquired_t acquired; + fingerprint_authenticated_t authenticated; + } data; +} fingerprint_msg_t; + +/* Callback function type */ +typedef void (*fingerprint_notify_t)(const fingerprint_msg_t *msg); + +/* Synchronous operation */ +typedef struct fingerprint_device { + /** + * Common methods of the fingerprint device. This *must* be the first member + * of fingerprint_device as users of this structure will cast a hw_device_t + * to fingerprint_device pointer in contexts where it's known + * the hw_device_t references a fingerprint_device. + */ + struct hw_device_t common; + + /* + * Client provided callback function to receive notifications. + * Do not set by hand, use the function above instead. + */ + fingerprint_notify_t notify; + + /* + * Set notification callback: + * Registers a user function that would receive notifications from the HAL + * The call will block if the HAL state machine is in busy state until HAL + * leaves the busy state. + * + * Function return: 0 if callback function is successfuly registered + * or a negative number in case of error, generally from the errno.h set. + */ + int (*set_notify)(struct fingerprint_device *dev, fingerprint_notify_t notify); + + /* + * Fingerprint pre-enroll enroll request: + * Generates a unique token to upper layers to indicate the start of an enrollment transaction. + * This token will be wrapped by security for verification and passed to enroll() for + * verification before enrollment will be allowed. This is to ensure adding a new fingerprint + * template was preceded by some kind of credential confirmation (e.g. device password). + * + * Function return: 0 if function failed + * otherwise, a uint64_t of token + */ + uint64_t (*pre_enroll)(struct fingerprint_device *dev); + + /* + * Fingerprint enroll request: + * Switches the HAL state machine to collect and store a new fingerprint + * template. Switches back as soon as enroll is complete + * (fingerprint_msg.type == FINGERPRINT_TEMPLATE_ENROLLING && + * fingerprint_msg.data.enroll.samples_remaining == 0) + * or after timeout_sec seconds. + * The fingerprint template will be assigned to the group gid. User has a choice + * to supply the gid or set it to 0 in which case a unique group id will be generated. + * + * Function return: 0 if enrollment process can be successfully started + * or a negative number in case of error, generally from the errno.h set. + * A notify() function may be called indicating the error condition. + */ + int (*enroll)(struct fingerprint_device *dev, const hw_auth_token_t *hat, + uint32_t gid, uint32_t timeout_sec); + + /* + * Finishes the enroll operation and invalidates the pre_enroll() generated challenge. + * This will be called at the end of a multi-finger enrollment session to indicate + * that no more fingers will be added. + * + * Function return: 0 if the request is accepted + * or a negative number in case of error, generally from the errno.h set. + */ + int (*post_enroll)(struct fingerprint_device *dev); + + /* + * get_authenticator_id: + * Returns a token associated with the current fingerprint set. This value will + * change whenever a new fingerprint is enrolled, thus creating a new fingerprint + * set. + * + * Function return: current authenticator id or 0 if function failed. + */ + uint64_t (*get_authenticator_id)(struct fingerprint_device *dev); + + /* + * Cancel pending enroll or authenticate, sending FINGERPRINT_ERROR_CANCELED + * to all running clients. Switches the HAL state machine back to the idle state. + * Unlike enroll_done() doesn't invalidate the pre_enroll() challenge. + * + * Function return: 0 if cancel request is accepted + * or a negative number in case of error, generally from the errno.h set. + */ + int (*cancel)(struct fingerprint_device *dev); + + /* + * Enumerate all the fingerprint templates found in the directory set by + * set_active_group() + * This is a synchronous call. The function takes: + * - A pointer to an array of fingerprint_finger_id_t. + * - The size of the array provided, in fingerprint_finger_id_t elements. + * Max_size is a bi-directional parameter and returns the actual number + * of elements copied to the caller supplied array. + * In the absence of errors the function returns the total number of templates + * in the user directory. + * If the caller has no good guess on the size of the array he should call this + * function witn *max_size == 0 and use the return value for the array allocation. + * The caller of this function has a complete list of the templates when *max_size + * is the same as the function return. + * + * Function return: Total number of fingerprint templates in the current storage directory. + * or a negative number in case of error, generally from the errno.h set. + */ + int (*enumerate)(struct fingerprint_device *dev, fingerprint_finger_id_t *results, + uint32_t *max_size); + + /* + * Fingerprint remove request: + * Deletes a fingerprint template. + * Works only within a path set by set_active_group(). + * notify() will be called with details on the template deleted. + * fingerprint_msg.type == FINGERPRINT_TEMPLATE_REMOVED and + * fingerprint_msg.data.removed.id indicating the template id removed. + * + * Function return: 0 if fingerprint template(s) can be successfully deleted + * or a negative number in case of error, generally from the errno.h set. + */ + int (*remove)(struct fingerprint_device *dev, uint32_t gid, uint32_t fid); + + /* + * Restricts the HAL operation to a set of fingerprints belonging to a + * group provided. + * The caller must provide a path to a storage location within the user's + * data directory. + * + * Function return: 0 on success + * or a negative number in case of error, generally from the errno.h set. + */ + int (*set_active_group)(struct fingerprint_device *dev, uint32_t gid, + const char *store_path); + + /* + * Authenticates an operation identifed by operation_id + * + * Function return: 0 on success + * or a negative number in case of error, generally from the errno.h set. + */ + int (*authenticate)(struct fingerprint_device *dev, uint64_t operation_id, uint32_t gid); + + /* Reserved for backward binary compatibility */ + void *reserved[4]; +} fingerprint_device_t; + +typedef struct fingerprint_module { + /** + * Common methods of the fingerprint module. This *must* be the first member + * of fingerprint_module as users of this structure will cast a hw_module_t + * to fingerprint_module pointer in contexts where it's known + * the hw_module_t references a fingerprint_module. + */ + struct hw_module_t common; +} fingerprint_module_t; + +#endif /* ANDROID_INCLUDE_HARDWARE_FINGERPRINT_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/fused_location.h b/phonelibs/android_hardware_libhardware/include/hardware/fused_location.h new file mode 100644 index 0000000000..73360a12a1 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/fused_location.h @@ -0,0 +1,825 @@ +/* + * 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_INCLUDE_HARDWARE_FUSED_LOCATION_H +#define ANDROID_INCLUDE_HARDWARE_FUSED_LOCATION_H + +#include + + +/** + * This header file defines the interface of the Fused Location Provider. + * Fused Location Provider is designed to fuse data from various sources + * like GPS, Wifi, Cell, Sensors, Bluetooth etc to provide a fused location to the + * upper layers. The advantage of doing fusion in hardware is power savings. + * The goal is to do this without waking up the AP to get additional data. + * The software implementation of FLP will decide when to use + * the hardware fused location. Other location features like geofencing will + * also be implemented using fusion in hardware. + */ +__BEGIN_DECLS + +#define FLP_HEADER_VERSION 1 +#define FLP_MODULE_API_VERSION_0_1 HARDWARE_MODULE_API_VERSION(0, 1) +#define FLP_DEVICE_API_VERSION_0_1 HARDWARE_DEVICE_API_VERSION_2(0, 1, FLP_HEADER_VERSION) + +/** + * The id of this module + */ +#define FUSED_LOCATION_HARDWARE_MODULE_ID "flp" + +/** + * Name for the FLP location interface + */ +#define FLP_LOCATION_INTERFACE "flp_location" + +/** + * Name for the FLP location interface + */ +#define FLP_DIAGNOSTIC_INTERFACE "flp_diagnostic" + +/** + * Name for the FLP_Geofencing interface. + */ +#define FLP_GEOFENCING_INTERFACE "flp_geofencing" + +/** + * Name for the FLP_device context interface. + */ +#define FLP_DEVICE_CONTEXT_INTERFACE "flp_device_context" + +/** + * Constants to indicate the various subsystems + * that will be used. + */ +#define FLP_TECH_MASK_GNSS (1U<<0) +#define FLP_TECH_MASK_WIFI (1U<<1) +#define FLP_TECH_MASK_SENSORS (1U<<2) +#define FLP_TECH_MASK_CELL (1U<<3) +#define FLP_TECH_MASK_BLUETOOTH (1U<<4) + +/** + * Set when your implementation can produce GNNS-derived locations, + * for use with flp_capabilities_callback. + * + * GNNS is a required capability for a particular feature to be used + * (batching or geofencing). If not supported that particular feature + * won't be used by the upper layer. + */ +#define CAPABILITY_GNSS (1U<<0) +/** + * Set when your implementation can produce WiFi-derived locations, for + * use with flp_capabilities_callback. + */ +#define CAPABILITY_WIFI (1U<<1) +/** + * Set when your implementation can produce cell-derived locations, for + * use with flp_capabilities_callback. + */ +#define CAPABILITY_CELL (1U<<3) + +/** + * Status to return in flp_status_callback when your implementation transitions + * from being unsuccessful in determining location to being successful. + */ +#define FLP_STATUS_LOCATION_AVAILABLE 0 +/** + * Status to return in flp_status_callback when your implementation transitions + * from being successful in determining location to being unsuccessful. + */ +#define FLP_STATUS_LOCATION_UNAVAILABLE 1 + +/** + * This constant is used with the batched locations + * APIs. Batching is mandatory when FLP implementation + * is supported. If the flag is set, the hardware implementation + * will wake up the application processor when the FIFO is full, + * If the flag is not set, the hardware implementation will drop + * the oldest data when the FIFO is full. + */ +#define FLP_BATCH_WAKEUP_ON_FIFO_FULL 0x0000001 + +/** + * While batching, the implementation should not call the + * flp_location_callback on every location fix. However, + * sometimes in high power mode, the system might need + * a location callback every single time the location + * fix has been obtained. This flag controls that option. + * Its the responsibility of the upper layers (caller) to switch + * it off, if it knows that the AP might go to sleep. + * When this bit is on amidst a batching session, batching should + * continue while location fixes are reported in real time. + */ +#define FLP_BATCH_CALLBACK_ON_LOCATION_FIX 0x0000002 + +/** Flags to indicate which values are valid in a FlpLocation. */ +typedef uint16_t FlpLocationFlags; + +// IMPORTANT: Note that the following values must match +// constants in the corresponding java file. + +/** FlpLocation has valid latitude and longitude. */ +#define FLP_LOCATION_HAS_LAT_LONG (1U<<0) +/** FlpLocation has valid altitude. */ +#define FLP_LOCATION_HAS_ALTITUDE (1U<<1) +/** FlpLocation has valid speed. */ +#define FLP_LOCATION_HAS_SPEED (1U<<2) +/** FlpLocation has valid bearing. */ +#define FLP_LOCATION_HAS_BEARING (1U<<4) +/** FlpLocation has valid accuracy. */ +#define FLP_LOCATION_HAS_ACCURACY (1U<<8) + + +typedef int64_t FlpUtcTime; + +/** Represents a location. */ +typedef struct { + /** set to sizeof(FlpLocation) */ + size_t size; + + /** Flags associated with the location object. */ + FlpLocationFlags flags; + + /** Represents latitude in degrees. */ + double latitude; + + /** Represents longitude in degrees. */ + double longitude; + + /** + * Represents altitude in meters above the WGS 84 reference + * ellipsoid. */ + double altitude; + + /** Represents speed in meters per second. */ + float speed; + + /** Represents heading in degrees. */ + float bearing; + + /** Represents expected accuracy in meters. */ + float accuracy; + + /** Timestamp for the location fix. */ + FlpUtcTime timestamp; + + /** Sources used, will be Bitwise OR of the FLP_TECH_MASK bits. */ + uint32_t sources_used; +} FlpLocation; + +typedef enum { + ASSOCIATE_JVM, + DISASSOCIATE_JVM, +} ThreadEvent; + +/** + * Callback with location information. + * Can only be called from a thread associated to JVM using set_thread_event_cb. + * Parameters: + * num_locations is the number of batched locations available. + * location is the pointer to an array of pointers to location objects. + */ +typedef void (*flp_location_callback)(int32_t num_locations, FlpLocation** location); + +/** + * Callback utility for acquiring a wakelock. + * This can be used to prevent the CPU from suspending while handling FLP events. + */ +typedef void (*flp_acquire_wakelock)(); + +/** + * Callback utility for releasing the FLP wakelock. + */ +typedef void (*flp_release_wakelock)(); + +/** + * Callback for associating a thread that can call into the Java framework code. + * This must be used to initialize any threads that report events up to the framework. + * Return value: + * FLP_RESULT_SUCCESS on success. + * FLP_RESULT_ERROR if the association failed in the current thread. + */ +typedef int (*flp_set_thread_event)(ThreadEvent event); + +/** + * Callback for technologies supported by this implementation. + * + * Parameters: capabilities is a bitmask of FLP_CAPABILITY_* values describing + * which features your implementation supports. You should support + * CAPABILITY_GNSS at a minimum for your implementation to be utilized. You can + * return 0 in FlpGeofenceCallbacks to indicate you don't support geofencing, + * or 0 in FlpCallbacks to indicate you don't support location batching. + */ +typedef void (*flp_capabilities_callback)(int capabilities); + +/** + * Callback with status information on the ability to compute location. + * To avoid waking up the application processor you should only send + * changes in status (you shouldn't call this method twice in a row + * with the same status value). As a guideline you should not call this + * more frequently then the requested batch period set with period_ns + * in FlpBatchOptions. For example if period_ns is set to 5 minutes and + * the status changes many times in that interval, you should only report + * one status change every 5 minutes. + * + * Parameters: + * status is one of FLP_STATUS_LOCATION_AVAILABLE + * or FLP_STATUS_LOCATION_UNAVAILABLE. + */ +typedef void (*flp_status_callback)(int32_t status); + +/** FLP callback structure. */ +typedef struct { + /** set to sizeof(FlpCallbacks) */ + size_t size; + flp_location_callback location_cb; + flp_acquire_wakelock acquire_wakelock_cb; + flp_release_wakelock release_wakelock_cb; + flp_set_thread_event set_thread_event_cb; + flp_capabilities_callback flp_capabilities_cb; + flp_status_callback flp_status_cb; +} FlpCallbacks; + + +/** Options with the batching FLP APIs */ +typedef struct { + /** + * Maximum power in mW that the underlying implementation + * can use for this batching call. + * If max_power_allocation_mW is 0, only fixes that are generated + * at no additional cost of power shall be reported. + */ + double max_power_allocation_mW; + + /** Bitwise OR of the FLP_TECH_MASKS to use */ + uint32_t sources_to_use; + + /** + * FLP_BATCH_WAKEUP_ON_FIFO_FULL - If set the hardware + * will wake up the AP when the buffer is full. If not set, the + * hardware will drop the oldest location object. + * + * FLP_BATCH_CALLBACK_ON_LOCATION_FIX - If set the location + * callback will be called every time there is a location fix. + * Its the responsibility of the upper layers (caller) to switch + * it off, if it knows that the AP might go to sleep. When this + * bit is on amidst a batching session, batching should continue + * while location fixes are reported in real time. + * + * Other flags to be bitwised ORed in the future. + */ + uint32_t flags; + + /** + * Frequency with which location needs to be batched in nano + * seconds. + */ + int64_t period_ns; + + /** + * The smallest displacement between reported locations in meters. + * + * If set to 0, then you should report locations at the requested + * interval even if the device is stationary. If positive, you + * can use this parameter as a hint to save power (e.g. throttling + * location period if the user hasn't traveled close to the displacement + * threshold). Even small positive values can be interpreted to mean + * that you don't have to compute location when the device is stationary. + * + * There is no need to filter location delivery based on this parameter. + * Locations can be delivered even if they have a displacement smaller than + * requested. This parameter can safely be ignored at the cost of potential + * power savings. + */ + float smallest_displacement_meters; +} FlpBatchOptions; + +#define FLP_RESULT_SUCCESS 0 +#define FLP_RESULT_ERROR -1 +#define FLP_RESULT_INSUFFICIENT_MEMORY -2 +#define FLP_RESULT_TOO_MANY_GEOFENCES -3 +#define FLP_RESULT_ID_EXISTS -4 +#define FLP_RESULT_ID_UNKNOWN -5 +#define FLP_RESULT_INVALID_GEOFENCE_TRANSITION -6 + +/** + * Represents the standard FLP interface. + */ +typedef struct { + /** + * set to sizeof(FlpLocationInterface) + */ + size_t size; + + /** + * Opens the interface and provides the callback routines + * to the implementation of this interface. Once called you should respond + * by calling the flp_capabilities_callback in FlpCallbacks to + * specify the capabilities that your implementation supports. + */ + int (*init)(FlpCallbacks* callbacks ); + + /** + * Return the batch size (in number of FlpLocation objects) + * available in the hardware. Note, different HW implementations + * may have different sample sizes. This shall return number + * of samples defined in the format of FlpLocation. + * This will be used by the upper layer, to decide on the batching + * interval and whether the AP should be woken up or not. + */ + int (*get_batch_size)(); + + /** + * Start batching locations. This API is primarily used when the AP is + * asleep and the device can batch locations in the hardware. + * flp_location_callback is used to return the locations. When the buffer + * is full and FLP_BATCH_WAKEUP_ON_FIFO_FULL is used, the AP is woken up. + * When the buffer is full and FLP_BATCH_WAKEUP_ON_FIFO_FULL is not set, + * the oldest location object is dropped. In this case the AP will not be + * woken up. The upper layer will use get_batched_location + * API to explicitly ask for the location. + * If FLP_BATCH_CALLBACK_ON_LOCATION_FIX is set, the implementation + * will call the flp_location_callback every single time there is a location + * fix. This overrides FLP_BATCH_WAKEUP_ON_FIFO_FULL flag setting. + * It's the responsibility of the upper layers (caller) to switch + * it off, if it knows that the AP might go to sleep. This is useful + * for nagivational applications when the system is in high power mode. + * Parameters: + * id - Id for the request. + * options - See FlpBatchOptions struct definition. + * Return value: + * FLP_RESULT_SUCCESS on success, FLP_RESULT_INSUFFICIENT_MEMORY, + * FLP_RESULT_ID_EXISTS, FLP_RESULT_ERROR on failure. + */ + int (*start_batching)(int id, FlpBatchOptions* options); + + /** + * Update FlpBatchOptions associated with a batching request. + * When a batching operation is in progress and a batching option + * such as FLP_BATCH_WAKEUP_ON_FIFO_FULL needs to be updated, this API + * will be used. For instance, this can happen when the AP is awake and + * the maps application is being used. + * Parameters: + * id - Id of an existing batch request. + * new_options - Updated FlpBatchOptions + * Return value: + * FLP_RESULT_SUCCESS on success, FLP_RESULT_ID_UNKNOWN, + * FLP_RESULT_ERROR on error. + */ + int (*update_batching_options)(int id, FlpBatchOptions* new_options); + + /** + * Stop batching. + * Parameters: + * id - Id for the request. + * Return Value: + * FLP_RESULT_SUCCESS on success, FLP_RESULT_ID_UNKNOWN or + * FLP_RESULT_ERROR on failure. + */ + int (*stop_batching)(int id); + + /** + * Closes the interface. If any batch operations are in progress, + * they should be stopped. + */ + void (*cleanup)(); + + /** + * Get the fused location that was batched. + * flp_location_callback is used to return the location. The location object + * is dropped from the buffer only when the buffer is full. Do not remove it + * from the buffer just because it has been returned using the callback. + * In other words, when there is no new location object, two calls to + * get_batched_location(1) should return the same location object. + * Parameters: + * last_n_locations - Number of locations to get. This can be one or many. + * If the last_n_locations is 1, you get the latest location known to the + * hardware. + */ + void (*get_batched_location)(int last_n_locations); + + /** + * Injects current location from another location provider + * latitude and longitude are measured in degrees + * expected accuracy is measured in meters + * Parameters: + * location - The location object being injected. + * Return value: FLP_RESULT_SUCCESS or FLP_RESULT_ERROR. + */ + int (*inject_location)(FlpLocation* location); + + /** + * Get a pointer to extension information. + */ + const void* (*get_extension)(const char* name); + + /** + * Retrieve all batched locations currently stored and clear the buffer. + * flp_location_callback MUST be called in response, even if there are + * no locations to flush (in which case num_locations should be 0). + * Subsequent calls to get_batched_location or flush_batched_locations + * should not return any of the locations returned in this call. + */ + void (*flush_batched_locations)(); +} FlpLocationInterface; + +struct flp_device_t { + struct hw_device_t common; + + /** + * Get a handle to the FLP Interface. + */ + const FlpLocationInterface* (*get_flp_interface)(struct flp_device_t* dev); +}; + +/** + * Callback for reports diagnostic data into the Java framework code. +*/ +typedef void (*report_data)(char* data, int length); + +/** + * FLP diagnostic callback structure. + * Currently, not used - but this for future extension. + */ +typedef struct { + /** set to sizeof(FlpDiagnosticCallbacks) */ + size_t size; + + flp_set_thread_event set_thread_event_cb; + + /** reports diagnostic data into the Java framework code */ + report_data data_cb; +} FlpDiagnosticCallbacks; + +/** Extended interface for diagnostic support. */ +typedef struct { + /** set to sizeof(FlpDiagnosticInterface) */ + size_t size; + + /** + * Opens the diagnostic interface and provides the callback routines + * to the implemenation of this interface. + */ + void (*init)(FlpDiagnosticCallbacks* callbacks); + + /** + * Injects diagnostic data into the FLP subsystem. + * Return 0 on success, -1 on error. + **/ + int (*inject_data)(char* data, int length ); +} FlpDiagnosticInterface; + +/** + * Context setting information. + * All these settings shall be injected to FLP HAL at FLP init time. + * Following that, only the changed setting need to be re-injected + * upon changes. + */ + +#define FLP_DEVICE_CONTEXT_GPS_ENABLED (1U<<0) +#define FLP_DEVICE_CONTEXT_AGPS_ENABLED (1U<<1) +#define FLP_DEVICE_CONTEXT_NETWORK_POSITIONING_ENABLED (1U<<2) +#define FLP_DEVICE_CONTEXT_WIFI_CONNECTIVITY_ENABLED (1U<<3) +#define FLP_DEVICE_CONTEXT_WIFI_POSITIONING_ENABLED (1U<<4) +#define FLP_DEVICE_CONTEXT_HW_NETWORK_POSITIONING_ENABLED (1U<<5) +#define FLP_DEVICE_CONTEXT_AIRPLANE_MODE_ON (1U<<6) +#define FLP_DEVICE_CONTEXT_DATA_ENABLED (1U<<7) +#define FLP_DEVICE_CONTEXT_ROAMING_ENABLED (1U<<8) +#define FLP_DEVICE_CONTEXT_CURRENTLY_ROAMING (1U<<9) +#define FLP_DEVICE_CONTEXT_SENSOR_ENABLED (1U<<10) +#define FLP_DEVICE_CONTEXT_BLUETOOTH_ENABLED (1U<<11) +#define FLP_DEVICE_CONTEXT_CHARGER_ON (1U<<12) + +/** Extended interface for device context support. */ +typedef struct { + /** set to sizeof(FlpDeviceContextInterface) */ + size_t size; + + /** + * Injects debug data into the FLP subsystem. + * Return 0 on success, -1 on error. + **/ + int (*inject_device_context)(uint32_t enabledMask); +} FlpDeviceContextInterface; + + +/** + * There are 3 states associated with a Geofence: Inside, Outside, Unknown. + * There are 3 transitions: ENTERED, EXITED, UNCERTAIN. + * + * An example state diagram with confidence level: 95% and Unknown time limit + * set as 30 secs is shown below. (confidence level and Unknown time limit are + * explained latter) + * ____________________________ + * | Unknown (30 secs) | + * """""""""""""""""""""""""""" + * ^ | | ^ + * UNCERTAIN| |ENTERED EXITED| |UNCERTAIN + * | v v | + * ________ EXITED _________ + * | Inside | -----------> | Outside | + * | | <----------- | | + * """""""" ENTERED """"""""" + * + * Inside state: We are 95% confident that the user is inside the geofence. + * Outside state: We are 95% confident that the user is outside the geofence + * Unknown state: Rest of the time. + * + * The Unknown state is better explained with an example: + * + * __________ + * | c| + * | ___ | _______ + * | |a| | | b | + * | """ | """"""" + * | | + * """""""""" + * In the diagram above, "a" and "b" are 2 geofences and "c" is the accuracy + * circle reported by the FLP subsystem. Now with regard to "b", the system is + * confident that the user is outside. But with regard to "a" is not confident + * whether it is inside or outside the geofence. If the accuracy remains the + * same for a sufficient period of time, the UNCERTAIN transition would be + * triggered with the state set to Unknown. If the accuracy improves later, an + * appropriate transition should be triggered. This "sufficient period of time" + * is defined by the parameter in the add_geofence_area API. + * In other words, Unknown state can be interpreted as a state in which the + * FLP subsystem isn't confident enough that the user is either inside or + * outside the Geofence. It moves to Unknown state only after the expiry of the + * timeout. + * + * The geofence callback needs to be triggered for the ENTERED and EXITED + * transitions, when the FLP system is confident that the user has entered + * (Inside state) or exited (Outside state) the Geofence. An implementation + * which uses a value of 95% as the confidence is recommended. The callback + * should be triggered only for the transitions requested by the + * add_geofence_area call. + * + * Even though the diagram and explanation talks about states and transitions, + * the callee is only interested in the transistions. The states are mentioned + * here for illustrative purposes. + * + * Startup Scenario: When the device boots up, if an application adds geofences, + * and then we get an accurate FLP location fix, it needs to trigger the + * appropriate (ENTERED or EXITED) transition for every Geofence it knows about. + * By default, all the Geofences will be in the Unknown state. + * + * When the FLP system is unavailable, flp_geofence_status_callback should be + * called to inform the upper layers of the same. Similarly, when it becomes + * available the callback should be called. This is a global state while the + * UNKNOWN transition described above is per geofence. + * + */ +#define FLP_GEOFENCE_TRANSITION_ENTERED (1L<<0) +#define FLP_GEOFENCE_TRANSITION_EXITED (1L<<1) +#define FLP_GEOFENCE_TRANSITION_UNCERTAIN (1L<<2) + +#define FLP_GEOFENCE_MONITOR_STATUS_UNAVAILABLE (1L<<0) +#define FLP_GEOFENCE_MONITOR_STATUS_AVAILABLE (1L<<1) + +/** + * The callback associated with the geofence. + * Parameters: + * geofence_id - The id associated with the add_geofence_area. + * location - The current location as determined by the FLP subsystem. + * transition - Can be one of FLP_GEOFENCE_TRANSITION_ENTERED, FLP_GEOFENCE_TRANSITION_EXITED, + * FLP_GEOFENCE_TRANSITION_UNCERTAIN. + * timestamp - Timestamp when the transition was detected; -1 if not available. + * sources_used - Bitwise OR of FLP_TECH_MASK flags indicating which + * subsystems were used. + * + * The callback should only be called when the caller is interested in that + * particular transition. For instance, if the caller is interested only in + * ENTERED transition, then the callback should NOT be called with the EXITED + * transition. + * + * IMPORTANT: If a transition is triggered resulting in this callback, the + * subsystem will wake up the application processor, if its in suspend state. + */ +typedef void (*flp_geofence_transition_callback) (int32_t geofence_id, FlpLocation* location, + int32_t transition, FlpUtcTime timestamp, uint32_t sources_used); + +/** + * The callback associated with the availablity of one the sources used for geofence + * monitoring by the FLP sub-system For example, if the GPS system determines that it cannot + * monitor geofences because of lack of reliability or unavailability of the GPS signals, + * it will call this callback with FLP_GEOFENCE_MONITOR_STATUS_UNAVAILABLE parameter and the + * source set to FLP_TECH_MASK_GNSS. + * + * Parameters: + * status - FLP_GEOFENCE_MONITOR_STATUS_UNAVAILABLE or FLP_GEOFENCE_MONITOR_STATUS_AVAILABLE. + * source - One of the FLP_TECH_MASKS + * last_location - Last known location. + */ +typedef void (*flp_geofence_monitor_status_callback) (int32_t status, uint32_t source, + FlpLocation* last_location); + +/** + * The callback associated with the add_geofence call. + * + * Parameter: + * geofence_id - Id of the geofence. + * result - FLP_RESULT_SUCCESS + * FLP_RESULT_ERROR_TOO_MANY_GEOFENCES - geofence limit has been reached. + * FLP_RESULT_ID_EXISTS - geofence with id already exists + * FLP_RESULT_INVALID_GEOFENCE_TRANSITION - the monitorTransition contains an + * invalid transition + * FLP_RESULT_ERROR - for other errors. + */ +typedef void (*flp_geofence_add_callback) (int32_t geofence_id, int32_t result); + +/** + * The callback associated with the remove_geofence call. + * + * Parameter: + * geofence_id - Id of the geofence. + * result - FLP_RESULT_SUCCESS + * FLP_RESULT_ID_UNKNOWN - for invalid id + * FLP_RESULT_ERROR for others. + */ +typedef void (*flp_geofence_remove_callback) (int32_t geofence_id, int32_t result); + + +/** + * The callback associated with the pause_geofence call. + * + * Parameter: + * geofence_id - Id of the geofence. + * result - FLP_RESULT_SUCCESS + * FLP_RESULT__ID_UNKNOWN - for invalid id + * FLP_RESULT_INVALID_TRANSITION - + * when monitor_transitions is invalid + * FLP_RESULT_ERROR for others. + */ +typedef void (*flp_geofence_pause_callback) (int32_t geofence_id, int32_t result); + +/** + * The callback associated with the resume_geofence call. + * + * Parameter: + * geofence_id - Id of the geofence. + * result - FLP_RESULT_SUCCESS + * FLP_RESULT_ID_UNKNOWN - for invalid id + * FLP_RESULT_ERROR for others. + */ +typedef void (*flp_geofence_resume_callback) (int32_t geofence_id, int32_t result); + +typedef struct { + /** set to sizeof(FlpGeofenceCallbacks) */ + size_t size; + flp_geofence_transition_callback geofence_transition_callback; + flp_geofence_monitor_status_callback geofence_status_callback; + flp_geofence_add_callback geofence_add_callback; + flp_geofence_remove_callback geofence_remove_callback; + flp_geofence_pause_callback geofence_pause_callback; + flp_geofence_resume_callback geofence_resume_callback; + flp_set_thread_event set_thread_event_cb; + flp_capabilities_callback flp_capabilities_cb; +} FlpGeofenceCallbacks; + + +/** Type of geofence */ +typedef enum { + TYPE_CIRCLE = 0, +} GeofenceType; + +/** Circular geofence is represented by lat / long / radius */ +typedef struct { + double latitude; + double longitude; + double radius_m; +} GeofenceCircle; + +/** Represents the type of geofence and data */ +typedef struct { + GeofenceType type; + union { + GeofenceCircle circle; + } geofence; +} GeofenceData; + +/** Geofence Options */ +typedef struct { + /** + * The current state of the geofence. For example, if + * the system already knows that the user is inside the geofence, + * this will be set to FLP_GEOFENCE_TRANSITION_ENTERED. In most cases, it + * will be FLP_GEOFENCE_TRANSITION_UNCERTAIN. */ + int last_transition; + + /** + * Transitions to monitor. Bitwise OR of + * FLP_GEOFENCE_TRANSITION_ENTERED, FLP_GEOFENCE_TRANSITION_EXITED and + * FLP_GEOFENCE_TRANSITION_UNCERTAIN. + */ + int monitor_transitions; + + /** + * Defines the best-effort description + * of how soon should the callback be called when the transition + * associated with the Geofence is triggered. For instance, if set + * to 1000 millseconds with FLP_GEOFENCE_TRANSITION_ENTERED, the callback + * should be called 1000 milliseconds within entering the geofence. + * This parameter is defined in milliseconds. + * NOTE: This is not to be confused with the rate that the GPS is + * polled at. It is acceptable to dynamically vary the rate of + * sampling the GPS for power-saving reasons; thus the rate of + * sampling may be faster or slower than this. + */ + int notification_responsivenes_ms; + + /** + * The time limit after which the UNCERTAIN transition + * should be triggered. This paramter is defined in milliseconds. + */ + int unknown_timer_ms; + + /** + * The sources to use for monitoring geofences. Its a BITWISE-OR + * of FLP_TECH_MASK flags. + */ + uint32_t sources_to_use; +} GeofenceOptions; + +/** Geofence struct */ +typedef struct { + int32_t geofence_id; + GeofenceData* data; + GeofenceOptions* options; +} Geofence; + +/** Extended interface for FLP_Geofencing support */ +typedef struct { + /** set to sizeof(FlpGeofencingInterface) */ + size_t size; + + /** + * Opens the geofence interface and provides the callback routines + * to the implemenation of this interface. Once called you should respond + * by calling the flp_capabilities_callback in FlpGeofenceCallbacks to + * specify the capabilities that your implementation supports. + */ + void (*init)( FlpGeofenceCallbacks* callbacks ); + + /** + * Add a list of geofences. + * Parameters: + * number_of_geofences - The number of geofences that needed to be added. + * geofences - Pointer to array of pointers to Geofence structure. + */ + void (*add_geofences) (int32_t number_of_geofences, Geofence** geofences); + + /** + * Pause monitoring a particular geofence. + * Parameters: + * geofence_id - The id for the geofence. + */ + void (*pause_geofence) (int32_t geofence_id); + + /** + * Resume monitoring a particular geofence. + * Parameters: + * geofence_id - The id for the geofence. + * monitor_transitions - Which transitions to monitor. Bitwise OR of + * FLP_GEOFENCE_TRANSITION_ENTERED, FLP_GEOFENCE_TRANSITION_EXITED and + * FLP_GEOFENCE_TRANSITION_UNCERTAIN. + * This supersedes the value associated provided in the + * add_geofence_area call. + */ + void (*resume_geofence) (int32_t geofence_id, int monitor_transitions); + + /** + * Modify a particular geofence option. + * Parameters: + * geofence_id - The id for the geofence. + * options - Various options associated with the geofence. See + * GeofenceOptions structure for details. + */ + void (*modify_geofence_option) (int32_t geofence_id, GeofenceOptions* options); + + /** + * Remove a list of geofences. After the function returns, no notifications + * should be sent. + * Parameter: + * number_of_geofences - The number of geofences that needed to be added. + * geofence_id - Pointer to array of geofence_ids to be removed. + */ + void (*remove_geofences) (int32_t number_of_geofences, int32_t* geofence_id); +} FlpGeofencingInterface; + +__END_DECLS + +#endif /* ANDROID_INCLUDE_HARDWARE_FLP_H */ + diff --git a/phonelibs/android_hardware_libhardware/include/hardware/gatekeeper.h b/phonelibs/android_hardware_libhardware/include/hardware/gatekeeper.h new file mode 100644 index 0000000000..2bb2b08c39 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/gatekeeper.h @@ -0,0 +1,190 @@ +/* + * 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_HARDWARE_GATEKEEPER_H +#define ANDROID_HARDWARE_GATEKEEPER_H + +#include +#include +#include + +__BEGIN_DECLS + +#define GATEKEEPER_HARDWARE_MODULE_ID "gatekeeper" + +#define GATEKEEPER_MODULE_API_VERSION_0_1 HARDWARE_MODULE_API_VERSION(0, 1) + +#define HARDWARE_GATEKEEPER "gatekeeper" + +struct gatekeeper_module { + /** + * Comon methods of the gatekeeper module. This *must* be the first member of + * gatekeeper_module as users of this structure will cast a hw_module_t to + * a gatekeeper_module pointer in the appropriate context. + */ + hw_module_t common; +}; + +struct gatekeeper_device { + /** + * Common methods of the gatekeeper device. As above, this must be the first + * member of keymaster_device. + */ + hw_device_t common; + + /** + * Enrolls desired_password, which should be derived from a user selected pin or password, + * with the authentication factor private key used only for enrolling authentication + * factor data. + * + * If there was already a password enrolled, it should be provided in + * current_password_handle, along with the current password in current_password + * that should validate against current_password_handle. + * + * Parameters: + * - dev: pointer to gatekeeper_device acquired via calls to gatekeeper_open + * - uid: the Android user identifier + * + * - current_password_handle: the currently enrolled password handle the user + * wants to replace. May be null if there's no currently enrolled password. + * - current_password_handle_length: the length in bytes of the buffer pointed + * at by current_password_handle. Must be 0 if current_password_handle is NULL. + * + * - current_password: the user's current password in plain text. If presented, + * it MUST verify against current_password_handle. + * - current_password_length: the size in bytes of the buffer pointed at by + * current_password. Must be 0 if the current_password is NULL. + * + * - desired_password: the new password the user wishes to enroll in plain-text. + * Cannot be NULL. + * - desired_password_length: the length in bytes of the buffer pointed at by + * desired_password. + * + * - enrolled_password_handle: on success, a buffer will be allocated with the + * new password handle referencing the password provided in desired_password. + * This buffer can be used on subsequent calls to enroll or verify. + * The caller is responsible for deallocating this buffer via a call to delete[] + * - enrolled_password_handle_length: pointer to the length in bytes of the buffer allocated + * by this function and pointed to by *enrolled_password_handle_length. + * + * Returns: + * - 0 on success + * - An error code < 0 on failure, or + * - A timeout value T > 0 if the call should not be re-attempted until T milliseconds + * have elapsed. + * + * On error, enrolled_password_handle will not be allocated. + */ + int (*enroll)(const struct gatekeeper_device *dev, uint32_t uid, + const uint8_t *current_password_handle, uint32_t current_password_handle_length, + const uint8_t *current_password, uint32_t current_password_length, + const uint8_t *desired_password, uint32_t desired_password_length, + uint8_t **enrolled_password_handle, uint32_t *enrolled_password_handle_length); + + /** + * Verifies provided_password matches enrolled_password_handle. + * + * Implementations of this module may retain the result of this call + * to attest to the recency of authentication. + * + * On success, writes the address of a verification token to auth_token, + * usable to attest password verification to other trusted services. Clients + * may pass NULL for this value. + * + * Parameters: + * - dev: pointer to gatekeeper_device acquired via calls to gatekeeper_open + * - uid: the Android user identifier + * + * - challenge: An optional challenge to authenticate against, or 0. Used when a separate + * authenticator requests password verification, or for transactional + * password authentication. + * + * - enrolled_password_handle: the currently enrolled password handle that the + * user wishes to verify against. + * - enrolled_password_handle_length: the length in bytes of the buffer pointed + * to by enrolled_password_handle + * + * - provided_password: the plaintext password to be verified against the + * enrolled_password_handle + * - provided_password_length: the length in bytes of the buffer pointed to by + * provided_password + * + * - auth_token: on success, a buffer containing the authentication token + * resulting from this verification is assigned to *auth_token. The caller + * is responsible for deallocating this memory via a call to delete[] + * - auth_token_length: on success, the length in bytes of the authentication + * token assigned to *auth_token will be assigned to *auth_token_length + * + * - request_reenroll: a request to the upper layers to re-enroll the verified + * password due to a version change. Not set if verification fails. + * + * Returns: + * - 0 on success + * - An error code < 0 on failure, or + * - A timeout value T > 0 if the call should not be re-attempted until T milliseconds + * have elapsed. + * On error, auth token will not be allocated + */ + int (*verify)(const struct gatekeeper_device *dev, uint32_t uid, uint64_t challenge, + const uint8_t *enrolled_password_handle, uint32_t enrolled_password_handle_length, + const uint8_t *provided_password, uint32_t provided_password_length, + uint8_t **auth_token, uint32_t *auth_token_length, bool *request_reenroll); + + /* + * Deletes the enrolled_password_handle associated wth the uid. Once deleted + * the user cannot be verified anymore. + * This function is optional and should be set to NULL if it is not implemented. + * + * Parameters + * - dev: pointer to gatekeeper_device acquired via calls to gatekeeper_open + * - uid: the Android user identifier + * + * Returns: + * - 0 on success + * - An error code < 0 on failure + */ + int (*delete_user)(const struct gatekeeper_device *dev, uint32_t uid); + + /* + * Deletes all the enrolled_password_handles for all uid's. Once called, + * no users will be enrolled on the device. + * This function is optional and should be set to NULL if it is not implemented. + * + * Parameters + * - dev: pointer to gatekeeper_device acquired via calls to gatekeeper_open + * + * Returns: + * - 0 on success + * - An error code < 0 on failure + */ + int (*delete_all_users)(const struct gatekeeper_device *dev); +}; + +typedef struct gatekeeper_device gatekeeper_device_t; + +static inline int gatekeeper_open(const struct hw_module_t *module, + gatekeeper_device_t **device) { + return module->methods->open(module, HARDWARE_GATEKEEPER, + (struct hw_device_t **) device); +} + +static inline int gatekeeper_close(gatekeeper_device_t *device) { + return device->common.close(&device->common); +} + +__END_DECLS + +#endif // ANDROID_HARDWARE_GATEKEEPER_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/gps.h b/phonelibs/android_hardware_libhardware/include/hardware/gps.h new file mode 100644 index 0000000000..76b6cb7aed --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/gps.h @@ -0,0 +1,1871 @@ +/* + * 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_INCLUDE_HARDWARE_GPS_H +#define ANDROID_INCLUDE_HARDWARE_GPS_H + +#include +#include +#include +#include +#include +#include + +#include + +__BEGIN_DECLS + +/** + * The id of this module + */ +#define GPS_HARDWARE_MODULE_ID "gps" + + +/** Milliseconds since January 1, 1970 */ +typedef int64_t GpsUtcTime; + +/** Maximum number of SVs for gps_sv_status_callback(). */ +#define GPS_MAX_SVS 32 + +/** Maximum number of Measurements in gps_measurement_callback(). */ +#define GPS_MAX_MEASUREMENT 32 + +/** Requested operational mode for GPS operation. */ +typedef uint32_t GpsPositionMode; +// IMPORTANT: Note that the following values must match +// constants in GpsLocationProvider.java. +/** Mode for running GPS standalone (no assistance). */ +#define GPS_POSITION_MODE_STANDALONE 0 +/** AGPS MS-Based mode. */ +#define GPS_POSITION_MODE_MS_BASED 1 +/** + * AGPS MS-Assisted mode. This mode is not maintained by the platform anymore. + * It is strongly recommended to use GPS_POSITION_MODE_MS_BASE instead. + */ +#define GPS_POSITION_MODE_MS_ASSISTED 2 + +/** Requested recurrence mode for GPS operation. */ +typedef uint32_t GpsPositionRecurrence; +// IMPORTANT: Note that the following values must match +// constants in GpsLocationProvider.java. +/** Receive GPS fixes on a recurring basis at a specified period. */ +#define GPS_POSITION_RECURRENCE_PERIODIC 0 +/** Request a single shot GPS fix. */ +#define GPS_POSITION_RECURRENCE_SINGLE 1 + +/** GPS status event values. */ +typedef uint16_t GpsStatusValue; +// IMPORTANT: Note that the following values must match +// constants in GpsLocationProvider.java. +/** GPS status unknown. */ +#define GPS_STATUS_NONE 0 +/** GPS has begun navigating. */ +#define GPS_STATUS_SESSION_BEGIN 1 +/** GPS has stopped navigating. */ +#define GPS_STATUS_SESSION_END 2 +/** GPS has powered on but is not navigating. */ +#define GPS_STATUS_ENGINE_ON 3 +/** GPS is powered off. */ +#define GPS_STATUS_ENGINE_OFF 4 + +/** Flags to indicate which values are valid in a GpsLocation. */ +typedef uint16_t GpsLocationFlags; +// IMPORTANT: Note that the following values must match +// constants in GpsLocationProvider.java. +/** GpsLocation has valid latitude and longitude. */ +#define GPS_LOCATION_HAS_LAT_LONG 0x0001 +/** GpsLocation has valid altitude. */ +#define GPS_LOCATION_HAS_ALTITUDE 0x0002 +/** GpsLocation has valid speed. */ +#define GPS_LOCATION_HAS_SPEED 0x0004 +/** GpsLocation has valid bearing. */ +#define GPS_LOCATION_HAS_BEARING 0x0008 +/** GpsLocation has valid accuracy. */ +#define GPS_LOCATION_HAS_ACCURACY 0x0010 + +/** Flags for the gps_set_capabilities callback. */ + +/** GPS HAL schedules fixes for GPS_POSITION_RECURRENCE_PERIODIC mode. + If this is not set, then the framework will use 1000ms for min_interval + and will start and call start() and stop() to schedule the GPS. + */ +#define GPS_CAPABILITY_SCHEDULING 0x0000001 +/** GPS supports MS-Based AGPS mode */ +#define GPS_CAPABILITY_MSB 0x0000002 +/** GPS supports MS-Assisted AGPS mode */ +#define GPS_CAPABILITY_MSA 0x0000004 +/** GPS supports single-shot fixes */ +#define GPS_CAPABILITY_SINGLE_SHOT 0x0000008 +/** GPS supports on demand time injection */ +#define GPS_CAPABILITY_ON_DEMAND_TIME 0x0000010 +/** GPS supports Geofencing */ +#define GPS_CAPABILITY_GEOFENCING 0x0000020 +/** GPS supports Measurements */ +#define GPS_CAPABILITY_MEASUREMENTS 0x0000040 +/** GPS supports Navigation Messages */ +#define GPS_CAPABILITY_NAV_MESSAGES 0x0000080 + +/** Flags used to specify which aiding data to delete + when calling delete_aiding_data(). */ +typedef uint16_t GpsAidingData; +// IMPORTANT: Note that the following values must match +// constants in GpsLocationProvider.java. +#define GPS_DELETE_EPHEMERIS 0x0001 +#define GPS_DELETE_ALMANAC 0x0002 +#define GPS_DELETE_POSITION 0x0004 +#define GPS_DELETE_TIME 0x0008 +#define GPS_DELETE_IONO 0x0010 +#define GPS_DELETE_UTC 0x0020 +#define GPS_DELETE_HEALTH 0x0040 +#define GPS_DELETE_SVDIR 0x0080 +#define GPS_DELETE_SVSTEER 0x0100 +#define GPS_DELETE_SADATA 0x0200 +#define GPS_DELETE_RTI 0x0400 +#define GPS_DELETE_CELLDB_INFO 0x8000 +#define GPS_DELETE_ALL 0xFFFF + +/** AGPS type */ +typedef uint16_t AGpsType; +#define AGPS_TYPE_SUPL 1 +#define AGPS_TYPE_C2K 2 + +typedef uint16_t AGpsSetIDType; +#define AGPS_SETID_TYPE_NONE 0 +#define AGPS_SETID_TYPE_IMSI 1 +#define AGPS_SETID_TYPE_MSISDN 2 + +typedef uint16_t ApnIpType; +#define APN_IP_INVALID 0 +#define APN_IP_IPV4 1 +#define APN_IP_IPV6 2 +#define APN_IP_IPV4V6 3 + +/** + * String length constants + */ +#define GPS_NI_SHORT_STRING_MAXLEN 256 +#define GPS_NI_LONG_STRING_MAXLEN 2048 + +/** + * GpsNiType constants + */ +typedef uint32_t GpsNiType; +#define GPS_NI_TYPE_VOICE 1 +#define GPS_NI_TYPE_UMTS_SUPL 2 +#define GPS_NI_TYPE_UMTS_CTRL_PLANE 3 + +/** + * GpsNiNotifyFlags constants + */ +typedef uint32_t GpsNiNotifyFlags; +/** NI requires notification */ +#define GPS_NI_NEED_NOTIFY 0x0001 +/** NI requires verification */ +#define GPS_NI_NEED_VERIFY 0x0002 +/** NI requires privacy override, no notification/minimal trace */ +#define GPS_NI_PRIVACY_OVERRIDE 0x0004 + +/** + * GPS NI responses, used to define the response in + * NI structures + */ +typedef int GpsUserResponseType; +#define GPS_NI_RESPONSE_ACCEPT 1 +#define GPS_NI_RESPONSE_DENY 2 +#define GPS_NI_RESPONSE_NORESP 3 + +/** + * NI data encoding scheme + */ +typedef int GpsNiEncodingType; +#define GPS_ENC_NONE 0 +#define GPS_ENC_SUPL_GSM_DEFAULT 1 +#define GPS_ENC_SUPL_UTF8 2 +#define GPS_ENC_SUPL_UCS2 3 +#define GPS_ENC_UNKNOWN -1 + +/** AGPS status event values. */ +typedef uint16_t AGpsStatusValue; +/** GPS requests data connection for AGPS. */ +#define GPS_REQUEST_AGPS_DATA_CONN 1 +/** GPS releases the AGPS data connection. */ +#define GPS_RELEASE_AGPS_DATA_CONN 2 +/** AGPS data connection initiated */ +#define GPS_AGPS_DATA_CONNECTED 3 +/** AGPS data connection completed */ +#define GPS_AGPS_DATA_CONN_DONE 4 +/** AGPS data connection failed */ +#define GPS_AGPS_DATA_CONN_FAILED 5 + +#define AGPS_REF_LOCATION_TYPE_GSM_CELLID 1 +#define AGPS_REF_LOCATION_TYPE_UMTS_CELLID 2 +#define AGPS_REG_LOCATION_TYPE_MAC 3 + +/** Network types for update_network_state "type" parameter */ +#define AGPS_RIL_NETWORK_TYPE_MOBILE 0 +#define AGPS_RIL_NETWORK_TYPE_WIFI 1 +#define AGPS_RIL_NETWORK_TYPE_MOBILE_MMS 2 +#define AGPS_RIL_NETWORK_TYPE_MOBILE_SUPL 3 +#define AGPS_RIL_NETWORK_TTYPE_MOBILE_DUN 4 +#define AGPS_RIL_NETWORK_TTYPE_MOBILE_HIPRI 5 +#define AGPS_RIL_NETWORK_TTYPE_WIMAX 6 + +/** + * Flags to indicate what fields in GpsClock are valid. + */ +typedef uint16_t GpsClockFlags; +/** A valid 'leap second' is stored in the data structure. */ +#define GPS_CLOCK_HAS_LEAP_SECOND (1<<0) +/** A valid 'time uncertainty' is stored in the data structure. */ +#define GPS_CLOCK_HAS_TIME_UNCERTAINTY (1<<1) +/** A valid 'full bias' is stored in the data structure. */ +#define GPS_CLOCK_HAS_FULL_BIAS (1<<2) +/** A valid 'bias' is stored in the data structure. */ +#define GPS_CLOCK_HAS_BIAS (1<<3) +/** A valid 'bias uncertainty' is stored in the data structure. */ +#define GPS_CLOCK_HAS_BIAS_UNCERTAINTY (1<<4) +/** A valid 'drift' is stored in the data structure. */ +#define GPS_CLOCK_HAS_DRIFT (1<<5) +/** A valid 'drift uncertainty' is stored in the data structure. */ +#define GPS_CLOCK_HAS_DRIFT_UNCERTAINTY (1<<6) + +/** + * Enumeration of the available values for the GPS Clock type. + */ +typedef uint8_t GpsClockType; +/** The type is not available ot it is unknown. */ +#define GPS_CLOCK_TYPE_UNKNOWN 0 +/** The source of the time value reported by GPS clock is the local hardware clock. */ +#define GPS_CLOCK_TYPE_LOCAL_HW_TIME 1 +/** + * The source of the time value reported by GPS clock is the GPS time derived from satellites + * (epoch = Jan 6, 1980) + */ +#define GPS_CLOCK_TYPE_GPS_TIME 2 + +/** + * Flags to indicate what fields in GpsMeasurement are valid. + */ +typedef uint32_t GpsMeasurementFlags; +/** A valid 'snr' is stored in the data structure. */ +#define GPS_MEASUREMENT_HAS_SNR (1<<0) +/** A valid 'elevation' is stored in the data structure. */ +#define GPS_MEASUREMENT_HAS_ELEVATION (1<<1) +/** A valid 'elevation uncertainty' is stored in the data structure. */ +#define GPS_MEASUREMENT_HAS_ELEVATION_UNCERTAINTY (1<<2) +/** A valid 'azimuth' is stored in the data structure. */ +#define GPS_MEASUREMENT_HAS_AZIMUTH (1<<3) +/** A valid 'azimuth uncertainty' is stored in the data structure. */ +#define GPS_MEASUREMENT_HAS_AZIMUTH_UNCERTAINTY (1<<4) +/** A valid 'pseudorange' is stored in the data structure. */ +#define GPS_MEASUREMENT_HAS_PSEUDORANGE (1<<5) +/** A valid 'pseudorange uncertainty' is stored in the data structure. */ +#define GPS_MEASUREMENT_HAS_PSEUDORANGE_UNCERTAINTY (1<<6) +/** A valid 'code phase' is stored in the data structure. */ +#define GPS_MEASUREMENT_HAS_CODE_PHASE (1<<7) +/** A valid 'code phase uncertainty' is stored in the data structure. */ +#define GPS_MEASUREMENT_HAS_CODE_PHASE_UNCERTAINTY (1<<8) +/** A valid 'carrier frequency' is stored in the data structure. */ +#define GPS_MEASUREMENT_HAS_CARRIER_FREQUENCY (1<<9) +/** A valid 'carrier cycles' is stored in the data structure. */ +#define GPS_MEASUREMENT_HAS_CARRIER_CYCLES (1<<10) +/** A valid 'carrier phase' is stored in the data structure. */ +#define GPS_MEASUREMENT_HAS_CARRIER_PHASE (1<<11) +/** A valid 'carrier phase uncertainty' is stored in the data structure. */ +#define GPS_MEASUREMENT_HAS_CARRIER_PHASE_UNCERTAINTY (1<<12) +/** A valid 'bit number' is stored in the data structure. */ +#define GPS_MEASUREMENT_HAS_BIT_NUMBER (1<<13) +/** A valid 'time from last bit' is stored in the data structure. */ +#define GPS_MEASUREMENT_HAS_TIME_FROM_LAST_BIT (1<<14) +/** A valid 'doppler shift' is stored in the data structure. */ +#define GPS_MEASUREMENT_HAS_DOPPLER_SHIFT (1<<15) +/** A valid 'doppler shift uncertainty' is stored in the data structure. */ +#define GPS_MEASUREMENT_HAS_DOPPLER_SHIFT_UNCERTAINTY (1<<16) +/** A valid 'used in fix' flag is stored in the data structure. */ +#define GPS_MEASUREMENT_HAS_USED_IN_FIX (1<<17) +/** The value of 'pseudorange rate' is uncorrected. */ +#define GPS_MEASUREMENT_HAS_UNCORRECTED_PSEUDORANGE_RATE (1<<18) + +/** + * Enumeration of the available values for the GPS Measurement's loss of lock. + */ +typedef uint8_t GpsLossOfLock; +/** The indicator is not available or it is unknown. */ +#define GPS_LOSS_OF_LOCK_UNKNOWN 0 +/** The measurement does not present any indication of loss of lock. */ +#define GPS_LOSS_OF_LOCK_OK 1 +/** Loss of lock between previous and current observation: cycle slip possible. */ +#define GPS_LOSS_OF_LOCK_CYCLE_SLIP 2 + +/** + * Enumeration of available values for the GPS Measurement's multipath indicator. + */ +typedef uint8_t GpsMultipathIndicator; +/** The indicator is not available or unknown. */ +#define GPS_MULTIPATH_INDICATOR_UNKNOWN 0 +/** The measurement has been indicated to use multipath. */ +#define GPS_MULTIPATH_INDICATOR_DETECTED 1 +/** The measurement has been indicated Not to use multipath. */ +#define GPS_MULTIPATH_INDICATOR_NOT_USED 2 + +/** + * Flags indicating the GPS measurement state. + * The expected behavior here is for GPS HAL to set all the flags that applies. For + * example, if the state for a satellite is only C/A code locked and bit synchronized, + * and there is still millisecond ambiguity, the state should be set as: + * GPS_MEASUREMENT_STATE_CODE_LOCK|GPS_MEASUREMENT_STATE_BIT_SYNC|GPS_MEASUREMENT_STATE_MSEC_AMBIGUOUS + * If GPS is still searching for a satellite, the corresponding state should be set to + * GPS_MEASUREMENT_STATE_UNKNOWN(0). + */ +typedef uint16_t GpsMeasurementState; +#define GPS_MEASUREMENT_STATE_UNKNOWN 0 +#define GPS_MEASUREMENT_STATE_CODE_LOCK (1<<0) +#define GPS_MEASUREMENT_STATE_BIT_SYNC (1<<1) +#define GPS_MEASUREMENT_STATE_SUBFRAME_SYNC (1<<2) +#define GPS_MEASUREMENT_STATE_TOW_DECODED (1<<3) +#define GPS_MEASUREMENT_STATE_MSEC_AMBIGUOUS (1<<4) + +/** + * Flags indicating the Accumulated Delta Range's states. + */ +typedef uint16_t GpsAccumulatedDeltaRangeState; +#define GPS_ADR_STATE_UNKNOWN 0 +#define GPS_ADR_STATE_VALID (1<<0) +#define GPS_ADR_STATE_RESET (1<<1) +#define GPS_ADR_STATE_CYCLE_SLIP (1<<2) + +/** + * Enumeration of available values to indicate the available GPS Navigation message types. + */ +typedef uint8_t GpsNavigationMessageType; +/** The message type is unknown. */ +#define GPS_NAVIGATION_MESSAGE_TYPE_UNKNOWN 0 +/** L1 C/A message contained in the structure. */ +#define GPS_NAVIGATION_MESSAGE_TYPE_L1CA 1 +/** L2-CNAV message contained in the structure. */ +#define GPS_NAVIGATION_MESSAGE_TYPE_L2CNAV 2 +/** L5-CNAV message contained in the structure. */ +#define GPS_NAVIGATION_MESSAGE_TYPE_L5CNAV 3 +/** CNAV-2 message contained in the structure. */ +#define GPS_NAVIGATION_MESSAGE_TYPE_CNAV2 4 + +/** + * Status of Navigation Message + * When a message is received properly without any parity error in its navigation words, the + * status should be set to NAV_MESSAGE_STATUS_PARITY_PASSED. But if a message is received + * with words that failed parity check, but GPS is able to correct those words, the status + * should be set to NAV_MESSAGE_STATUS_PARITY_REBUILT. + * No need to send any navigation message that contains words with parity error and cannot be + * corrected. + */ +typedef uint16_t NavigationMessageStatus; +#define NAV_MESSAGE_STATUS_UNKONW 0 +#define NAV_MESSAGE_STATUS_PARITY_PASSED (1<<0) +#define NAV_MESSAGE_STATUS_PARITY_REBUILT (1<<1) + +/** + * Name for the GPS XTRA interface. + */ +#define GPS_XTRA_INTERFACE "gps-xtra" + +/** + * Name for the GPS DEBUG interface. + */ +#define GPS_DEBUG_INTERFACE "gps-debug" + +/** + * Name for the AGPS interface. + */ +#define AGPS_INTERFACE "agps" + +/** + * Name of the Supl Certificate interface. + */ +#define SUPL_CERTIFICATE_INTERFACE "supl-certificate" + +/** + * Name for NI interface + */ +#define GPS_NI_INTERFACE "gps-ni" + +/** + * Name for the AGPS-RIL interface. + */ +#define AGPS_RIL_INTERFACE "agps_ril" + +/** + * Name for the GPS_Geofencing interface. + */ +#define GPS_GEOFENCING_INTERFACE "gps_geofencing" + +/** + * Name of the GPS Measurements interface. + */ +#define GPS_MEASUREMENT_INTERFACE "gps_measurement" + +/** + * Name of the GPS navigation message interface. + */ +#define GPS_NAVIGATION_MESSAGE_INTERFACE "gps_navigation_message" + +/** + * Name of the GNSS/GPS configuration interface. + */ +#define GNSS_CONFIGURATION_INTERFACE "gnss_configuration" + + +/** Represents a location. */ +typedef struct { + /** set to sizeof(GpsLocation) */ + size_t size; + /** Contains GpsLocationFlags bits. */ + uint16_t flags; + /** Represents latitude in degrees. */ + double latitude; + /** Represents longitude in degrees. */ + double longitude; + /** Represents altitude in meters above the WGS 84 reference + * ellipsoid. */ + double altitude; + /** Represents speed in meters per second. */ + float speed; + /** Represents heading in degrees. */ + float bearing; + /** Represents expected accuracy in meters. */ + float accuracy; + /** Timestamp for the location fix. */ + GpsUtcTime timestamp; +} GpsLocation; + +/** Represents the status. */ +typedef struct { + /** set to sizeof(GpsStatus) */ + size_t size; + GpsStatusValue status; +} GpsStatus; + +/** Represents SV information. */ +typedef struct { + /** set to sizeof(GpsSvInfo) */ + size_t size; + /** Pseudo-random number for the SV. */ + int prn; + /** Signal to noise ratio. */ + float snr; + /** Elevation of SV in degrees. */ + float elevation; + /** Azimuth of SV in degrees. */ + float azimuth; +} GpsSvInfo; + +/** Represents SV status. */ +typedef struct { + /** set to sizeof(GpsSvStatus) */ + size_t size; + + /** Number of SVs currently visible. */ + int num_svs; + + /** Contains an array of SV information. */ + GpsSvInfo sv_list[GPS_MAX_SVS]; + + /** Represents a bit mask indicating which SVs + * have ephemeris data. + */ + uint32_t ephemeris_mask; + + /** Represents a bit mask indicating which SVs + * have almanac data. + */ + uint32_t almanac_mask; + + /** + * Represents a bit mask indicating which SVs + * were used for computing the most recent position fix. + */ + uint32_t used_in_fix_mask; +} GpsSvStatus; + + +/* 2G and 3G */ +/* In 3G lac is discarded */ +typedef struct { + uint16_t type; + uint16_t mcc; + uint16_t mnc; + uint16_t lac; + uint32_t cid; +} AGpsRefLocationCellID; + +typedef struct { + uint8_t mac[6]; +} AGpsRefLocationMac; + +/** Represents ref locations */ +typedef struct { + uint16_t type; + union { + AGpsRefLocationCellID cellID; + AGpsRefLocationMac mac; + } u; +} AGpsRefLocation; + +/** Callback with location information. + * Can only be called from a thread created by create_thread_cb. + */ +typedef void (* gps_location_callback)(GpsLocation* location); + +/** Callback with status information. + * Can only be called from a thread created by create_thread_cb. + */ +typedef void (* gps_status_callback)(GpsStatus* status); + +/** + * Callback with SV status information. + * Can only be called from a thread created by create_thread_cb. + */ +typedef void (* gps_sv_status_callback)(GpsSvStatus* sv_info); + +/** Callback for reporting NMEA sentences. + * Can only be called from a thread created by create_thread_cb. + */ +typedef void (* gps_nmea_callback)(GpsUtcTime timestamp, const char* nmea, int length); + +/** Callback to inform framework of the GPS engine's capabilities. + * Capability parameter is a bit field of GPS_CAPABILITY_* flags. + */ +typedef void (* gps_set_capabilities)(uint32_t capabilities); + +/** Callback utility for acquiring the GPS wakelock. + * This can be used to prevent the CPU from suspending while handling GPS events. + */ +typedef void (* gps_acquire_wakelock)(); + +/** Callback utility for releasing the GPS wakelock. */ +typedef void (* gps_release_wakelock)(); + +/** Callback for requesting NTP time */ +typedef void (* gps_request_utc_time)(); + +/** Callback for creating a thread that can call into the Java framework code. + * This must be used to create any threads that report events up to the framework. + */ +typedef pthread_t (* gps_create_thread)(const char* name, void (*start)(void *), void* arg); + +/** GPS callback structure. */ +typedef struct { + /** set to sizeof(GpsCallbacks) */ + size_t size; + gps_location_callback location_cb; + gps_status_callback status_cb; + gps_sv_status_callback sv_status_cb; + gps_nmea_callback nmea_cb; + gps_set_capabilities set_capabilities_cb; + gps_acquire_wakelock acquire_wakelock_cb; + gps_release_wakelock release_wakelock_cb; + gps_create_thread create_thread_cb; + gps_request_utc_time request_utc_time_cb; +} GpsCallbacks; + + +/** Represents the standard GPS interface. */ +typedef struct { + /** set to sizeof(GpsInterface) */ + size_t size; + /** + * Opens the interface and provides the callback routines + * to the implementation of this interface. + */ + int (*init)( GpsCallbacks* callbacks ); + + /** Starts navigating. */ + int (*start)( void ); + + /** Stops navigating. */ + int (*stop)( void ); + + /** Closes the interface. */ + void (*cleanup)( void ); + + /** Injects the current time. */ + int (*inject_time)(GpsUtcTime time, int64_t timeReference, + int uncertainty); + + /** Injects current location from another location provider + * (typically cell ID). + * latitude and longitude are measured in degrees + * expected accuracy is measured in meters + */ + int (*inject_location)(double latitude, double longitude, float accuracy); + + /** + * Specifies that the next call to start will not use the + * information defined in the flags. GPS_DELETE_ALL is passed for + * a cold start. + */ + void (*delete_aiding_data)(GpsAidingData flags); + + /** + * min_interval represents the time between fixes in milliseconds. + * preferred_accuracy represents the requested fix accuracy in meters. + * preferred_time represents the requested time to first fix in milliseconds. + * + * 'mode' parameter should be one of GPS_POSITION_MODE_MS_BASE + * or GPS_POSITION_MODE_STANDALONE. + * It is allowed by the platform (and it is recommended) to fallback to + * GPS_POSITION_MODE_MS_BASE if GPS_POSITION_MODE_MS_ASSISTED is passed in, and + * GPS_POSITION_MODE_MS_BASED is supported. + */ + int (*set_position_mode)(GpsPositionMode mode, GpsPositionRecurrence recurrence, + uint32_t min_interval, uint32_t preferred_accuracy, uint32_t preferred_time); + + /** Get a pointer to extension information. */ + const void* (*get_extension)(const char* name); +} GpsInterface; + +/** Callback to request the client to download XTRA data. + * The client should download XTRA data and inject it by calling inject_xtra_data(). + * Can only be called from a thread created by create_thread_cb. + */ +typedef void (* gps_xtra_download_request)(); + +/** Callback structure for the XTRA interface. */ +typedef struct { + gps_xtra_download_request download_request_cb; + gps_create_thread create_thread_cb; +} GpsXtraCallbacks; + +/** Extended interface for XTRA support. */ +typedef struct { + /** set to sizeof(GpsXtraInterface) */ + size_t size; + /** + * Opens the XTRA interface and provides the callback routines + * to the implementation of this interface. + */ + int (*init)( GpsXtraCallbacks* callbacks ); + /** Injects XTRA data into the GPS. */ + int (*inject_xtra_data)( char* data, int length ); +} GpsXtraInterface; + +/** Extended interface for DEBUG support. */ +typedef struct { + /** set to sizeof(GpsDebugInterface) */ + size_t size; + + /** + * This function should return any information that the native + * implementation wishes to include in a bugreport. + */ + size_t (*get_internal_state)(char* buffer, size_t bufferSize); +} GpsDebugInterface; + +#pragma pack(push,4) +// We need to keep the alignment of this data structure to 4-bytes, to ensure that in 64-bit +// environments the size of this legacy definition does not collide with _v2. Implementations should +// be using _v2 and _v3, so it's OK to pay the 'unaligned' penalty in 64-bit if an old +// implementation is still in use. + +/** Represents the status of AGPS. */ +typedef struct { + /** set to sizeof(AGpsStatus_v1) */ + size_t size; + + AGpsType type; + AGpsStatusValue status; +} AGpsStatus_v1; + +#pragma pack(pop) + +/** Represents the status of AGPS augmented with a IPv4 address field. */ +typedef struct { + /** set to sizeof(AGpsStatus_v2) */ + size_t size; + + AGpsType type; + AGpsStatusValue status; + uint32_t ipaddr; +} AGpsStatus_v2; + +/* Represents the status of AGPS augmented to support IPv4 and IPv6. */ +typedef struct { + /** set to sizeof(AGpsStatus_v3) */ + size_t size; + + AGpsType type; + AGpsStatusValue status; + + /** + * Must be set to a valid IPv4 address if the field 'addr' contains an IPv4 + * address, or set to INADDR_NONE otherwise. + */ + uint32_t ipaddr; + + /** + * Must contain the IPv4 (AF_INET) or IPv6 (AF_INET6) address to report. + * Any other value of addr.ss_family will be rejected. + * */ + struct sockaddr_storage addr; +} AGpsStatus_v3; + +typedef AGpsStatus_v3 AGpsStatus; + +/** Callback with AGPS status information. + * Can only be called from a thread created by create_thread_cb. + */ +typedef void (* agps_status_callback)(AGpsStatus* status); + +/** Callback structure for the AGPS interface. */ +typedef struct { + agps_status_callback status_cb; + gps_create_thread create_thread_cb; +} AGpsCallbacks; + + +/** Extended interface for AGPS support. */ +typedef struct { + /** set to sizeof(AGpsInterface_v1) */ + size_t size; + + /** + * Opens the AGPS interface and provides the callback routines + * to the implementation of this interface. + */ + void (*init)( AGpsCallbacks* callbacks ); + /** + * Notifies that a data connection is available and sets + * the name of the APN to be used for SUPL. + */ + int (*data_conn_open)( const char* apn ); + /** + * Notifies that the AGPS data connection has been closed. + */ + int (*data_conn_closed)(); + /** + * Notifies that a data connection is not available for AGPS. + */ + int (*data_conn_failed)(); + /** + * Sets the hostname and port for the AGPS server. + */ + int (*set_server)( AGpsType type, const char* hostname, int port ); +} AGpsInterface_v1; + +/** + * Extended interface for AGPS support, it is augmented to enable to pass + * extra APN data. + */ +typedef struct { + /** set to sizeof(AGpsInterface_v2) */ + size_t size; + + /** + * Opens the AGPS interface and provides the callback routines to the + * implementation of this interface. + */ + void (*init)(AGpsCallbacks* callbacks); + /** + * Deprecated. + * If the HAL supports AGpsInterface_v2 this API will not be used, see + * data_conn_open_with_apn_ip_type for more information. + */ + int (*data_conn_open)(const char* apn); + /** + * Notifies that the AGPS data connection has been closed. + */ + int (*data_conn_closed)(); + /** + * Notifies that a data connection is not available for AGPS. + */ + int (*data_conn_failed)(); + /** + * Sets the hostname and port for the AGPS server. + */ + int (*set_server)(AGpsType type, const char* hostname, int port); + + /** + * Notifies that a data connection is available and sets the name of the + * APN, and its IP type, to be used for SUPL connections. + */ + int (*data_conn_open_with_apn_ip_type)( + const char* apn, + ApnIpType apnIpType); +} AGpsInterface_v2; + +typedef AGpsInterface_v2 AGpsInterface; + +/** Error codes associated with certificate operations */ +#define AGPS_CERTIFICATE_OPERATION_SUCCESS 0 +#define AGPS_CERTIFICATE_ERROR_GENERIC -100 +#define AGPS_CERTIFICATE_ERROR_TOO_MANY_CERTIFICATES -101 + +/** A data structure that represents an X.509 certificate using DER encoding */ +typedef struct { + size_t length; + u_char* data; +} DerEncodedCertificate; + +/** + * A type definition for SHA1 Fingerprints used to identify X.509 Certificates + * The Fingerprint is a digest of the DER Certificate that uniquely identifies it. + */ +typedef struct { + u_char data[20]; +} Sha1CertificateFingerprint; + +/** AGPS Interface to handle SUPL certificate operations */ +typedef struct { + /** set to sizeof(SuplCertificateInterface) */ + size_t size; + + /** + * Installs a set of Certificates used for SUPL connections to the AGPS server. + * If needed the HAL should find out internally any certificates that need to be removed to + * accommodate the certificates to install. + * The certificates installed represent a full set of valid certificates needed to connect to + * AGPS SUPL servers. + * The list of certificates is required, and all must be available at the same time, when trying + * to establish a connection with the AGPS Server. + * + * Parameters: + * certificates - A pointer to an array of DER encoded certificates that are need to be + * installed in the HAL. + * length - The number of certificates to install. + * Returns: + * AGPS_CERTIFICATE_OPERATION_SUCCESS if the operation is completed successfully + * AGPS_CERTIFICATE_ERROR_TOO_MANY_CERTIFICATES if the HAL cannot store the number of + * certificates attempted to be installed, the state of the certificates stored should + * remain the same as before on this error case. + * + * IMPORTANT: + * If needed the HAL should find out internally the set of certificates that need to be + * removed to accommodate the certificates to install. + */ + int (*install_certificates) ( const DerEncodedCertificate* certificates, size_t length ); + + /** + * Notifies the HAL that a list of certificates used for SUPL connections are revoked. It is + * expected that the given set of certificates is removed from the internal store of the HAL. + * + * Parameters: + * fingerprints - A pointer to an array of SHA1 Fingerprints to identify the set of + * certificates to revoke. + * length - The number of fingerprints provided. + * Returns: + * AGPS_CERTIFICATE_OPERATION_SUCCESS if the operation is completed successfully. + * + * IMPORTANT: + * If any of the certificates provided (through its fingerprint) is not known by the HAL, + * it should be ignored and continue revoking/deleting the rest of them. + */ + int (*revoke_certificates) ( const Sha1CertificateFingerprint* fingerprints, size_t length ); +} SuplCertificateInterface; + +/** Represents an NI request */ +typedef struct { + /** set to sizeof(GpsNiNotification) */ + size_t size; + + /** + * An ID generated by HAL to associate NI notifications and UI + * responses + */ + int notification_id; + + /** + * An NI type used to distinguish different categories of NI + * events, such as GPS_NI_TYPE_VOICE, GPS_NI_TYPE_UMTS_SUPL, ... + */ + GpsNiType ni_type; + + /** + * Notification/verification options, combinations of GpsNiNotifyFlags constants + */ + GpsNiNotifyFlags notify_flags; + + /** + * Timeout period to wait for user response. + * Set to 0 for no time out limit. + */ + int timeout; + + /** + * Default response when time out. + */ + GpsUserResponseType default_response; + + /** + * Requestor ID + */ + char requestor_id[GPS_NI_SHORT_STRING_MAXLEN]; + + /** + * Notification message. It can also be used to store client_id in some cases + */ + char text[GPS_NI_LONG_STRING_MAXLEN]; + + /** + * Client name decoding scheme + */ + GpsNiEncodingType requestor_id_encoding; + + /** + * Client name decoding scheme + */ + GpsNiEncodingType text_encoding; + + /** + * A pointer to extra data. Format: + * key_1 = value_1 + * key_2 = value_2 + */ + char extras[GPS_NI_LONG_STRING_MAXLEN]; + +} GpsNiNotification; + +/** Callback with NI notification. + * Can only be called from a thread created by create_thread_cb. + */ +typedef void (*gps_ni_notify_callback)(GpsNiNotification *notification); + +/** GPS NI callback structure. */ +typedef struct +{ + /** + * Sends the notification request from HAL to GPSLocationProvider. + */ + gps_ni_notify_callback notify_cb; + gps_create_thread create_thread_cb; +} GpsNiCallbacks; + +/** + * Extended interface for Network-initiated (NI) support. + */ +typedef struct +{ + /** set to sizeof(GpsNiInterface) */ + size_t size; + + /** Registers the callbacks for HAL to use. */ + void (*init) (GpsNiCallbacks *callbacks); + + /** Sends a response to HAL. */ + void (*respond) (int notif_id, GpsUserResponseType user_response); +} GpsNiInterface; + +struct gps_device_t { + struct hw_device_t common; + + /** + * Set the provided lights to the provided values. + * + * Returns: 0 on succes, error code on failure. + */ + const GpsInterface* (*get_gps_interface)(struct gps_device_t* dev); +}; + +#define AGPS_RIL_REQUEST_SETID_IMSI (1<<0L) +#define AGPS_RIL_REQUEST_SETID_MSISDN (1<<1L) + +#define AGPS_RIL_REQUEST_REFLOC_CELLID (1<<0L) +#define AGPS_RIL_REQUEST_REFLOC_MAC (1<<1L) + +typedef void (*agps_ril_request_set_id)(uint32_t flags); +typedef void (*agps_ril_request_ref_loc)(uint32_t flags); + +typedef struct { + agps_ril_request_set_id request_setid; + agps_ril_request_ref_loc request_refloc; + gps_create_thread create_thread_cb; +} AGpsRilCallbacks; + +/** Extended interface for AGPS_RIL support. */ +typedef struct { + /** set to sizeof(AGpsRilInterface) */ + size_t size; + /** + * Opens the AGPS interface and provides the callback routines + * to the implementation of this interface. + */ + void (*init)( AGpsRilCallbacks* callbacks ); + + /** + * Sets the reference location. + */ + void (*set_ref_location) (const AGpsRefLocation *agps_reflocation, size_t sz_struct); + /** + * Sets the set ID. + */ + void (*set_set_id) (AGpsSetIDType type, const char* setid); + + /** + * Send network initiated message. + */ + void (*ni_message) (uint8_t *msg, size_t len); + + /** + * Notify GPS of network status changes. + * These parameters match values in the android.net.NetworkInfo class. + */ + void (*update_network_state) (int connected, int type, int roaming, const char* extra_info); + + /** + * Notify GPS of network status changes. + * These parameters match values in the android.net.NetworkInfo class. + */ + void (*update_network_availability) (int avaiable, const char* apn); +} AGpsRilInterface; + +/** + * GPS Geofence. + * There are 3 states associated with a Geofence: Inside, Outside, Unknown. + * There are 3 transitions: ENTERED, EXITED, UNCERTAIN. + * + * An example state diagram with confidence level: 95% and Unknown time limit + * set as 30 secs is shown below. (confidence level and Unknown time limit are + * explained latter) + * ____________________________ + * | Unknown (30 secs) | + * """""""""""""""""""""""""""" + * ^ | | ^ + * UNCERTAIN| |ENTERED EXITED| |UNCERTAIN + * | v v | + * ________ EXITED _________ + * | Inside | -----------> | Outside | + * | | <----------- | | + * """""""" ENTERED """"""""" + * + * Inside state: We are 95% confident that the user is inside the geofence. + * Outside state: We are 95% confident that the user is outside the geofence + * Unknown state: Rest of the time. + * + * The Unknown state is better explained with an example: + * + * __________ + * | c| + * | ___ | _______ + * | |a| | | b | + * | """ | """"""" + * | | + * """""""""" + * In the diagram above, "a" and "b" are 2 geofences and "c" is the accuracy + * circle reported by the GPS subsystem. Now with regard to "b", the system is + * confident that the user is outside. But with regard to "a" is not confident + * whether it is inside or outside the geofence. If the accuracy remains the + * same for a sufficient period of time, the UNCERTAIN transition would be + * triggered with the state set to Unknown. If the accuracy improves later, an + * appropriate transition should be triggered. This "sufficient period of time" + * is defined by the parameter in the add_geofence_area API. + * In other words, Unknown state can be interpreted as a state in which the + * GPS subsystem isn't confident enough that the user is either inside or + * outside the Geofence. It moves to Unknown state only after the expiry of the + * timeout. + * + * The geofence callback needs to be triggered for the ENTERED and EXITED + * transitions, when the GPS system is confident that the user has entered + * (Inside state) or exited (Outside state) the Geofence. An implementation + * which uses a value of 95% as the confidence is recommended. The callback + * should be triggered only for the transitions requested by the + * add_geofence_area call. + * + * Even though the diagram and explanation talks about states and transitions, + * the callee is only interested in the transistions. The states are mentioned + * here for illustrative purposes. + * + * Startup Scenario: When the device boots up, if an application adds geofences, + * and then we get an accurate GPS location fix, it needs to trigger the + * appropriate (ENTERED or EXITED) transition for every Geofence it knows about. + * By default, all the Geofences will be in the Unknown state. + * + * When the GPS system is unavailable, gps_geofence_status_callback should be + * called to inform the upper layers of the same. Similarly, when it becomes + * available the callback should be called. This is a global state while the + * UNKNOWN transition described above is per geofence. + * + * An important aspect to note is that users of this API (framework), will use + * other subsystems like wifi, sensors, cell to handle Unknown case and + * hopefully provide a definitive state transition to the third party + * application. GPS Geofence will just be a signal indicating what the GPS + * subsystem knows about the Geofence. + * + */ +#define GPS_GEOFENCE_ENTERED (1<<0L) +#define GPS_GEOFENCE_EXITED (1<<1L) +#define GPS_GEOFENCE_UNCERTAIN (1<<2L) + +#define GPS_GEOFENCE_UNAVAILABLE (1<<0L) +#define GPS_GEOFENCE_AVAILABLE (1<<1L) + +#define GPS_GEOFENCE_OPERATION_SUCCESS 0 +#define GPS_GEOFENCE_ERROR_TOO_MANY_GEOFENCES -100 +#define GPS_GEOFENCE_ERROR_ID_EXISTS -101 +#define GPS_GEOFENCE_ERROR_ID_UNKNOWN -102 +#define GPS_GEOFENCE_ERROR_INVALID_TRANSITION -103 +#define GPS_GEOFENCE_ERROR_GENERIC -149 + +/** + * The callback associated with the geofence. + * Parameters: + * geofence_id - The id associated with the add_geofence_area. + * location - The current GPS location. + * transition - Can be one of GPS_GEOFENCE_ENTERED, GPS_GEOFENCE_EXITED, + * GPS_GEOFENCE_UNCERTAIN. + * timestamp - Timestamp when the transition was detected. + * + * The callback should only be called when the caller is interested in that + * particular transition. For instance, if the caller is interested only in + * ENTERED transition, then the callback should NOT be called with the EXITED + * transition. + * + * IMPORTANT: If a transition is triggered resulting in this callback, the GPS + * subsystem will wake up the application processor, if its in suspend state. + */ +typedef void (*gps_geofence_transition_callback) (int32_t geofence_id, GpsLocation* location, + int32_t transition, GpsUtcTime timestamp); + +/** + * The callback associated with the availability of the GPS system for geofencing + * monitoring. If the GPS system determines that it cannot monitor geofences + * because of lack of reliability or unavailability of the GPS signals, it will + * call this callback with GPS_GEOFENCE_UNAVAILABLE parameter. + * + * Parameters: + * status - GPS_GEOFENCE_UNAVAILABLE or GPS_GEOFENCE_AVAILABLE. + * last_location - Last known location. + */ +typedef void (*gps_geofence_status_callback) (int32_t status, GpsLocation* last_location); + +/** + * The callback associated with the add_geofence call. + * + * Parameter: + * geofence_id - Id of the geofence. + * status - GPS_GEOFENCE_OPERATION_SUCCESS + * GPS_GEOFENCE_ERROR_TOO_MANY_GEOFENCES - geofence limit has been reached. + * GPS_GEOFENCE_ERROR_ID_EXISTS - geofence with id already exists + * GPS_GEOFENCE_ERROR_INVALID_TRANSITION - the monitorTransition contains an + * invalid transition + * GPS_GEOFENCE_ERROR_GENERIC - for other errors. + */ +typedef void (*gps_geofence_add_callback) (int32_t geofence_id, int32_t status); + +/** + * The callback associated with the remove_geofence call. + * + * Parameter: + * geofence_id - Id of the geofence. + * status - GPS_GEOFENCE_OPERATION_SUCCESS + * GPS_GEOFENCE_ERROR_ID_UNKNOWN - for invalid id + * GPS_GEOFENCE_ERROR_GENERIC for others. + */ +typedef void (*gps_geofence_remove_callback) (int32_t geofence_id, int32_t status); + + +/** + * The callback associated with the pause_geofence call. + * + * Parameter: + * geofence_id - Id of the geofence. + * status - GPS_GEOFENCE_OPERATION_SUCCESS + * GPS_GEOFENCE_ERROR_ID_UNKNOWN - for invalid id + * GPS_GEOFENCE_ERROR_INVALID_TRANSITION - + * when monitor_transitions is invalid + * GPS_GEOFENCE_ERROR_GENERIC for others. + */ +typedef void (*gps_geofence_pause_callback) (int32_t geofence_id, int32_t status); + +/** + * The callback associated with the resume_geofence call. + * + * Parameter: + * geofence_id - Id of the geofence. + * status - GPS_GEOFENCE_OPERATION_SUCCESS + * GPS_GEOFENCE_ERROR_ID_UNKNOWN - for invalid id + * GPS_GEOFENCE_ERROR_GENERIC for others. + */ +typedef void (*gps_geofence_resume_callback) (int32_t geofence_id, int32_t status); + +typedef struct { + gps_geofence_transition_callback geofence_transition_callback; + gps_geofence_status_callback geofence_status_callback; + gps_geofence_add_callback geofence_add_callback; + gps_geofence_remove_callback geofence_remove_callback; + gps_geofence_pause_callback geofence_pause_callback; + gps_geofence_resume_callback geofence_resume_callback; + gps_create_thread create_thread_cb; +} GpsGeofenceCallbacks; + +/** Extended interface for GPS_Geofencing support */ +typedef struct { + /** set to sizeof(GpsGeofencingInterface) */ + size_t size; + + /** + * Opens the geofence interface and provides the callback routines + * to the implementation of this interface. + */ + void (*init)( GpsGeofenceCallbacks* callbacks ); + + /** + * Add a geofence area. This api currently supports circular geofences. + * Parameters: + * geofence_id - The id for the geofence. If a geofence with this id + * already exists, an error value (GPS_GEOFENCE_ERROR_ID_EXISTS) + * should be returned. + * latitude, longtitude, radius_meters - The lat, long and radius + * (in meters) for the geofence + * last_transition - The current state of the geofence. For example, if + * the system already knows that the user is inside the geofence, + * this will be set to GPS_GEOFENCE_ENTERED. In most cases, it + * will be GPS_GEOFENCE_UNCERTAIN. + * monitor_transition - Which transitions to monitor. Bitwise OR of + * GPS_GEOFENCE_ENTERED, GPS_GEOFENCE_EXITED and + * GPS_GEOFENCE_UNCERTAIN. + * notification_responsiveness_ms - Defines the best-effort description + * of how soon should the callback be called when the transition + * associated with the Geofence is triggered. For instance, if set + * to 1000 millseconds with GPS_GEOFENCE_ENTERED, the callback + * should be called 1000 milliseconds within entering the geofence. + * This parameter is defined in milliseconds. + * NOTE: This is not to be confused with the rate that the GPS is + * polled at. It is acceptable to dynamically vary the rate of + * sampling the GPS for power-saving reasons; thus the rate of + * sampling may be faster or slower than this. + * unknown_timer_ms - The time limit after which the UNCERTAIN transition + * should be triggered. This parameter is defined in milliseconds. + * See above for a detailed explanation. + */ + void (*add_geofence_area) (int32_t geofence_id, double latitude, double longitude, + double radius_meters, int last_transition, int monitor_transitions, + int notification_responsiveness_ms, int unknown_timer_ms); + + /** + * Pause monitoring a particular geofence. + * Parameters: + * geofence_id - The id for the geofence. + */ + void (*pause_geofence) (int32_t geofence_id); + + /** + * Resume monitoring a particular geofence. + * Parameters: + * geofence_id - The id for the geofence. + * monitor_transitions - Which transitions to monitor. Bitwise OR of + * GPS_GEOFENCE_ENTERED, GPS_GEOFENCE_EXITED and + * GPS_GEOFENCE_UNCERTAIN. + * This supersedes the value associated provided in the + * add_geofence_area call. + */ + void (*resume_geofence) (int32_t geofence_id, int monitor_transitions); + + /** + * Remove a geofence area. After the function returns, no notifications + * should be sent. + * Parameter: + * geofence_id - The id for the geofence. + */ + void (*remove_geofence_area) (int32_t geofence_id); +} GpsGeofencingInterface; + + +/** + * Represents an estimate of the GPS clock time. + */ +typedef struct { + /** set to sizeof(GpsClock) */ + size_t size; + + /** A set of flags indicating the validity of the fields in this data structure. */ + GpsClockFlags flags; + + /** + * Leap second data. + * The sign of the value is defined by the following equation: + * utc_time_ns = time_ns + (full_bias_ns + bias_ns) - leap_second * 1,000,000,000 + * + * If the data is available 'flags' must contain GPS_CLOCK_HAS_LEAP_SECOND. + */ + int16_t leap_second; + + /** + * Indicates the type of time reported by the 'time_ns' field. + * This is a Mandatory field. + */ + GpsClockType type; + + /** + * The GPS receiver internal clock value. This can be either the local hardware clock value + * (GPS_CLOCK_TYPE_LOCAL_HW_TIME), or the current GPS time derived inside GPS receiver + * (GPS_CLOCK_TYPE_GPS_TIME). The field 'type' defines the time reported. + * + * For local hardware clock, this value is expected to be monotonically increasing during + * the reporting session. The real GPS time can be derived by compensating the 'full bias' + * (when it is available) from this value. + * + * For GPS time, this value is expected to be the best estimation of current GPS time that GPS + * receiver can achieve. Set the 'time uncertainty' appropriately when GPS time is specified. + * + * Sub-nanosecond accuracy can be provided by means of the 'bias' field. + * The value contains the 'time uncertainty' in it. + * + * This is a Mandatory field. + */ + int64_t time_ns; + + /** + * 1-Sigma uncertainty associated with the clock's time in nanoseconds. + * The uncertainty is represented as an absolute (single sided) value. + * + * This value should be set if GPS_CLOCK_TYPE_GPS_TIME is set. + * If the data is available 'flags' must contain GPS_CLOCK_HAS_TIME_UNCERTAINTY. + */ + double time_uncertainty_ns; + + /** + * The difference between hardware clock ('time' field) inside GPS receiver and the true GPS + * time since 0000Z, January 6, 1980, in nanoseconds. + * This value is used if and only if GPS_CLOCK_TYPE_LOCAL_HW_TIME is set, and GPS receiver + * has solved the clock for GPS time. + * The caller is responsible for using the 'bias uncertainty' field for quality check. + * + * The sign of the value is defined by the following equation: + * true time (GPS time) = time_ns + (full_bias_ns + bias_ns) + * + * This value contains the 'bias uncertainty' in it. + * If the data is available 'flags' must contain GPS_CLOCK_HAS_FULL_BIAS. + + */ + int64_t full_bias_ns; + + /** + * Sub-nanosecond bias. + * The value contains the 'bias uncertainty' in it. + * + * If the data is available 'flags' must contain GPS_CLOCK_HAS_BIAS. + */ + double bias_ns; + + /** + * 1-Sigma uncertainty associated with the clock's bias in nanoseconds. + * The uncertainty is represented as an absolute (single sided) value. + * + * If the data is available 'flags' must contain GPS_CLOCK_HAS_BIAS_UNCERTAINTY. + */ + double bias_uncertainty_ns; + + /** + * The clock's drift in nanoseconds (per second). + * A positive value means that the frequency is higher than the nominal frequency. + * + * The value contains the 'drift uncertainty' in it. + * If the data is available 'flags' must contain GPS_CLOCK_HAS_DRIFT. + * + * If GpsMeasurement's 'flags' field contains GPS_MEASUREMENT_HAS_UNCORRECTED_PSEUDORANGE_RATE, + * it is encouraged that this field is also provided. + */ + double drift_nsps; + + /** + * 1-Sigma uncertainty associated with the clock's drift in nanoseconds (per second). + * The uncertainty is represented as an absolute (single sided) value. + * + * If the data is available 'flags' must contain GPS_CLOCK_HAS_DRIFT_UNCERTAINTY. + */ + double drift_uncertainty_nsps; +} GpsClock; + +/** + * Represents a GPS Measurement, it contains raw and computed information. + */ +typedef struct { + /** set to sizeof(GpsMeasurement) */ + size_t size; + + /** A set of flags indicating the validity of the fields in this data structure. */ + GpsMeasurementFlags flags; + + /** + * Pseudo-random number in the range of [1, 32] + * This is a Mandatory value. + */ + int8_t prn; + + /** + * Time offset at which the measurement was taken in nanoseconds. + * The reference receiver's time is specified by GpsData::clock::time_ns and should be + * interpreted in the same way as indicated by GpsClock::type. + * + * The sign of time_offset_ns is given by the following equation: + * measurement time = GpsClock::time_ns + time_offset_ns + * + * It provides an individual time-stamp for the measurement, and allows sub-nanosecond accuracy. + * This is a Mandatory value. + */ + double time_offset_ns; + + /** + * Per satellite sync state. It represents the current sync state for the associated satellite. + * Based on the sync state, the 'received GPS tow' field should be interpreted accordingly. + * + * This is a Mandatory value. + */ + GpsMeasurementState state; + + /** + * Received GPS Time-of-Week at the measurement time, in nanoseconds. + * The value is relative to the beginning of the current GPS week. + * + * Given the highest sync state that can be achieved, per each satellite, valid range for + * this field can be: + * Searching : [ 0 ] : GPS_MEASUREMENT_STATE_UNKNOWN + * C/A code lock : [ 0 1ms ] : GPS_MEASUREMENT_STATE_CODE_LOCK is set + * Bit sync : [ 0 20ms ] : GPS_MEASUREMENT_STATE_BIT_SYNC is set + * Subframe sync : [ 0 6s ] : GPS_MEASUREMENT_STATE_SUBFRAME_SYNC is set + * TOW decoded : [ 0 1week ] : GPS_MEASUREMENT_STATE_TOW_DECODED is set + * + * However, if there is any ambiguity in integer millisecond, + * GPS_MEASUREMENT_STATE_MSEC_AMBIGUOUS should be set accordingly, in the 'state' field. + * + * This value must be populated if 'state' != GPS_MEASUREMENT_STATE_UNKNOWN. + */ + int64_t received_gps_tow_ns; + + /** + * 1-Sigma uncertainty of the Received GPS Time-of-Week in nanoseconds. + * + * This value must be populated if 'state' != GPS_MEASUREMENT_STATE_UNKNOWN. + */ + int64_t received_gps_tow_uncertainty_ns; + + /** + * Carrier-to-noise density in dB-Hz, in the range [0, 63]. + * It contains the measured C/N0 value for the signal at the antenna input. + * + * This is a Mandatory value. + */ + double c_n0_dbhz; + + /** + * Pseudorange rate at the timestamp in m/s. + * The correction of a given Pseudorange Rate value includes corrections for receiver and + * satellite clock frequency errors. + * + * If GPS_MEASUREMENT_HAS_UNCORRECTED_PSEUDORANGE_RATE is set in 'flags' field, this field must + * be populated with the 'uncorrected' reading. + * If GPS_MEASUREMENT_HAS_UNCORRECTED_PSEUDORANGE_RATE is not set in 'flags' field, this field + * must be populated with the 'corrected' reading. This is the default behavior. + * + * It is encouraged to provide the 'uncorrected' 'pseudorange rate', and provide GpsClock's + * 'drift' field as well. + * + * The value includes the 'pseudorange rate uncertainty' in it. + * A positive 'uncorrected' value indicates that the SV is moving away from the receiver. + * + * The sign of the 'uncorrected' 'pseudorange rate' and its relation to the sign of 'doppler + * shift' is given by the equation: + * pseudorange rate = -k * doppler shift (where k is a constant) + * + * This is a Mandatory value. + */ + double pseudorange_rate_mps; + + /** + * 1-Sigma uncertainty of the pseudurange rate in m/s. + * The uncertainty is represented as an absolute (single sided) value. + * + * This is a Mandatory value. + */ + double pseudorange_rate_uncertainty_mps; + + /** + * Accumulated delta range's state. It indicates whether ADR is reset or there is a cycle slip + * (indicating loss of lock). + * + * This is a Mandatory value. + */ + GpsAccumulatedDeltaRangeState accumulated_delta_range_state; + + /** + * Accumulated delta range since the last channel reset in meters. + * A positive value indicates that the SV is moving away from the receiver. + * + * The sign of the 'accumulated delta range' and its relation to the sign of 'carrier phase' + * is given by the equation: + * accumulated delta range = -k * carrier phase (where k is a constant) + * + * This value must be populated if 'accumulated delta range state' != GPS_ADR_STATE_UNKNOWN. + * However, it is expected that the data is only accurate when: + * 'accumulated delta range state' == GPS_ADR_STATE_VALID. + */ + double accumulated_delta_range_m; + + /** + * 1-Sigma uncertainty of the accumulated delta range in meters. + * This value must be populated if 'accumulated delta range state' != GPS_ADR_STATE_UNKNOWN. + */ + double accumulated_delta_range_uncertainty_m; + + /** + * Best derived Pseudorange by the chip-set, in meters. + * The value contains the 'pseudorange uncertainty' in it. + * + * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_PSEUDORANGE. + */ + double pseudorange_m; + + /** + * 1-Sigma uncertainty of the pseudorange in meters. + * The value contains the 'pseudorange' and 'clock' uncertainty in it. + * The uncertainty is represented as an absolute (single sided) value. + * + * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_PSEUDORANGE_UNCERTAINTY. + */ + double pseudorange_uncertainty_m; + + /** + * A fraction of the current C/A code cycle, in the range [0.0, 1023.0] + * This value contains the time (in Chip units) since the last C/A code cycle (GPS Msec epoch). + * + * The reference frequency is given by the field 'carrier_frequency_hz'. + * The value contains the 'code-phase uncertainty' in it. + * + * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_CODE_PHASE. + */ + double code_phase_chips; + + /** + * 1-Sigma uncertainty of the code-phase, in a fraction of chips. + * The uncertainty is represented as an absolute (single sided) value. + * + * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_CODE_PHASE_UNCERTAINTY. + */ + double code_phase_uncertainty_chips; + + /** + * Carrier frequency at which codes and messages are modulated, it can be L1 or L2. + * If the field is not set, the carrier frequency is assumed to be L1. + * + * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_CARRIER_FREQUENCY. + */ + float carrier_frequency_hz; + + /** + * The number of full carrier cycles between the satellite and the receiver. + * The reference frequency is given by the field 'carrier_frequency_hz'. + * + * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_CARRIER_CYCLES. + */ + int64_t carrier_cycles; + + /** + * The RF phase detected by the receiver, in the range [0.0, 1.0]. + * This is usually the fractional part of the complete carrier phase measurement. + * + * The reference frequency is given by the field 'carrier_frequency_hz'. + * The value contains the 'carrier-phase uncertainty' in it. + * + * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_CARRIER_PHASE. + */ + double carrier_phase; + + /** + * 1-Sigma uncertainty of the carrier-phase. + * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_CARRIER_PHASE_UNCERTAINTY. + */ + double carrier_phase_uncertainty; + + /** + * An enumeration that indicates the 'loss of lock' state of the event. + */ + GpsLossOfLock loss_of_lock; + + /** + * The number of GPS bits transmitted since Sat-Sun midnight (GPS week). + * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_BIT_NUMBER. + */ + int32_t bit_number; + + /** + * The elapsed time since the last received bit in milliseconds, in the range [0, 20] + * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_TIME_FROM_LAST_BIT. + */ + int16_t time_from_last_bit_ms; + + /** + * Doppler shift in Hz. + * A positive value indicates that the SV is moving toward the receiver. + * + * The reference frequency is given by the field 'carrier_frequency_hz'. + * The value contains the 'doppler shift uncertainty' in it. + * + * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_DOPPLER_SHIFT. + */ + double doppler_shift_hz; + + /** + * 1-Sigma uncertainty of the doppler shift in Hz. + * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_DOPPLER_SHIFT_UNCERTAINTY. + */ + double doppler_shift_uncertainty_hz; + + /** + * An enumeration that indicates the 'multipath' state of the event. + */ + GpsMultipathIndicator multipath_indicator; + + /** + * Signal-to-noise ratio in dB. + * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_SNR. + */ + double snr_db; + + /** + * Elevation in degrees, the valid range is [-90, 90]. + * The value contains the 'elevation uncertainty' in it. + * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_ELEVATION. + */ + double elevation_deg; + + /** + * 1-Sigma uncertainty of the elevation in degrees, the valid range is [0, 90]. + * The uncertainty is represented as the absolute (single sided) value. + * + * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_ELEVATION_UNCERTAINTY. + */ + double elevation_uncertainty_deg; + + /** + * Azimuth in degrees, in the range [0, 360). + * The value contains the 'azimuth uncertainty' in it. + * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_AZIMUTH. + * */ + double azimuth_deg; + + /** + * 1-Sigma uncertainty of the azimuth in degrees, the valid range is [0, 180]. + * The uncertainty is represented as an absolute (single sided) value. + * + * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_AZIMUTH_UNCERTAINTY. + */ + double azimuth_uncertainty_deg; + + /** + * Whether the GPS represented by the measurement was used for computing the most recent fix. + * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_USED_IN_FIX. + */ + bool used_in_fix; +} GpsMeasurement; + +/** Represents a reading of GPS measurements. */ +typedef struct { + /** set to sizeof(GpsData) */ + size_t size; + + /** Number of measurements. */ + size_t measurement_count; + + /** The array of measurements. */ + GpsMeasurement measurements[GPS_MAX_MEASUREMENT]; + + /** The GPS clock time reading. */ + GpsClock clock; +} GpsData; + +/** + * The callback for to report measurements from the HAL. + * + * Parameters: + * data - A data structure containing the measurements. + */ +typedef void (*gps_measurement_callback) (GpsData* data); + +typedef struct { + /** set to sizeof(GpsMeasurementCallbacks) */ + size_t size; + gps_measurement_callback measurement_callback; +} GpsMeasurementCallbacks; + +#define GPS_MEASUREMENT_OPERATION_SUCCESS 0 +#define GPS_MEASUREMENT_ERROR_ALREADY_INIT -100 +#define GPS_MEASUREMENT_ERROR_GENERIC -101 + +/** + * Extended interface for GPS Measurements support. + */ +typedef struct { + /** Set to sizeof(GpsMeasurementInterface) */ + size_t size; + + /** + * Initializes the interface and registers the callback routines with the HAL. + * After a successful call to 'init' the HAL must begin to provide updates at its own phase. + * + * Status: + * GPS_MEASUREMENT_OPERATION_SUCCESS + * GPS_MEASUREMENT_ERROR_ALREADY_INIT - if a callback has already been registered without a + * corresponding call to 'close' + * GPS_MEASUREMENT_ERROR_GENERIC - if any other error occurred, it is expected that the HAL + * will not generate any updates upon returning this error code. + */ + int (*init) (GpsMeasurementCallbacks* callbacks); + + /** + * Stops updates from the HAL, and unregisters the callback routines. + * After a call to stop, the previously registered callbacks must be considered invalid by the + * HAL. + * If stop is invoked without a previous 'init', this function should perform no work. + */ + void (*close) (); + +} GpsMeasurementInterface; + + +/** Represents a GPS navigation message (or a fragment of it). */ +typedef struct { + /** set to sizeof(GpsNavigationMessage) */ + size_t size; + + /** + * Pseudo-random number in the range of [1, 32] + * This is a Mandatory value. + */ + int8_t prn; + + /** + * The type of message contained in the structure. + * This is a Mandatory value. + */ + GpsNavigationMessageType type; + + /** + * The status of the received navigation message. + * No need to send any navigation message that contains words with parity error and cannot be + * corrected. + */ + NavigationMessageStatus status; + + /** + * Message identifier. + * It provides an index so the complete Navigation Message can be assembled. i.e. fo L1 C/A + * subframe 4 and 5, this value corresponds to the 'frame id' of the navigation message. + * Subframe 1, 2, 3 does not contain a 'frame id' and this value can be set to -1. + */ + int16_t message_id; + + /** + * Sub-message identifier. + * If required by the message 'type', this value contains a sub-index within the current + * message (or frame) that is being transmitted. + * i.e. for L1 C/A the submessage id corresponds to the sub-frame id of the navigation message. + */ + int16_t submessage_id; + + /** + * The length of the data (in bytes) contained in the current message. + * If this value is different from zero, 'data' must point to an array of the same size. + * e.g. for L1 C/A the size of the sub-frame will be 40 bytes (10 words, 30 bits/word). + * + * This is a Mandatory value. + */ + size_t data_length; + + /** + * The data of the reported GPS message. + * The bytes (or words) specified using big endian format (MSB first). + * + * For L1 C/A, each subframe contains 10 30-bit GPS words. Each GPS word (30 bits) should be + * fitted into the last 30 bits in a 4-byte word (skip B31 and B32), with MSB first. + */ + uint8_t* data; + +} GpsNavigationMessage; + +/** + * The callback to report an available fragment of a GPS navigation messages from the HAL. + * + * Parameters: + * message - The GPS navigation submessage/subframe representation. + */ +typedef void (*gps_navigation_message_callback) (GpsNavigationMessage* message); + +typedef struct { + /** set to sizeof(GpsNavigationMessageCallbacks) */ + size_t size; + gps_navigation_message_callback navigation_message_callback; +} GpsNavigationMessageCallbacks; + +#define GPS_NAVIGATION_MESSAGE_OPERATION_SUCCESS 0 +#define GPS_NAVIGATION_MESSAGE_ERROR_ALREADY_INIT -100 +#define GPS_NAVIGATION_MESSAGE_ERROR_GENERIC -101 + +/** + * Extended interface for GPS navigation message reporting support. + */ +typedef struct { + /** Set to sizeof(GpsNavigationMessageInterface) */ + size_t size; + + /** + * Initializes the interface and registers the callback routines with the HAL. + * After a successful call to 'init' the HAL must begin to provide updates as they become + * available. + * + * Status: + * GPS_NAVIGATION_MESSAGE_OPERATION_SUCCESS + * GPS_NAVIGATION_MESSAGE_ERROR_ALREADY_INIT - if a callback has already been registered + * without a corresponding call to 'close'. + * GPS_NAVIGATION_MESSAGE_ERROR_GENERIC - if any other error occurred, it is expected that + * the HAL will not generate any updates upon returning this error code. + */ + int (*init) (GpsNavigationMessageCallbacks* callbacks); + + /** + * Stops updates from the HAL, and unregisters the callback routines. + * After a call to stop, the previously registered callbacks must be considered invalid by the + * HAL. + * If stop is invoked without a previous 'init', this function should perform no work. + */ + void (*close) (); + +} GpsNavigationMessageInterface; + +/** + * Interface for passing GNSS configuration contents from platform to HAL. + */ +typedef struct { + /** Set to sizeof(GnssConfigurationInterface) */ + size_t size; + + /** + * Deliver GNSS configuration contents to HAL. + * Parameters: + * config_data - a pointer to a char array which holds what usually is expected from + file(/etc/gps.conf), i.e., a sequence of UTF8 strings separated by '\n'. + * length - total number of UTF8 characters in configuraiton data. + * + * IMPORTANT: + * GPS HAL should expect this function can be called multiple times. And it may be + * called even when GpsLocationProvider is already constructed and enabled. GPS HAL + * should maintain the existing requests for various callback regardless the change + * in configuration data. + */ + void (*configuration_update) (const char* config_data, int32_t length); +} GnssConfigurationInterface; + +__END_DECLS + +#endif /* ANDROID_INCLUDE_HARDWARE_GPS_H */ + diff --git a/phonelibs/android_hardware_libhardware/include/hardware/gralloc.h b/phonelibs/android_hardware_libhardware/include/hardware/gralloc.h new file mode 100644 index 0000000000..07ac0290b4 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/gralloc.h @@ -0,0 +1,401 @@ +/* + * 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_GRALLOC_INTERFACE_H +#define ANDROID_GRALLOC_INTERFACE_H + +#include +#include +#include + +#include +#include +#include + +#include + +#include +#include + +__BEGIN_DECLS + +/** + * Module versioning information for the Gralloc hardware module, based on + * gralloc_module_t.common.module_api_version. + * + * Version History: + * + * GRALLOC_MODULE_API_VERSION_0_1: + * Initial Gralloc hardware module API. + * + * GRALLOC_MODULE_API_VERSION_0_2: + * Add support for flexible YCbCr format with (*lock_ycbcr)() method. + * + * GRALLOC_MODULE_API_VERSION_0_3: + * Add support for fence passing to/from lock/unlock. + */ + +#define GRALLOC_MODULE_API_VERSION_0_1 HARDWARE_MODULE_API_VERSION(0, 1) +#define GRALLOC_MODULE_API_VERSION_0_2 HARDWARE_MODULE_API_VERSION(0, 2) +#define GRALLOC_MODULE_API_VERSION_0_3 HARDWARE_MODULE_API_VERSION(0, 3) + +#define GRALLOC_DEVICE_API_VERSION_0_1 HARDWARE_DEVICE_API_VERSION(0, 1) + +/** + * The id of this module + */ +#define GRALLOC_HARDWARE_MODULE_ID "gralloc" + +/** + * Name of the graphics device to open + */ + +#define GRALLOC_HARDWARE_GPU0 "gpu0" + +enum { + /* buffer is never read in software */ + GRALLOC_USAGE_SW_READ_NEVER = 0x00000000, + /* buffer is rarely read in software */ + GRALLOC_USAGE_SW_READ_RARELY = 0x00000002, + /* buffer is often read in software */ + GRALLOC_USAGE_SW_READ_OFTEN = 0x00000003, + /* mask for the software read values */ + GRALLOC_USAGE_SW_READ_MASK = 0x0000000F, + + /* buffer is never written in software */ + GRALLOC_USAGE_SW_WRITE_NEVER = 0x00000000, + /* buffer is rarely written in software */ + GRALLOC_USAGE_SW_WRITE_RARELY = 0x00000020, + /* buffer is often written in software */ + GRALLOC_USAGE_SW_WRITE_OFTEN = 0x00000030, + /* mask for the software write values */ + GRALLOC_USAGE_SW_WRITE_MASK = 0x000000F0, + + /* buffer will be used as an OpenGL ES texture */ + GRALLOC_USAGE_HW_TEXTURE = 0x00000100, + /* buffer will be used as an OpenGL ES render target */ + GRALLOC_USAGE_HW_RENDER = 0x00000200, + /* buffer will be used by the 2D hardware blitter */ + GRALLOC_USAGE_HW_2D = 0x00000400, + /* buffer will be used by the HWComposer HAL module */ + GRALLOC_USAGE_HW_COMPOSER = 0x00000800, + /* buffer will be used with the framebuffer device */ + GRALLOC_USAGE_HW_FB = 0x00001000, + + /* buffer should be displayed full-screen on an external display when + * possible */ + GRALLOC_USAGE_EXTERNAL_DISP = 0x00002000, + + /* Must have a hardware-protected path to external display sink for + * this buffer. If a hardware-protected path is not available, then + * either don't composite only this buffer (preferred) to the + * external sink, or (less desirable) do not route the entire + * composition to the external sink. */ + GRALLOC_USAGE_PROTECTED = 0x00004000, + + /* buffer may be used as a cursor */ + GRALLOC_USAGE_CURSOR = 0x00008000, + + /* buffer will be used with the HW video encoder */ + GRALLOC_USAGE_HW_VIDEO_ENCODER = 0x00010000, + /* buffer will be written by the HW camera pipeline */ + GRALLOC_USAGE_HW_CAMERA_WRITE = 0x00020000, + /* buffer will be read by the HW camera pipeline */ + GRALLOC_USAGE_HW_CAMERA_READ = 0x00040000, + /* buffer will be used as part of zero-shutter-lag queue */ + GRALLOC_USAGE_HW_CAMERA_ZSL = 0x00060000, + /* mask for the camera access values */ + GRALLOC_USAGE_HW_CAMERA_MASK = 0x00060000, + /* mask for the software usage bit-mask */ + GRALLOC_USAGE_HW_MASK = 0x00071F00, + + /* buffer will be used as a RenderScript Allocation */ + GRALLOC_USAGE_RENDERSCRIPT = 0x00100000, + + /* Set by the consumer to indicate to the producer that they may attach a + * buffer that they did not detach from the BufferQueue. Will be filtered + * out by GRALLOC_USAGE_ALLOC_MASK, so gralloc modules will not need to + * handle this flag. */ + GRALLOC_USAGE_FOREIGN_BUFFERS = 0x00200000, + + /* Mask of all flags which could be passed to a gralloc module for buffer + * allocation. Any flags not in this mask do not need to be handled by + * gralloc modules. */ + GRALLOC_USAGE_ALLOC_MASK = ~(GRALLOC_USAGE_FOREIGN_BUFFERS), + + /* implementation-specific private usage flags */ + GRALLOC_USAGE_PRIVATE_0 = 0x10000000, + GRALLOC_USAGE_PRIVATE_1 = 0x20000000, + GRALLOC_USAGE_PRIVATE_2 = 0x40000000, + GRALLOC_USAGE_PRIVATE_3 = 0x80000000, + GRALLOC_USAGE_PRIVATE_MASK = 0xF0000000, + +#ifdef EXYNOS4_ENHANCEMENTS + /* SAMSUNG */ + GRALLOC_USAGE_PRIVATE_NONECACHE = 0x00800000, + + GRALLOC_USAGE_HW_FIMC1 = 0x01000000, + GRALLOC_USAGE_HW_ION = 0x02000000, + GRALLOC_USAGE_YUV_ADDR = 0x04000000, + GRALLOC_USAGE_CAMERA = 0x08000000, + + /* SEC Private usage , for Overlay path at HWC */ + GRALLOC_USAGE_HWC_HWOVERLAY = 0x20000000, +#endif +}; + +/*****************************************************************************/ + +/** + * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM + * and the fields of this data structure must begin with hw_module_t + * followed by module specific information. + */ +typedef struct gralloc_module_t { + struct hw_module_t common; + + /* + * (*registerBuffer)() must be called before a buffer_handle_t that has not + * been created with (*alloc_device_t::alloc)() can be used. + * + * This is intended to be used with buffer_handle_t's that have been + * received in this process through IPC. + * + * This function checks that the handle is indeed a valid one and prepares + * it for use with (*lock)() and (*unlock)(). + * + * It is not necessary to call (*registerBuffer)() on a handle created + * with (*alloc_device_t::alloc)(). + * + * returns an error if this buffer_handle_t is not valid. + */ + int (*registerBuffer)(struct gralloc_module_t const* module, + buffer_handle_t handle); + + /* + * (*unregisterBuffer)() is called once this handle is no longer needed in + * this process. After this call, it is an error to call (*lock)(), + * (*unlock)(), or (*registerBuffer)(). + * + * This function doesn't close or free the handle itself; this is done + * by other means, usually through libcutils's native_handle_close() and + * native_handle_free(). + * + * It is an error to call (*unregisterBuffer)() on a buffer that wasn't + * explicitly registered first. + */ + int (*unregisterBuffer)(struct gralloc_module_t const* module, + buffer_handle_t handle); + + /* + * The (*lock)() method is called before a buffer is accessed for the + * specified usage. This call may block, for instance if the h/w needs + * to finish rendering or if CPU caches need to be synchronized. + * + * The caller promises to modify only pixels in the area specified + * by (l,t,w,h). + * + * The content of the buffer outside of the specified area is NOT modified + * by this call. + * + * If usage specifies GRALLOC_USAGE_SW_*, vaddr is filled with the address + * of the buffer in virtual memory. + * + * Note calling (*lock)() on HAL_PIXEL_FORMAT_YCbCr_*_888 buffers will fail + * and return -EINVAL. These buffers must be locked with (*lock_ycbcr)() + * instead. + * + * THREADING CONSIDERATIONS: + * + * It is legal for several different threads to lock a buffer from + * read access, none of the threads are blocked. + * + * However, locking a buffer simultaneously for write or read/write is + * undefined, but: + * - shall not result in termination of the process + * - shall not block the caller + * It is acceptable to return an error or to leave the buffer's content + * into an indeterminate state. + * + * If the buffer was created with a usage mask incompatible with the + * requested usage flags here, -EINVAL is returned. + * + */ + + int (*lock)(struct gralloc_module_t const* module, + buffer_handle_t handle, int usage, + int l, int t, int w, int h, + void** vaddr); + + + /* + * The (*unlock)() method must be called after all changes to the buffer + * are completed. + */ + + int (*unlock)(struct gralloc_module_t const* module, + buffer_handle_t handle); + +#ifdef EXYNOS4_ENHANCEMENTS + int (*getphys) (struct gralloc_module_t const* module, + buffer_handle_t handle, void** paddr); +#endif + + /* reserved for future use */ + int (*perform)(struct gralloc_module_t const* module, + int operation, ... ); + + /* + * The (*lock_ycbcr)() method is like the (*lock)() method, with the + * difference that it fills a struct ycbcr with a description of the buffer + * layout, and zeroes out the reserved fields. + * + * If the buffer format is not compatible with a flexible YUV format (e.g. + * the buffer layout cannot be represented with the ycbcr struct), it + * will return -EINVAL. + * + * This method must work on buffers with HAL_PIXEL_FORMAT_YCbCr_*_888 + * if supported by the device, as well as with any other format that is + * requested by the multimedia codecs when they are configured with a + * flexible-YUV-compatible color-format with android native buffers. + * + * Note that this method may also be called on buffers of other formats, + * including non-YUV formats. + * + * Added in GRALLOC_MODULE_API_VERSION_0_2. + */ + + int (*lock_ycbcr)(struct gralloc_module_t const* module, + buffer_handle_t handle, int usage, + int l, int t, int w, int h, + struct android_ycbcr *ycbcr); + + /* + * The (*lockAsync)() method is like the (*lock)() method except + * that the buffer's sync fence object is passed into the lock + * call instead of requiring the caller to wait for completion. + * + * The gralloc implementation takes ownership of the fenceFd and + * is responsible for closing it when no longer needed. + * + * Added in GRALLOC_MODULE_API_VERSION_0_3. + */ + int (*lockAsync)(struct gralloc_module_t const* module, + buffer_handle_t handle, int usage, + int l, int t, int w, int h, + void** vaddr, int fenceFd); + + /* + * The (*unlockAsync)() method is like the (*unlock)() method + * except that a buffer sync fence object is returned from the + * lock call, representing the completion of any pending work + * performed by the gralloc implementation. + * + * The caller takes ownership of the fenceFd and is responsible + * for closing it when no longer needed. + * + * Added in GRALLOC_MODULE_API_VERSION_0_3. + */ + int (*unlockAsync)(struct gralloc_module_t const* module, + buffer_handle_t handle, int* fenceFd); + + /* + * The (*lockAsync_ycbcr)() method is like the (*lock_ycbcr)() + * method except that the buffer's sync fence object is passed + * into the lock call instead of requiring the caller to wait for + * completion. + * + * The gralloc implementation takes ownership of the fenceFd and + * is responsible for closing it when no longer needed. + * + * Added in GRALLOC_MODULE_API_VERSION_0_3. + */ + int (*lockAsync_ycbcr)(struct gralloc_module_t const* module, + buffer_handle_t handle, int usage, + int l, int t, int w, int h, + struct android_ycbcr *ycbcr, int fenceFd); + + /* reserved for future use */ + void* reserved_proc[3]; +} gralloc_module_t; + +/*****************************************************************************/ + +/** + * Every device data structure must begin with hw_device_t + * followed by module specific public methods and attributes. + */ + +typedef struct alloc_device_t { + struct hw_device_t common; + + /* + * (*alloc)() Allocates a buffer in graphic memory with the requested + * parameters and returns a buffer_handle_t and the stride in pixels to + * allow the implementation to satisfy hardware constraints on the width + * of a pixmap (eg: it may have to be multiple of 8 pixels). + * The CALLER TAKES OWNERSHIP of the buffer_handle_t. + * + * If format is HAL_PIXEL_FORMAT_YCbCr_420_888, the returned stride must be + * 0, since the actual strides are available from the android_ycbcr + * structure. + * + * Returns 0 on success or -errno on error. + */ + + int (*alloc)(struct alloc_device_t* dev, + int w, int h, int format, int usage, + buffer_handle_t* handle, int* stride); + + /* + * (*free)() Frees a previously allocated buffer. + * Behavior is undefined if the buffer is still mapped in any process, + * but shall not result in termination of the program or security breaches + * (allowing a process to get access to another process' buffers). + * THIS FUNCTION TAKES OWNERSHIP of the buffer_handle_t which becomes + * invalid after the call. + * + * Returns 0 on success or -errno on error. + */ + int (*free)(struct alloc_device_t* dev, + buffer_handle_t handle); + + /* This hook is OPTIONAL. + * + * If non NULL it will be caused by SurfaceFlinger on dumpsys + */ + void (*dump)(struct alloc_device_t *dev, char *buff, int buff_len); + + void* reserved_proc[7]; +} alloc_device_t; + + +/** convenience API for opening and closing a supported device */ + +static inline int gralloc_open(const struct hw_module_t* module, + struct alloc_device_t** device) { + return module->methods->open(module, + GRALLOC_HARDWARE_GPU0, (struct hw_device_t**)device); +} + +static inline int gralloc_close(struct alloc_device_t* device) { + return device->common.close(&device->common); +} + +__END_DECLS + +#endif // ANDROID_GRALLOC_INTERFACE_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/hardware.h b/phonelibs/android_hardware_libhardware/include/hardware/hardware.h new file mode 100644 index 0000000000..74f57aa4c2 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/hardware.h @@ -0,0 +1,238 @@ +/* + * 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_INCLUDE_HARDWARE_HARDWARE_H +#define ANDROID_INCLUDE_HARDWARE_HARDWARE_H + +#include +#include + +#include +#include + +__BEGIN_DECLS + +/* + * Value for the hw_module_t.tag field + */ + +#define MAKE_TAG_CONSTANT(A,B,C,D) (((A) << 24) | ((B) << 16) | ((C) << 8) | (D)) + +#define HARDWARE_MODULE_TAG MAKE_TAG_CONSTANT('H', 'W', 'M', 'T') +#define HARDWARE_DEVICE_TAG MAKE_TAG_CONSTANT('H', 'W', 'D', 'T') + +#define HARDWARE_MAKE_API_VERSION(maj,min) \ + ((((maj) & 0xff) << 8) | ((min) & 0xff)) + +#define HARDWARE_MAKE_API_VERSION_2(maj,min,hdr) \ + ((((maj) & 0xff) << 24) | (((min) & 0xff) << 16) | ((hdr) & 0xffff)) +#define HARDWARE_API_VERSION_2_MAJ_MIN_MASK 0xffff0000 +#define HARDWARE_API_VERSION_2_HEADER_MASK 0x0000ffff + + +/* + * The current HAL API version. + * + * All module implementations must set the hw_module_t.hal_api_version field + * to this value when declaring the module with HAL_MODULE_INFO_SYM. + * + * Note that previous implementations have always set this field to 0. + * Therefore, libhardware HAL API will always consider versions 0.0 and 1.0 + * to be 100% binary compatible. + * + */ +#define HARDWARE_HAL_API_VERSION HARDWARE_MAKE_API_VERSION(1, 0) + +/* + * Helper macros for module implementors. + * + * The derived modules should provide convenience macros for supported + * versions so that implementations can explicitly specify module/device + * versions at definition time. + * + * Use this macro to set the hw_module_t.module_api_version field. + */ +#define HARDWARE_MODULE_API_VERSION(maj,min) HARDWARE_MAKE_API_VERSION(maj,min) +#define HARDWARE_MODULE_API_VERSION_2(maj,min,hdr) HARDWARE_MAKE_API_VERSION_2(maj,min,hdr) + +/* + * Use this macro to set the hw_device_t.version field + */ +#define HARDWARE_DEVICE_API_VERSION(maj,min) HARDWARE_MAKE_API_VERSION(maj,min) +#define HARDWARE_DEVICE_API_VERSION_2(maj,min,hdr) HARDWARE_MAKE_API_VERSION_2(maj,min,hdr) + +struct hw_module_t; +struct hw_module_methods_t; +struct hw_device_t; + +/** + * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM + * and the fields of this data structure must begin with hw_module_t + * followed by module specific information. + */ +typedef struct hw_module_t { + /** tag must be initialized to HARDWARE_MODULE_TAG */ + uint32_t tag; + + /** + * The API version of the implemented module. The module owner is + * responsible for updating the version when a module interface has + * changed. + * + * The derived modules such as gralloc and audio own and manage this field. + * The module user must interpret the version field to decide whether or + * not to inter-operate with the supplied module implementation. + * For example, SurfaceFlinger is responsible for making sure that + * it knows how to manage different versions of the gralloc-module API, + * and AudioFlinger must know how to do the same for audio-module API. + * + * The module API version should include a major and a minor component. + * For example, version 1.0 could be represented as 0x0100. This format + * implies that versions 0x0100-0x01ff are all API-compatible. + * + * In the future, libhardware will expose a hw_get_module_version() + * (or equivalent) function that will take minimum/maximum supported + * versions as arguments and would be able to reject modules with + * versions outside of the supplied range. + */ + uint16_t module_api_version; +#define version_major module_api_version + /** + * version_major/version_minor defines are supplied here for temporary + * source code compatibility. They will be removed in the next version. + * ALL clients must convert to the new version format. + */ + + /** + * The API version of the HAL module interface. This is meant to + * version the hw_module_t, hw_module_methods_t, and hw_device_t + * structures and definitions. + * + * The HAL interface owns this field. Module users/implementations + * must NOT rely on this value for version information. + * + * Presently, 0 is the only valid value. + */ + uint16_t hal_api_version; +#define version_minor hal_api_version + + /** Identifier of module */ + const char *id; + + /** Name of this module */ + const char *name; + + /** Author/owner/implementor of the module */ + const char *author; + + /** Modules methods */ + struct hw_module_methods_t* methods; + + /** module's dso */ + void* dso; + +#ifdef __LP64__ + uint64_t reserved[32-7]; +#else + /** padding to 128 bytes, reserved for future use */ + uint32_t reserved[32-7]; +#endif + +} hw_module_t; + +typedef struct hw_module_methods_t { + /** Open a specific device */ + int (*open)(const struct hw_module_t* module, const char* id, + struct hw_device_t** device); + +} hw_module_methods_t; + +/** + * Every device data structure must begin with hw_device_t + * followed by module specific public methods and attributes. + */ +typedef struct hw_device_t { + /** tag must be initialized to HARDWARE_DEVICE_TAG */ + uint32_t tag; + + /** + * Version of the module-specific device API. This value is used by + * the derived-module user to manage different device implementations. + * + * The module user is responsible for checking the module_api_version + * and device version fields to ensure that the user is capable of + * communicating with the specific module implementation. + * + * One module can support multiple devices with different versions. This + * can be useful when a device interface changes in an incompatible way + * but it is still necessary to support older implementations at the same + * time. One such example is the Camera 2.0 API. + * + * This field is interpreted by the module user and is ignored by the + * HAL interface itself. + */ + uint32_t version; + + /** reference to the module this device belongs to */ + struct hw_module_t* module; + + /** padding reserved for future use */ +#ifdef __LP64__ + uint64_t reserved[12]; +#else + uint32_t reserved[12]; +#endif + + /** Close this device */ + int (*close)(struct hw_device_t* device); + +} hw_device_t; + +/** + * Name of the hal_module_info + */ +#define HAL_MODULE_INFO_SYM HMI + +/** + * Name of the hal_module_info as a string + */ +#define HAL_MODULE_INFO_SYM_AS_STR "HMI" + +/** + * Get the module info associated with a module by id. + * + * @return: 0 == success, <0 == error and *module == NULL + */ +int hw_get_module(const char *id, const struct hw_module_t **module); + +/** + * Get the module info associated with a module instance by class 'class_id' + * and instance 'inst'. + * + * Some modules types necessitate multiple instances. For example audio supports + * multiple concurrent interfaces and thus 'audio' is the module class + * and 'primary' or 'a2dp' are module interfaces. This implies that the files + * providing these modules would be named audio.primary..so and + * audio.a2dp..so + * + * @return: 0 == success, <0 == error and *module == NULL + */ +int hw_get_module_by_class(const char *class_id, const char *inst, + const struct hw_module_t **module); + +__END_DECLS + +#endif /* ANDROID_INCLUDE_HARDWARE_HARDWARE_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/hdmi_cec.h b/phonelibs/android_hardware_libhardware/include/hardware/hdmi_cec.h new file mode 100644 index 0000000000..ab70f92e2b --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/hdmi_cec.h @@ -0,0 +1,429 @@ +/* + * Copyright (C) 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_INCLUDE_HARDWARE_HDMI_CEC_H +#define ANDROID_INCLUDE_HARDWARE_HDMI_CEC_H + +#include +#include + +#include + +__BEGIN_DECLS + +#define HDMI_CEC_MODULE_API_VERSION_1_0 HARDWARE_MODULE_API_VERSION(1, 0) +#define HDMI_CEC_MODULE_API_VERSION_CURRENT HDMI_MODULE_API_VERSION_1_0 + +#define HDMI_CEC_DEVICE_API_VERSION_1_0 HARDWARE_DEVICE_API_VERSION(1, 0) +#define HDMI_CEC_DEVICE_API_VERSION_CURRENT HDMI_DEVICE_API_VERSION_1_0 + +#define HDMI_CEC_HARDWARE_MODULE_ID "hdmi_cec" +#define HDMI_CEC_HARDWARE_INTERFACE "hdmi_cec_hw_if" + +typedef enum cec_device_type { + CEC_DEVICE_INACTIVE = -1, + CEC_DEVICE_TV = 0, + CEC_DEVICE_RECORDER = 1, + CEC_DEVICE_RESERVED = 2, + CEC_DEVICE_TUNER = 3, + CEC_DEVICE_PLAYBACK = 4, + CEC_DEVICE_AUDIO_SYSTEM = 5, + CEC_DEVICE_MAX = CEC_DEVICE_AUDIO_SYSTEM +} cec_device_type_t; + +typedef enum cec_logical_address { + CEC_ADDR_TV = 0, + CEC_ADDR_RECORDER_1 = 1, + CEC_ADDR_RECORDER_2 = 2, + CEC_ADDR_TUNER_1 = 3, + CEC_ADDR_PLAYBACK_1 = 4, + CEC_ADDR_AUDIO_SYSTEM = 5, + CEC_ADDR_TUNER_2 = 6, + CEC_ADDR_TUNER_3 = 7, + CEC_ADDR_PLAYBACK_2 = 8, + CEC_ADDR_RECORDER_3 = 9, + CEC_ADDR_TUNER_4 = 10, + CEC_ADDR_PLAYBACK_3 = 11, + CEC_ADDR_RESERVED_1 = 12, + CEC_ADDR_RESERVED_2 = 13, + CEC_ADDR_FREE_USE = 14, + CEC_ADDR_UNREGISTERED = 15, + CEC_ADDR_BROADCAST = 15 +} cec_logical_address_t; + +/* + * HDMI CEC messages + */ +enum cec_message_type { + CEC_MESSAGE_FEATURE_ABORT = 0x00, + CEC_MESSAGE_IMAGE_VIEW_ON = 0x04, + CEC_MESSAGE_TUNER_STEP_INCREMENT = 0x05, + CEC_MESSAGE_TUNER_STEP_DECREMENT = 0x06, + CEC_MESSAGE_TUNER_DEVICE_STATUS = 0x07, + CEC_MESSAGE_GIVE_TUNER_DEVICE_STATUS = 0x08, + CEC_MESSAGE_RECORD_ON = 0x09, + CEC_MESSAGE_RECORD_STATUS = 0x0A, + CEC_MESSAGE_RECORD_OFF = 0x0B, + CEC_MESSAGE_TEXT_VIEW_ON = 0x0D, + CEC_MESSAGE_RECORD_TV_SCREEN = 0x0F, + CEC_MESSAGE_GIVE_DECK_STATUS = 0x1A, + CEC_MESSAGE_DECK_STATUS = 0x1B, + CEC_MESSAGE_SET_MENU_LANGUAGE = 0x32, + CEC_MESSAGE_CLEAR_ANALOG_TIMER = 0x33, + CEC_MESSAGE_SET_ANALOG_TIMER = 0x34, + CEC_MESSAGE_TIMER_STATUS = 0x35, + CEC_MESSAGE_STANDBY = 0x36, + CEC_MESSAGE_PLAY = 0x41, + CEC_MESSAGE_DECK_CONTROL = 0x42, + CEC_MESSAGE_TIMER_CLEARED_STATUS = 0x043, + CEC_MESSAGE_USER_CONTROL_PRESSED = 0x44, + CEC_MESSAGE_USER_CONTROL_RELEASED = 0x45, + CEC_MESSAGE_GIVE_OSD_NAME = 0x46, + CEC_MESSAGE_SET_OSD_NAME = 0x47, + CEC_MESSAGE_SET_OSD_STRING = 0x64, + CEC_MESSAGE_SET_TIMER_PROGRAM_TITLE = 0x67, + CEC_MESSAGE_SYSTEM_AUDIO_MODE_REQUEST = 0x70, + CEC_MESSAGE_GIVE_AUDIO_STATUS = 0x71, + CEC_MESSAGE_SET_SYSTEM_AUDIO_MODE = 0x72, + CEC_MESSAGE_REPORT_AUDIO_STATUS = 0x7A, + CEC_MESSAGE_GIVE_SYSTEM_AUDIO_MODE_STATUS = 0x7D, + CEC_MESSAGE_SYSTEM_AUDIO_MODE_STATUS = 0x7E, + CEC_MESSAGE_ROUTING_CHANGE = 0x80, + CEC_MESSAGE_ROUTING_INFORMATION = 0x81, + CEC_MESSAGE_ACTIVE_SOURCE = 0x82, + CEC_MESSAGE_GIVE_PHYSICAL_ADDRESS = 0x83, + CEC_MESSAGE_REPORT_PHYSICAL_ADDRESS = 0x84, + CEC_MESSAGE_REQUEST_ACTIVE_SOURCE = 0x85, + CEC_MESSAGE_SET_STREAM_PATH = 0x86, + CEC_MESSAGE_DEVICE_VENDOR_ID = 0x87, + CEC_MESSAGE_VENDOR_COMMAND = 0x89, + CEC_MESSAGE_VENDOR_REMOTE_BUTTON_DOWN = 0x8A, + CEC_MESSAGE_VENDOR_REMOTE_BUTTON_UP = 0x8B, + CEC_MESSAGE_GIVE_DEVICE_VENDOR_ID = 0x8C, + CEC_MESSAGE_MENU_REQUEST = 0x8D, + CEC_MESSAGE_MENU_STATUS = 0x8E, + CEC_MESSAGE_GIVE_DEVICE_POWER_STATUS = 0x8F, + CEC_MESSAGE_REPORT_POWER_STATUS = 0x90, + CEC_MESSAGE_GET_MENU_LANGUAGE = 0x91, + CEC_MESSAGE_SELECT_ANALOG_SERVICE = 0x92, + CEC_MESSAGE_SELECT_DIGITAL_SERVICE = 0x93, + CEC_MESSAGE_SET_DIGITAL_TIMER = 0x97, + CEC_MESSAGE_CLEAR_DIGITAL_TIMER = 0x99, + CEC_MESSAGE_SET_AUDIO_RATE = 0x9A, + CEC_MESSAGE_INACTIVE_SOURCE = 0x9D, + CEC_MESSAGE_CEC_VERSION = 0x9E, + CEC_MESSAGE_GET_CEC_VERSION = 0x9F, + CEC_MESSAGE_VENDOR_COMMAND_WITH_ID = 0xA0, + CEC_MESSAGE_CLEAR_EXTERNAL_TIMER = 0xA1, + CEC_MESSAGE_SET_EXTERNAL_TIMER = 0xA2, + CEC_MESSAGE_INITIATE_ARC = 0xC0, + CEC_MESSAGE_REPORT_ARC_INITIATED = 0xC1, + CEC_MESSAGE_REPORT_ARC_TERMINATED = 0xC2, + CEC_MESSAGE_REQUEST_ARC_INITIATION = 0xC3, + CEC_MESSAGE_REQUEST_ARC_TERMINATION = 0xC4, + CEC_MESSAGE_TERMINATE_ARC = 0xC5, + CEC_MESSAGE_ABORT = 0xFF +}; + +/* + * Operand description [Abort Reason] + */ +enum abort_reason { + ABORT_UNRECOGNIZED_MODE = 0, + ABORT_NOT_IN_CORRECT_MODE = 1, + ABORT_CANNOT_PROVIDE_SOURCE = 2, + ABORT_INVALID_OPERAND = 3, + ABORT_REFUSED = 4, + ABORT_UNABLE_TO_DETERMINE = 5 +}; + +/* + * HDMI event type. used for hdmi_event_t. + */ +enum { + HDMI_EVENT_CEC_MESSAGE = 1, + HDMI_EVENT_HOT_PLUG = 2, +}; + +/* + * HDMI hotplug event type. Used when the event + * type is HDMI_EVENT_HOT_PLUG. + */ +enum { + HDMI_NOT_CONNECTED = 0, + HDMI_CONNECTED = 1 +}; + +/* + * error code used for send_message. + */ +enum { + HDMI_RESULT_SUCCESS = 0, + HDMI_RESULT_NACK = 1, /* not acknowledged */ + HDMI_RESULT_BUSY = 2, /* bus is busy */ + HDMI_RESULT_FAIL = 3, +}; + +/* + * HDMI port type. + */ +typedef enum hdmi_port_type { + HDMI_INPUT = 0, + HDMI_OUTPUT = 1 +} hdmi_port_type_t; + +/* + * Flags used for set_option() + */ +enum { + /* When set to false, HAL does not wake up the system upon receiving + * or . Used when user changes the TV + * settings to disable the auto TV on functionality. + * True by default. + */ + HDMI_OPTION_WAKEUP = 1, + + /* When set to false, all the CEC commands are discarded. Used when + * user changes the TV settings to disable CEC functionality. + * True by default. + */ + HDMI_OPTION_ENABLE_CEC = 2, + + /* Setting this flag to false means Android system will stop handling + * CEC service and yield the control over to the microprocessor that is + * powered on through the standby mode. When set to true, the system + * will gain the control over, hence telling the microprocessor to stop + * handling the cec commands. This is called when system goes + * in and out of standby mode to notify the microprocessor that it should + * start/stop handling CEC commands on behalf of the system. + * False by default. + */ + HDMI_OPTION_SYSTEM_CEC_CONTROL = 3, + + /* Option 4 not used */ + + /* Passes the updated language information of Android system. + * Contains 3-byte ASCII code as defined in ISO/FDIS 639-2. Can be + * used for HAL to respond to while in standby mode. + * English(eng), for example, is converted to 0x656e67. + */ + HDMI_OPTION_SET_LANG = 5, +}; + +/* + * Maximum length in bytes of cec message body (exclude header block), + * should not exceed 16 (spec CEC 6 Frame Description) + */ +#define CEC_MESSAGE_BODY_MAX_LENGTH 16 + +typedef struct cec_message { + /* logical address of sender */ + cec_logical_address_t initiator; + + /* logical address of receiver */ + cec_logical_address_t destination; + + /* Length in bytes of body, range [0, CEC_MESSAGE_BODY_MAX_LENGTH] */ + size_t length; + unsigned char body[CEC_MESSAGE_BODY_MAX_LENGTH]; +} cec_message_t; + +typedef struct hotplug_event { + /* + * true if the cable is connected; otherwise false. + */ + int connected; + int port_id; +} hotplug_event_t; + +typedef struct tx_status_event { + int status; + int opcode; /* CEC opcode */ +} tx_status_event_t; + +/* + * HDMI event generated from HAL. + */ +typedef struct hdmi_event { + int type; + struct hdmi_cec_device* dev; + union { + cec_message_t cec; + hotplug_event_t hotplug; + }; +} hdmi_event_t; + +/* + * HDMI port descriptor + */ +typedef struct hdmi_port_info { + hdmi_port_type_t type; + // Port ID should start from 1 which corresponds to HDMI "port 1". + int port_id; + int cec_supported; + int arc_supported; + uint16_t physical_address; +} hdmi_port_info_t; + +/* + * Callback function type that will be called by HAL implementation. + * Services can not close/open the device in the callback. + */ +typedef void (*event_callback_t)(const hdmi_event_t* event, void* arg); + +typedef struct hdmi_cec_module { + /** + * Common methods of the HDMI CEC module. This *must* be the first member of + * hdmi_cec_module as users of this structure will cast a hw_module_t to hdmi_cec_module + * pointer in contexts where it's known the hw_module_t references a hdmi_cec_module. + */ + struct hw_module_t common; +} hdmi_module_t; + +/* + * HDMI-CEC HAL interface definition. + */ +typedef struct hdmi_cec_device { + /** + * Common methods of the HDMI CEC device. This *must* be the first member of + * hdmi_cec_device as users of this structure will cast a hw_device_t to hdmi_cec_device + * pointer in contexts where it's known the hw_device_t references a hdmi_cec_device. + */ + struct hw_device_t common; + + /* + * (*add_logical_address)() passes the logical address that will be used + * in this system. + * + * HAL may use it to configure the hardware so that the CEC commands addressed + * the given logical address can be filtered in. This method can be called + * as many times as necessary in order to support multiple logical devices. + * addr should be in the range of valid logical addresses for the call + * to succeed. + * + * Returns 0 on success or -errno on error. + */ + int (*add_logical_address)(const struct hdmi_cec_device* dev, cec_logical_address_t addr); + + /* + * (*clear_logical_address)() tells HAL to reset all the logical addresses. + * + * It is used when the system doesn't need to process CEC command any more, + * hence to tell HAL to stop receiving commands from the CEC bus, and change + * the state back to the beginning. + */ + void (*clear_logical_address)(const struct hdmi_cec_device* dev); + + /* + * (*get_physical_address)() returns the CEC physical address. The + * address is written to addr. + * + * The physical address depends on the topology of the network formed + * by connected HDMI devices. It is therefore likely to change if the cable + * is plugged off and on again. It is advised to call get_physical_address + * to get the updated address when hot plug event takes place. + * + * Returns 0 on success or -errno on error. + */ + int (*get_physical_address)(const struct hdmi_cec_device* dev, uint16_t* addr); + + /* + * (*send_message)() transmits HDMI-CEC message to other HDMI device. + * + * The method should be designed to return in a certain amount of time not + * hanging forever, which can happen if CEC signal line is pulled low for + * some reason. HAL implementation should take the situation into account + * so as not to wait forever for the message to get sent out. + * + * It should try retransmission at least once as specified in the standard. + * + * Returns error code. See HDMI_RESULT_SUCCESS, HDMI_RESULT_NACK, and + * HDMI_RESULT_BUSY. + */ + int (*send_message)(const struct hdmi_cec_device* dev, const cec_message_t*); + + /* + * (*register_event_callback)() registers a callback that HDMI-CEC HAL + * can later use for incoming CEC messages or internal HDMI events. + * When calling from C++, use the argument arg to pass the calling object. + * It will be passed back when the callback is invoked so that the context + * can be retrieved. + */ + void (*register_event_callback)(const struct hdmi_cec_device* dev, + event_callback_t callback, void* arg); + + /* + * (*get_version)() returns the CEC version supported by underlying hardware. + */ + void (*get_version)(const struct hdmi_cec_device* dev, int* version); + + /* + * (*get_vendor_id)() returns the identifier of the vendor. It is + * the 24-bit unique company ID obtained from the IEEE Registration + * Authority Committee (RAC). + */ + void (*get_vendor_id)(const struct hdmi_cec_device* dev, uint32_t* vendor_id); + + /* + * (*get_port_info)() returns the hdmi port information of underlying hardware. + * info is the list of HDMI port information, and 'total' is the number of + * HDMI ports in the system. + */ + void (*get_port_info)(const struct hdmi_cec_device* dev, + struct hdmi_port_info* list[], int* total); + + /* + * (*set_option)() passes flags controlling the way HDMI-CEC service works down + * to HAL implementation. Those flags will be used in case the feature needs + * update in HAL itself, firmware or microcontroller. + */ + void (*set_option)(const struct hdmi_cec_device* dev, int flag, int value); + + /* + * (*set_audio_return_channel)() configures ARC circuit in the hardware logic + * to start or stop the feature. Flag can be either 1 to start the feature + * or 0 to stop it. + * + * Returns 0 on success or -errno on error. + */ + void (*set_audio_return_channel)(const struct hdmi_cec_device* dev, int port_id, int flag); + + /* + * (*is_connected)() returns the connection status of the specified port. + * Returns HDMI_CONNECTED if a device is connected, otherwise HDMI_NOT_CONNECTED. + * The HAL should watch for +5V power signal to determine the status. + */ + int (*is_connected)(const struct hdmi_cec_device* dev, int port_id); + + /* Reserved for future use to maximum 16 functions. Must be NULL. */ + void* reserved[16 - 11]; +} hdmi_cec_device_t; + +/** convenience API for opening and closing a device */ + +static inline int hdmi_cec_open(const struct hw_module_t* module, + struct hdmi_cec_device** device) { + return module->methods->open(module, + HDMI_CEC_HARDWARE_INTERFACE, (struct hw_device_t**)device); +} + +static inline int hdmi_cec_close(struct hdmi_cec_device* device) { + return device->common.close(&device->common); +} + +__END_DECLS + +#endif /* ANDROID_INCLUDE_HARDWARE_HDMI_CEC_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/hw_auth_token.h b/phonelibs/android_hardware_libhardware/include/hardware/hw_auth_token.h new file mode 100644 index 0000000000..f471d1ab7d --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/hw_auth_token.h @@ -0,0 +1,53 @@ +/* + * Copyright (C) 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. + */ + +#include + +#ifndef ANDROID_HARDWARE_HW_AUTH_TOKEN_H +#define ANDROID_HARDWARE_HW_AUTH_TOKEN_H + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +const uint8_t HW_AUTH_TOKEN_VERSION = 0; + +typedef enum { + HW_AUTH_NONE = 0, + HW_AUTH_PASSWORD = 1 << 0, + HW_AUTH_FINGERPRINT = 1 << 1, + // Additional entries should be powers of 2. + HW_AUTH_ANY = UINT32_MAX, +} hw_authenticator_type_t; + +/** + * Data format for an authentication record used to prove successful authentication. + */ +typedef struct __attribute__((__packed__)) { + uint8_t version; // Current version is 0 + uint64_t challenge; + uint64_t user_id; // secure user ID, not Android user ID + uint64_t authenticator_id; // secure authenticator ID + uint32_t authenticator_type; // hw_authenticator_type_t, in network order + uint64_t timestamp; // in network order + uint8_t hmac[32]; +} hw_auth_token_t; + +#ifdef __cplusplus +} // extern "C" +#endif // __cplusplus + +#endif // ANDROID_HARDWARE_HW_AUTH_TOKEN_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/hwcomposer.h b/phonelibs/android_hardware_libhardware/include/hardware/hwcomposer.h new file mode 100644 index 0000000000..aa466b300a --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/hwcomposer.h @@ -0,0 +1,833 @@ +/* + * 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_INCLUDE_HARDWARE_HWCOMPOSER_H +#define ANDROID_INCLUDE_HARDWARE_HWCOMPOSER_H + +#include +#include + +#include +#include +#include + +#include + +__BEGIN_DECLS + +/*****************************************************************************/ + +/* for compatibility */ +#define HWC_MODULE_API_VERSION HWC_MODULE_API_VERSION_0_1 +#define HWC_DEVICE_API_VERSION HWC_DEVICE_API_VERSION_0_1 +#define HWC_API_VERSION HWC_DEVICE_API_VERSION + +/*****************************************************************************/ + +/** + * The id of this module + */ +#define HWC_HARDWARE_MODULE_ID "hwcomposer" + +/** + * Name of the sensors device to open + */ +#define HWC_HARDWARE_COMPOSER "composer" + +typedef struct hwc_rect { + int left; + int top; + int right; + int bottom; +} hwc_rect_t; + +typedef struct hwc_frect { + float left; + float top; + float right; + float bottom; +} hwc_frect_t; + +typedef struct hwc_region { + size_t numRects; + hwc_rect_t const* rects; +} hwc_region_t; + +typedef struct hwc_color { + uint8_t r; + uint8_t g; + uint8_t b; + uint8_t a; +} hwc_color_t; + +typedef struct hwc_layer_1 { + /* + * compositionType is used to specify this layer's type and is set by either + * the hardware composer implementation, or by the caller (see below). + * + * This field is always reset to HWC_BACKGROUND or HWC_FRAMEBUFFER + * before (*prepare)() is called when the HWC_GEOMETRY_CHANGED flag is + * also set, otherwise, this field is preserved between (*prepare)() + * calls. + * + * HWC_BACKGROUND + * Always set by the caller before calling (*prepare)(), this value + * indicates this is a special "background" layer. The only valid field + * is backgroundColor. + * The HWC can toggle this value to HWC_FRAMEBUFFER to indicate it CANNOT + * handle the background color. + * + * + * HWC_FRAMEBUFFER_TARGET + * Always set by the caller before calling (*prepare)(), this value + * indicates this layer is the framebuffer surface used as the target of + * OpenGL ES composition. If the HWC sets all other layers to HWC_OVERLAY + * or HWC_BACKGROUND, then no OpenGL ES composition will be done, and + * this layer should be ignored during set(). + * + * This flag (and the framebuffer surface layer) will only be used if the + * HWC version is HWC_DEVICE_API_VERSION_1_1 or higher. In older versions, + * the OpenGL ES target surface is communicated by the (dpy, sur) fields + * in hwc_compositor_device_1_t. + * + * This value cannot be set by the HWC implementation. + * + * + * HWC_FRAMEBUFFER + * Set by the caller before calling (*prepare)() ONLY when the + * HWC_GEOMETRY_CHANGED flag is also set. + * + * Set by the HWC implementation during (*prepare)(), this indicates + * that the layer will be drawn into the framebuffer using OpenGL ES. + * The HWC can toggle this value to HWC_OVERLAY to indicate it will + * handle the layer. + * + * + * HWC_OVERLAY + * Set by the HWC implementation during (*prepare)(), this indicates + * that the layer will be handled by the HWC (ie: it must not be + * composited with OpenGL ES). + * + * + * HWC_SIDEBAND + * Set by the caller before calling (*prepare)(), this value indicates + * the contents of this layer come from a sideband video stream. + * + * The h/w composer is responsible for receiving new image buffers from + * the stream at the appropriate time (e.g. synchronized to a separate + * audio stream), compositing them with the current contents of other + * layers, and displaying the resulting image. This happens + * independently of the normal prepare/set cycle. The prepare/set calls + * only happen when other layers change, or when properties of the + * sideband layer such as position or size change. + * + * If the h/w composer can't handle the layer as a sideband stream for + * some reason (e.g. unsupported scaling/blending/rotation, or too many + * sideband layers) it can set compositionType to HWC_FRAMEBUFFER in + * (*prepare)(). However, doing so will result in the layer being shown + * as a solid color since the platform is not currently able to composite + * sideband layers with the GPU. This may be improved in future + * versions of the platform. + * + * + * HWC_CURSOR_OVERLAY + * Set by the HWC implementation during (*prepare)(), this value + * indicates the layer's composition will now be handled by the HWC. + * Additionally, the client can now asynchronously update the on-screen + * position of this layer using the setCursorPositionAsync() api. + */ + int32_t compositionType; + + /* + * hints is bit mask set by the HWC implementation during (*prepare)(). + * It is preserved between (*prepare)() calls, unless the + * HWC_GEOMETRY_CHANGED flag is set, in which case it is reset to 0. + * + * see hwc_layer_t::hints + */ + uint32_t hints; + + /* see hwc_layer_t::flags */ + uint32_t flags; + + union { + /* color of the background. hwc_color_t.a is ignored */ + hwc_color_t backgroundColor; + + struct { + union { + /* When compositionType is HWC_FRAMEBUFFER, HWC_OVERLAY, + * HWC_FRAMEBUFFER_TARGET, this is the handle of the buffer to + * compose. This handle is guaranteed to have been allocated + * from gralloc using the GRALLOC_USAGE_HW_COMPOSER usage flag. + * If the layer's handle is unchanged across two consecutive + * prepare calls and the HWC_GEOMETRY_CHANGED flag is not set + * for the second call then the HWComposer implementation may + * assume that the contents of the buffer have not changed. */ + buffer_handle_t handle; + + /* When compositionType is HWC_SIDEBAND, this is the handle + * of the sideband video stream to compose. */ + const native_handle_t* sidebandStream; + }; + + /* transformation to apply to the buffer during composition */ + uint32_t transform; + + /* blending to apply during composition */ + int32_t blending; + + /* area of the source to consider, the origin is the top-left corner of + * the buffer. As of HWC_DEVICE_API_VERSION_1_3, sourceRect uses floats. + * If the h/w can't support a non-integer source crop rectangle, it should + * punt to OpenGL ES composition. + */ + union { + // crop rectangle in integer (pre HWC_DEVICE_API_VERSION_1_3) + hwc_rect_t sourceCropi; + hwc_rect_t sourceCrop; // just for source compatibility + // crop rectangle in floats (as of HWC_DEVICE_API_VERSION_1_3) + hwc_frect_t sourceCropf; + }; + + /* where to composite the sourceCrop onto the display. The sourceCrop + * is scaled using linear filtering to the displayFrame. The origin is the + * top-left corner of the screen. + */ + hwc_rect_t displayFrame; + + /* visible region in screen space. The origin is the + * top-left corner of the screen. + * The visible region INCLUDES areas overlapped by a translucent layer. + */ + hwc_region_t visibleRegionScreen; + + /* Sync fence object that will be signaled when the buffer's + * contents are available. May be -1 if the contents are already + * available. This field is only valid during set(), and should be + * ignored during prepare(). The set() call must not wait for the + * fence to be signaled before returning, but the HWC must wait for + * all buffers to be signaled before reading from them. + * + * HWC_FRAMEBUFFER layers will never have an acquire fence, since + * reads from them are complete before the framebuffer is ready for + * display. + * + * HWC_SIDEBAND layers will never have an acquire fence, since + * synchronization is handled through implementation-defined + * sideband mechanisms. + * + * The HWC takes ownership of the acquireFenceFd and is responsible + * for closing it when no longer needed. + */ + int acquireFenceFd; + + /* During set() the HWC must set this field to a file descriptor for + * a sync fence object that will signal after the HWC has finished + * reading from the buffer. The field is ignored by prepare(). Each + * layer should have a unique file descriptor, even if more than one + * refer to the same underlying fence object; this allows each to be + * closed independently. + * + * If buffer reads can complete at significantly different times, + * then using independent fences is preferred. For example, if the + * HWC handles some layers with a blit engine and others with + * overlays, then the blit layers can be reused immediately after + * the blit completes, but the overlay layers can't be reused until + * a subsequent frame has been displayed. + * + * Since HWC doesn't read from HWC_FRAMEBUFFER layers, it shouldn't + * produce a release fence for them. The releaseFenceFd will be -1 + * for these layers when set() is called. + * + * Since HWC_SIDEBAND buffers don't pass through the HWC client, + * the HWC shouldn't produce a release fence for them. The + * releaseFenceFd will be -1 for these layers when set() is called. + * + * The HWC client taks ownership of the releaseFenceFd and is + * responsible for closing it when no longer needed. + */ + int releaseFenceFd; + + /* + * Availability: HWC_DEVICE_API_VERSION_1_2 + * + * Alpha value applied to the whole layer. The effective + * value of each pixel is computed as: + * + * if (blending == HWC_BLENDING_PREMULT) + * pixel.rgb = pixel.rgb * planeAlpha / 255 + * pixel.a = pixel.a * planeAlpha / 255 + * + * Then blending proceeds as usual according to the "blending" + * field above. + * + * NOTE: planeAlpha applies to YUV layers as well: + * + * pixel.rgb = yuv_to_rgb(pixel.yuv) + * if (blending == HWC_BLENDING_PREMULT) + * pixel.rgb = pixel.rgb * planeAlpha / 255 + * pixel.a = planeAlpha + * + * + * IMPLEMENTATION NOTE: + * + * If the source image doesn't have an alpha channel, then + * the h/w can use the HWC_BLENDING_COVERAGE equations instead of + * HWC_BLENDING_PREMULT and simply set the alpha channel to + * planeAlpha. + * + * e.g.: + * + * if (blending == HWC_BLENDING_PREMULT) + * blending = HWC_BLENDING_COVERAGE; + * pixel.a = planeAlpha; + * + */ + uint8_t planeAlpha; + + /* Pad to 32 bits */ + uint8_t _pad[3]; + + /* + * Availability: HWC_DEVICE_API_VERSION_1_5 + * + * This defines the region of the source buffer that has been + * modified since the last frame. + * + * If surfaceDamage.numRects > 0, then it may be assumed that any + * portion of the source buffer not covered by one of the rects has + * not been modified this frame. If surfaceDamage.numRects == 0, + * then the whole source buffer must be treated as if it had been + * modified. + * + * If the layer's contents are not modified relative to the prior + * prepare/set cycle, surfaceDamage will contain exactly one empty + * rect ([0, 0, 0, 0]). + * + * The damage rects are relative to the pre-transformed buffer, and + * their origin is the top-left corner. + */ + hwc_region_t surfaceDamage; + }; + }; + +#ifdef __LP64__ + /* + * For 64-bit mode, this struct is 120 bytes (and 8-byte aligned), and needs + * to be padded as such to maintain binary compatibility. + */ + uint8_t reserved[120 - 112]; +#else + /* + * For 32-bit mode, this struct is 96 bytes, and needs to be padded as such + * to maintain binary compatibility. + */ + uint8_t reserved[96 - 84]; +#endif + +} hwc_layer_1_t; + +/* This represents a display, typically an EGLDisplay object */ +typedef void* hwc_display_t; + +/* This represents a surface, typically an EGLSurface object */ +typedef void* hwc_surface_t; + +/* + * hwc_display_contents_1_t::flags values + */ +enum { + /* + * HWC_GEOMETRY_CHANGED is set by SurfaceFlinger to indicate that the list + * passed to (*prepare)() has changed by more than just the buffer handles + * and acquire fences. + */ + HWC_GEOMETRY_CHANGED = 0x00000001, +}; + +/* + * Description of the contents to output on a display. + * + * This is the top-level structure passed to the prepare and set calls to + * negotiate and commit the composition of a display image. + */ +typedef struct hwc_display_contents_1 { + /* File descriptor referring to a Sync HAL fence object which will signal + * when this composition is retired. For a physical display, a composition + * is retired when it has been replaced on-screen by a subsequent set. For + * a virtual display, the composition is retired when the writes to + * outputBuffer are complete and can be read. The fence object is created + * and returned by the set call; this field will be -1 on entry to prepare + * and set. SurfaceFlinger will close the returned file descriptor. + */ + int retireFenceFd; + + union { + /* Fields only relevant for HWC_DEVICE_VERSION_1_0. */ + struct { + /* (dpy, sur) is the target of SurfaceFlinger's OpenGL ES + * composition for HWC_DEVICE_VERSION_1_0. They aren't relevant to + * prepare. The set call should commit this surface atomically to + * the display along with any overlay layers. + */ + hwc_display_t dpy; + hwc_surface_t sur; + }; + + /* These fields are used for virtual displays when the h/w composer + * version is at least HWC_DEVICE_VERSION_1_3. */ + struct { + /* outbuf is the buffer that receives the composed image for + * virtual displays. Writes to the outbuf must wait until + * outbufAcquireFenceFd signals. A fence that will signal when + * writes to outbuf are complete should be returned in + * retireFenceFd. + * + * This field is set before prepare(), so properties of the buffer + * can be used to decide which layers can be handled by h/w + * composer. + * + * If prepare() sets all layers to FRAMEBUFFER, then GLES + * composition will happen directly to the output buffer. In this + * case, both outbuf and the FRAMEBUFFER_TARGET layer's buffer will + * be the same, and set() has no work to do besides managing fences. + * + * If the TARGET_FORCE_HWC_FOR_VIRTUAL_DISPLAYS board config + * variable is defined (not the default), then this behavior is + * changed: if all layers are marked for FRAMEBUFFER, GLES + * composition will take place to a scratch framebuffer, and + * h/w composer must copy it to the output buffer. This allows the + * h/w composer to do format conversion if there are cases where + * that is more desirable than doing it in the GLES driver or at the + * virtual display consumer. + * + * If some or all layers are marked OVERLAY, then the framebuffer + * and output buffer will be different. As with physical displays, + * the framebuffer handle will not change between frames if all + * layers are marked for OVERLAY. + */ + buffer_handle_t outbuf; + + /* File descriptor for a fence that will signal when outbuf is + * ready to be written. The h/w composer is responsible for closing + * this when no longer needed. + * + * Will be -1 whenever outbuf is NULL, or when the outbuf can be + * written immediately. + */ + int outbufAcquireFenceFd; + }; + }; + + /* List of layers that will be composed on the display. The buffer handles + * in the list will be unique. If numHwLayers is 0, all composition will be + * performed by SurfaceFlinger. + */ + uint32_t flags; + size_t numHwLayers; + hwc_layer_1_t hwLayers[0]; + +} hwc_display_contents_1_t; + +/* see hwc_composer_device::registerProcs() + * All of the callbacks are required and non-NULL unless otherwise noted. + */ +typedef struct hwc_procs { + /* + * (*invalidate)() triggers a screen refresh, in particular prepare and set + * will be called shortly after this call is made. Note that there is + * NO GUARANTEE that the screen refresh will happen after invalidate() + * returns (in particular, it could happen before). + * invalidate() is GUARANTEED TO NOT CALL BACK into the h/w composer HAL and + * it is safe to call invalidate() from any of hwc_composer_device + * hooks, unless noted otherwise. + */ + void (*invalidate)(const struct hwc_procs* procs); + + /* + * (*vsync)() is called by the h/w composer HAL when a vsync event is + * received and HWC_EVENT_VSYNC is enabled on a display + * (see: hwc_event_control). + * + * the "disp" parameter indicates which display the vsync event is for. + * the "timestamp" parameter is the system monotonic clock timestamp in + * nanosecond of when the vsync event happened. + * + * vsync() is GUARANTEED TO NOT CALL BACK into the h/w composer HAL. + * + * It is expected that vsync() is called from a thread of at least + * HAL_PRIORITY_URGENT_DISPLAY with as little latency as possible, + * typically less than 0.5 ms. + * + * It is a (silent) error to have HWC_EVENT_VSYNC enabled when calling + * hwc_composer_device.set(..., 0, 0, 0) (screen off). The implementation + * can either stop or continue to process VSYNC events, but must not + * crash or cause other problems. + */ + void (*vsync)(const struct hwc_procs* procs, int disp, int64_t timestamp); + + /* + * (*hotplug)() is called by the h/w composer HAL when a display is + * connected or disconnected. The PRIMARY display is always connected and + * the hotplug callback should not be called for it. + * + * The disp parameter indicates which display type this event is for. + * The connected parameter indicates whether the display has just been + * connected (1) or disconnected (0). + * + * The hotplug() callback may call back into the h/w composer on the same + * thread to query refresh rate and dpi for the display. Additionally, + * other threads may be calling into the h/w composer while the callback + * is in progress. + * + * The h/w composer must serialize calls to the hotplug callback; only + * one thread may call it at a time. + * + * This callback will be NULL if the h/w composer is using + * HWC_DEVICE_API_VERSION_1_0. + */ + void (*hotplug)(const struct hwc_procs* procs, int disp, int connected); + +} hwc_procs_t; + + +/*****************************************************************************/ + +typedef struct hwc_module { + /** + * Common methods of the hardware composer module. This *must* be the first member of + * hwc_module as users of this structure will cast a hw_module_t to + * hwc_module pointer in contexts where it's known the hw_module_t references a + * hwc_module. + */ + struct hw_module_t common; +} hwc_module_t; + +typedef struct hwc_composer_device_1 { + /** + * Common methods of the hardware composer device. This *must* be the first member of + * hwc_composer_device_1 as users of this structure will cast a hw_device_t to + * hwc_composer_device_1 pointer in contexts where it's known the hw_device_t references a + * hwc_composer_device_1. + */ + struct hw_device_t common; + + /* + * (*prepare)() is called for each frame before composition and is used by + * SurfaceFlinger to determine what composition steps the HWC can handle. + * + * (*prepare)() can be called more than once, the last call prevails. + * + * The HWC responds by setting the compositionType field in each layer to + * either HWC_FRAMEBUFFER, HWC_OVERLAY, or HWC_CURSOR_OVERLAY. For the + * HWC_FRAMEBUFFER type, composition for the layer is handled by + * SurfaceFlinger with OpenGL ES. For the latter two overlay types, + * the HWC will have to handle the layer's composition. compositionType + * and hints are preserved between (*prepare)() calles unless the + * HWC_GEOMETRY_CHANGED flag is set. + * + * (*prepare)() is called with HWC_GEOMETRY_CHANGED to indicate that the + * list's geometry has changed, that is, when more than just the buffer's + * handles have been updated. Typically this happens (but is not limited to) + * when a window is added, removed, resized or moved. In this case + * compositionType and hints are reset to their default value. + * + * For HWC 1.0, numDisplays will always be one, and displays[0] will be + * non-NULL. + * + * For HWC 1.1, numDisplays will always be HWC_NUM_PHYSICAL_DISPLAY_TYPES. + * Entries for unsupported or disabled/disconnected display types will be + * NULL. + * + * In HWC 1.3, numDisplays may be up to HWC_NUM_DISPLAY_TYPES. The extra + * entries correspond to enabled virtual displays, and will be non-NULL. + * + * returns: 0 on success. An negative error code on error. If an error is + * returned, SurfaceFlinger will assume that none of the layer will be + * handled by the HWC. + */ + int (*prepare)(struct hwc_composer_device_1 *dev, + size_t numDisplays, hwc_display_contents_1_t** displays); + + /* + * (*set)() is used in place of eglSwapBuffers(), and assumes the same + * functionality, except it also commits the work list atomically with + * the actual eglSwapBuffers(). + * + * The layer lists are guaranteed to be the same as the ones returned from + * the last call to (*prepare)(). + * + * When this call returns the caller assumes that the displays will be + * updated in the near future with the content of their work lists, without + * artifacts during the transition from the previous frame. + * + * A display with zero layers indicates that the entire composition has + * been handled by SurfaceFlinger with OpenGL ES. In this case, (*set)() + * behaves just like eglSwapBuffers(). + * + * For HWC 1.0, numDisplays will always be one, and displays[0] will be + * non-NULL. + * + * For HWC 1.1, numDisplays will always be HWC_NUM_PHYSICAL_DISPLAY_TYPES. + * Entries for unsupported or disabled/disconnected display types will be + * NULL. + * + * In HWC 1.3, numDisplays may be up to HWC_NUM_DISPLAY_TYPES. The extra + * entries correspond to enabled virtual displays, and will be non-NULL. + * + * IMPORTANT NOTE: There is an implicit layer containing opaque black + * pixels behind all the layers in the list. It is the responsibility of + * the hwcomposer module to make sure black pixels are output (or blended + * from). + * + * IMPORTANT NOTE: In the event of an error this call *MUST* still cause + * any fences returned in the previous call to set to eventually become + * signaled. The caller may have already issued wait commands on these + * fences, and having set return without causing those fences to signal + * will likely result in a deadlock. + * + * returns: 0 on success. A negative error code on error: + * HWC_EGL_ERROR: eglGetError() will provide the proper error code (only + * allowed prior to HWComposer 1.1) + * Another code for non EGL errors. + */ + int (*set)(struct hwc_composer_device_1 *dev, + size_t numDisplays, hwc_display_contents_1_t** displays); + + /* + * eventControl(..., event, enabled) + * Enables or disables h/w composer events for a display. + * + * eventControl can be called from any thread and takes effect + * immediately. + * + * Supported events are: + * HWC_EVENT_VSYNC + * + * returns -EINVAL if the "event" parameter is not one of the value above + * or if the "enabled" parameter is not 0 or 1. + */ + int (*eventControl)(struct hwc_composer_device_1* dev, int disp, + int event, int enabled); + + union { + /* + * For HWC 1.3 and earlier, the blank() interface is used. + * + * blank(..., blank) + * Blanks or unblanks a display's screen. + * + * Turns the screen off when blank is nonzero, on when blank is zero. + * Multiple sequential calls with the same blank value must be + * supported. + * The screen state transition must be be complete when the function + * returns. + * + * returns 0 on success, negative on error. + */ + int (*blank)(struct hwc_composer_device_1* dev, int disp, int blank); + + /* + * For HWC 1.4 and above, setPowerMode() will be used in place of + * blank(). + * + * setPowerMode(..., mode) + * Sets the display screen's power state. + * + * Refer to the documentation of the HWC_POWER_MODE_* constants + * for information about each power mode. + * + * The functionality is similar to the blank() command in previous + * versions of HWC, but with support for more power states. + * + * The display driver is expected to retain and restore the low power + * state of the display while entering and exiting from suspend. + * + * Multiple sequential calls with the same mode value must be supported. + * + * The screen state transition must be be complete when the function + * returns. + * + * returns 0 on success, negative on error. + */ + int (*setPowerMode)(struct hwc_composer_device_1* dev, int disp, + int mode); + }; + + /* + * Used to retrieve information about the h/w composer + * + * Returns 0 on success or -errno on error. + */ + int (*query)(struct hwc_composer_device_1* dev, int what, int* value); + + /* + * (*registerProcs)() registers callbacks that the h/w composer HAL can + * later use. It will be called immediately after the composer device is + * opened with non-NULL procs. It is FORBIDDEN to call any of the callbacks + * from within registerProcs(). registerProcs() must save the hwc_procs_t + * pointer which is needed when calling a registered callback. + */ + void (*registerProcs)(struct hwc_composer_device_1* dev, + hwc_procs_t const* procs); + + /* + * This field is OPTIONAL and can be NULL. + * + * If non NULL it will be called by SurfaceFlinger on dumpsys + */ + void (*dump)(struct hwc_composer_device_1* dev, char *buff, int buff_len); + + /* + * (*getDisplayConfigs)() returns handles for the configurations available + * on the connected display. These handles must remain valid as long as the + * display is connected. + * + * Configuration handles are written to configs. The number of entries + * allocated by the caller is passed in *numConfigs; getDisplayConfigs must + * not try to write more than this number of config handles. On return, the + * total number of configurations available for the display is returned in + * *numConfigs. If *numConfigs is zero on entry, then configs may be NULL. + * + * Hardware composers implementing HWC_DEVICE_API_VERSION_1_3 or prior + * shall choose one configuration to activate and report it as the first + * entry in the returned list. Reporting the inactive configurations is not + * required. + * + * HWC_DEVICE_API_VERSION_1_4 and later provide configuration management + * through SurfaceFlinger, and hardware composers implementing these APIs + * must also provide getActiveConfig and setActiveConfig. Hardware composers + * implementing these API versions may choose not to activate any + * configuration, leaving configuration selection to higher levels of the + * framework. + * + * Returns 0 on success or a negative error code on error. If disp is a + * hotpluggable display type and no display is connected, an error shall be + * returned. + * + * This field is REQUIRED for HWC_DEVICE_API_VERSION_1_1 and later. + * It shall be NULL for previous versions. + */ + int (*getDisplayConfigs)(struct hwc_composer_device_1* dev, int disp, + uint32_t* configs, size_t* numConfigs); + + /* + * (*getDisplayAttributes)() returns attributes for a specific config of a + * connected display. The config parameter is one of the config handles + * returned by getDisplayConfigs. + * + * The list of attributes to return is provided in the attributes + * parameter, terminated by HWC_DISPLAY_NO_ATTRIBUTE. The value for each + * requested attribute is written in order to the values array. The + * HWC_DISPLAY_NO_ATTRIBUTE attribute does not have a value, so the values + * array will have one less value than the attributes array. + * + * This field is REQUIRED for HWC_DEVICE_API_VERSION_1_1 and later. + * It shall be NULL for previous versions. + * + * If disp is a hotpluggable display type and no display is connected, + * or if config is not a valid configuration for the display, a negative + * error code shall be returned. + */ + int (*getDisplayAttributes)(struct hwc_composer_device_1* dev, int disp, + uint32_t config, const uint32_t* attributes, int32_t* values); + + /* + * (*getActiveConfig)() returns the index of the configuration that is + * currently active on the connected display. The index is relative to + * the list of configuration handles returned by getDisplayConfigs. If there + * is no active configuration, -1 shall be returned. + * + * Returns the configuration index on success or -1 on error. + * + * This field is REQUIRED for HWC_DEVICE_API_VERSION_1_4 and later. + * It shall be NULL for previous versions. + */ + int (*getActiveConfig)(struct hwc_composer_device_1* dev, int disp); + + /* + * (*setActiveConfig)() instructs the hardware composer to switch to the + * display configuration at the given index in the list of configuration + * handles returned by getDisplayConfigs. + * + * If this function returns without error, any subsequent calls to + * getActiveConfig shall return the index set by this function until one + * of the following occurs: + * 1) Another successful call of this function + * 2) The display is disconnected + * + * Returns 0 on success or a negative error code on error. If disp is a + * hotpluggable display type and no display is connected, or if index is + * outside of the range of hardware configurations returned by + * getDisplayConfigs, an error shall be returned. + * + * This field is REQUIRED for HWC_DEVICE_API_VERSION_1_4 and later. + * It shall be NULL for previous versions. + */ + int (*setActiveConfig)(struct hwc_composer_device_1* dev, int disp, + int index); + /* + * Asynchronously update the location of the cursor layer. + * + * Within the standard prepare()/set() composition loop, the client + * (surfaceflinger) can request that a given layer uses dedicated cursor + * composition hardware by specifiying the HWC_IS_CURSOR_LAYER flag. Only + * one layer per display can have this flag set. If the layer is suitable + * for the platform's cursor hardware, hwcomposer will return from prepare() + * a composition type of HWC_CURSOR_OVERLAY for that layer. This indicates + * not only that the client is not responsible for compositing that layer, + * but also that the client can continue to update the position of that layer + * after a call to set(). This can reduce the visible latency of mouse + * movement to visible, on-screen cursor updates. Calls to + * setCursorPositionAsync() may be made from a different thread doing the + * prepare()/set() composition loop, but care must be taken to not interleave + * calls of setCursorPositionAsync() between calls of set()/prepare(). + * + * Notes: + * - Only one layer per display can be specified as a cursor layer with + * HWC_IS_CURSOR_LAYER. + * - hwcomposer will only return one layer per display as HWC_CURSOR_OVERLAY + * - This returns 0 on success or -errno on error. + * - This field is optional for HWC_DEVICE_API_VERSION_1_4 and later. It + * should be null for previous versions. + */ + int (*setCursorPositionAsync)(struct hwc_composer_device_1 *dev, int disp, int x_pos, int y_pos); + + /* + * Reserved for future use. Must be NULL. + */ + void* reserved_proc[1]; + +} hwc_composer_device_1_t; + +/** convenience API for opening and closing a device */ + +static inline int hwc_open_1(const struct hw_module_t* module, + hwc_composer_device_1_t** device) { + return module->methods->open(module, + HWC_HARDWARE_COMPOSER, (struct hw_device_t**)device); +} + +static inline int hwc_close_1(hwc_composer_device_1_t* device) { + return device->common.close(&device->common); +} + +/*****************************************************************************/ + +__END_DECLS + +#endif /* ANDROID_INCLUDE_HARDWARE_HWCOMPOSER_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/hwcomposer_defs.h b/phonelibs/android_hardware_libhardware/include/hardware/hwcomposer_defs.h new file mode 100644 index 0000000000..a90822a4b8 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/hwcomposer_defs.h @@ -0,0 +1,263 @@ +/* + * 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_INCLUDE_HARDWARE_HWCOMPOSER_DEFS_H +#define ANDROID_INCLUDE_HARDWARE_HWCOMPOSER_DEFS_H + +#include +#include + +#include +#include +#include + +__BEGIN_DECLS + +/*****************************************************************************/ + +#define HWC_HEADER_VERSION 1 + +#define HWC_MODULE_API_VERSION_0_1 HARDWARE_MODULE_API_VERSION(0, 1) + +#define HWC_DEVICE_API_VERSION_1_0 HARDWARE_DEVICE_API_VERSION_2(1, 0, HWC_HEADER_VERSION) +#define HWC_DEVICE_API_VERSION_1_1 HARDWARE_DEVICE_API_VERSION_2(1, 1, HWC_HEADER_VERSION) +#define HWC_DEVICE_API_VERSION_1_2 HARDWARE_DEVICE_API_VERSION_2(1, 2, HWC_HEADER_VERSION) +#define HWC_DEVICE_API_VERSION_1_3 HARDWARE_DEVICE_API_VERSION_2(1, 3, HWC_HEADER_VERSION) +#define HWC_DEVICE_API_VERSION_1_4 HARDWARE_DEVICE_API_VERSION_2(1, 4, HWC_HEADER_VERSION) +#define HWC_DEVICE_API_VERSION_1_5 HARDWARE_DEVICE_API_VERSION_2(1, 5, HWC_HEADER_VERSION) + +enum { + /* hwc_composer_device_t::set failed in EGL */ + HWC_EGL_ERROR = -1 +}; + +/* + * hwc_layer_t::hints values + * Hints are set by the HAL and read by SurfaceFlinger + */ +enum { + /* + * HWC can set the HWC_HINT_TRIPLE_BUFFER hint to indicate to SurfaceFlinger + * that it should triple buffer this layer. Typically HWC does this when + * the layer will be unavailable for use for an extended period of time, + * e.g. if the display will be fetching data directly from the layer and + * the layer can not be modified until after the next set(). + */ + HWC_HINT_TRIPLE_BUFFER = 0x00000001, + + /* + * HWC sets HWC_HINT_CLEAR_FB to tell SurfaceFlinger that it should clear the + * framebuffer with transparent pixels where this layer would be. + * SurfaceFlinger will only honor this flag when the layer has no blending + * + */ + HWC_HINT_CLEAR_FB = 0x00000002 +}; + +/* + * hwc_layer_t::flags values + * Flags are set by SurfaceFlinger and read by the HAL + */ +enum { + /* + * HWC_SKIP_LAYER is set by SurfaceFlnger to indicate that the HAL + * shall not consider this layer for composition as it will be handled + * by SurfaceFlinger (just as if compositionType was set to HWC_OVERLAY). + */ + HWC_SKIP_LAYER = 0x00000001, + + /* + * HWC_IS_CURSOR_LAYER is set by surfaceflinger to indicate that this + * layer is being used as a cursor on this particular display, and that + * surfaceflinger can potentially perform asynchronous position updates for + * this layer. If a call to prepare() returns HWC_CURSOR_OVERLAY for the + * composition type of this layer, then the hwcomposer will allow async + * position updates to this layer via setCursorPositionAsync(). + */ + HWC_IS_CURSOR_LAYER = 0x00000002 +}; + +/* + * hwc_layer_t::compositionType values + */ +enum { + /* this layer is to be drawn into the framebuffer by SurfaceFlinger */ + HWC_FRAMEBUFFER = 0, + + /* this layer will be handled in the HWC */ + HWC_OVERLAY = 1, + + /* this is the background layer. it's used to set the background color. + * there is only a single background layer */ + HWC_BACKGROUND = 2, + + /* this layer holds the result of compositing the HWC_FRAMEBUFFER layers. + * Added in HWC_DEVICE_API_VERSION_1_1. */ + HWC_FRAMEBUFFER_TARGET = 3, + + /* this layer's contents are taken from a sideband buffer stream. + * Added in HWC_DEVICE_API_VERSION_1_4. */ + HWC_SIDEBAND = 4, + + /* this layer's composition will be handled by hwcomposer by dedicated + cursor overlay hardware. hwcomposer will also all async position updates + of this layer outside of the normal prepare()/set() loop. Added in + HWC_DEVICE_API_VERSION_1_4. */ + HWC_CURSOR_OVERLAY = 5 + }; +/* + * hwc_layer_t::blending values + */ +enum { + /* no blending */ + HWC_BLENDING_NONE = 0x0100, + + /* ONE / ONE_MINUS_SRC_ALPHA */ + HWC_BLENDING_PREMULT = 0x0105, + + /* SRC_ALPHA / ONE_MINUS_SRC_ALPHA */ + HWC_BLENDING_COVERAGE = 0x0405 +}; + +/* + * hwc_layer_t::transform values + */ +enum { + /* flip source image horizontally */ + HWC_TRANSFORM_FLIP_H = HAL_TRANSFORM_FLIP_H, + /* flip source image vertically */ + HWC_TRANSFORM_FLIP_V = HAL_TRANSFORM_FLIP_V, + /* rotate source image 90 degrees clock-wise */ + HWC_TRANSFORM_ROT_90 = HAL_TRANSFORM_ROT_90, + /* rotate source image 180 degrees */ + HWC_TRANSFORM_ROT_180 = HAL_TRANSFORM_ROT_180, + /* rotate source image 270 degrees clock-wise */ + HWC_TRANSFORM_ROT_270 = HAL_TRANSFORM_ROT_270, +}; + +/* attributes queriable with query() */ +enum { + /* + * Must return 1 if the background layer is supported, 0 otherwise. + */ + HWC_BACKGROUND_LAYER_SUPPORTED = 0, + + /* + * Returns the vsync period in nanoseconds. + * + * This query is not used for HWC_DEVICE_API_VERSION_1_1 and later. + * Instead, the per-display attribute HWC_DISPLAY_VSYNC_PERIOD is used. + */ + HWC_VSYNC_PERIOD = 1, + + /* + * Availability: HWC_DEVICE_API_VERSION_1_1 + * Returns a mask of supported display types. + */ + HWC_DISPLAY_TYPES_SUPPORTED = 2, +}; + +/* display attributes returned by getDisplayAttributes() */ +enum { + /* Indicates the end of an attribute list */ + HWC_DISPLAY_NO_ATTRIBUTE = 0, + + /* The vsync period in nanoseconds */ + HWC_DISPLAY_VSYNC_PERIOD = 1, + + /* The number of pixels in the horizontal and vertical directions. */ + HWC_DISPLAY_WIDTH = 2, + HWC_DISPLAY_HEIGHT = 3, + + /* The number of pixels per thousand inches of this configuration. + * + * Scaling DPI by 1000 allows it to be stored in an int without losing + * too much precision. + * + * If the DPI for a configuration is unavailable or the HWC implementation + * considers it unreliable, it should set these attributes to zero. + */ + HWC_DISPLAY_DPI_X = 4, + HWC_DISPLAY_DPI_Y = 5, + + /* Indicates which of the vendor-defined color transforms is provided by + * this configuration. */ + HWC_DISPLAY_COLOR_TRANSFORM = 6, +}; + +/* Allowed events for hwc_methods::eventControl() */ +enum { + HWC_EVENT_VSYNC = 0 +}; + +/* Display types and associated mask bits. */ +enum { + HWC_DISPLAY_PRIMARY = 0, + HWC_DISPLAY_EXTERNAL = 1, // HDMI, DP, etc. +#ifdef QTI_BSP + HWC_DISPLAY_TERTIARY = 2, + HWC_DISPLAY_VIRTUAL = 3, + + HWC_NUM_PHYSICAL_DISPLAY_TYPES = 3, + HWC_NUM_DISPLAY_TYPES = 4, +#else + HWC_DISPLAY_VIRTUAL = 2, + + HWC_NUM_PHYSICAL_DISPLAY_TYPES = 2, + HWC_NUM_DISPLAY_TYPES = 3, +#endif +}; + +enum { + HWC_DISPLAY_PRIMARY_BIT = 1 << HWC_DISPLAY_PRIMARY, + HWC_DISPLAY_EXTERNAL_BIT = 1 << HWC_DISPLAY_EXTERNAL, +#ifdef QTI_BSP + HWC_DISPLAY_TERTIARY_BIT = 1 << HWC_DISPLAY_TERTIARY, +#endif + HWC_DISPLAY_VIRTUAL_BIT = 1 << HWC_DISPLAY_VIRTUAL, +}; + +/* Display power modes */ +enum { + /* The display is turned off (blanked). */ + HWC_POWER_MODE_OFF = 0, + /* The display is turned on and configured in a low power state + * that is suitable for presenting ambient information to the user, + * possibly with lower fidelity than normal but greater efficiency. */ + HWC_POWER_MODE_DOZE = 1, + /* The display is turned on normally. */ + HWC_POWER_MODE_NORMAL = 2, + /* The display is configured as in HWC_POWER_MODE_DOZE but may + * stop applying frame buffer updates from the graphics subsystem. + * This power mode is effectively a hint from the doze dream to + * tell the hardware that it is done drawing to the display for the + * time being and that the display should remain on in a low power + * state and continue showing its current contents indefinitely + * until the mode changes. + * + * This mode may also be used as a signal to enable hardware-based doze + * functionality. In this case, the doze dream is effectively + * indicating that the hardware is free to take over the display + * and manage it autonomously to implement low power always-on display + * functionality. */ + HWC_POWER_MODE_DOZE_SUSPEND = 3, +}; + +/*****************************************************************************/ + +__END_DECLS + +#endif /* ANDROID_INCLUDE_HARDWARE_HWCOMPOSER_DEFS_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/input.h b/phonelibs/android_hardware_libhardware/include/hardware/input.h new file mode 100644 index 0000000000..969b8ce570 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/input.h @@ -0,0 +1,549 @@ +/* + * 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_INCLUDE_HARDWARE_INPUT_H +#define ANDROID_INCLUDE_HARDWARE_INPUT_H + +#include +#include + +__BEGIN_DECLS + +#define INPUT_MODULE_API_VERSION_1_0 HARDWARE_MODULE_API_VERSION(1, 0) +#define INPUT_HARDWARE_MODULE_ID "input" + +#define INPUT_INSTANCE_EVDEV "evdev" + +typedef enum input_bus { + INPUT_BUS_BT, + INPUT_BUS_USB, + INPUT_BUS_SERIAL, + INPUT_BUS_BUILTIN +} input_bus_t; + +typedef struct input_host input_host_t; + +typedef struct input_device_handle input_device_handle_t; + +typedef struct input_device_identifier input_device_identifier_t; + +typedef struct input_device_definition input_device_definition_t; + +typedef struct input_report_definition input_report_definition_t; + +typedef struct input_report input_report_t; + +typedef struct input_collection input_collection_t; + +typedef struct input_property_map input_property_map_t; + +typedef struct input_property input_property_t; + +typedef enum { + // keycodes + INPUT_USAGE_KEYCODE_UNKNOWN, + INPUT_USAGE_KEYCODE_SOFT_LEFT, + INPUT_USAGE_KEYCODE_SOFT_RIGHT, + INPUT_USAGE_KEYCODE_HOME, + INPUT_USAGE_KEYCODE_BACK, + INPUT_USAGE_KEYCODE_CALL, + INPUT_USAGE_KEYCODE_ENDCALL, + INPUT_USAGE_KEYCODE_0, + INPUT_USAGE_KEYCODE_1, + INPUT_USAGE_KEYCODE_2, + INPUT_USAGE_KEYCODE_3, + INPUT_USAGE_KEYCODE_4, + INPUT_USAGE_KEYCODE_5, + INPUT_USAGE_KEYCODE_6, + INPUT_USAGE_KEYCODE_7, + INPUT_USAGE_KEYCODE_8, + INPUT_USAGE_KEYCODE_9, + INPUT_USAGE_KEYCODE_STAR, + INPUT_USAGE_KEYCODE_POUND, + INPUT_USAGE_KEYCODE_DPAD_UP, + INPUT_USAGE_KEYCODE_DPAD_DOWN, + INPUT_USAGE_KEYCODE_DPAD_LEFT, + INPUT_USAGE_KEYCODE_DPAD_RIGHT, + INPUT_USAGE_KEYCODE_DPAD_CENTER, + INPUT_USAGE_KEYCODE_VOLUME_UP, + INPUT_USAGE_KEYCODE_VOLUME_DOWN, + INPUT_USAGE_KEYCODE_POWER, + INPUT_USAGE_KEYCODE_CAMERA, + INPUT_USAGE_KEYCODE_CLEAR, + INPUT_USAGE_KEYCODE_A, + INPUT_USAGE_KEYCODE_B, + INPUT_USAGE_KEYCODE_C, + INPUT_USAGE_KEYCODE_D, + INPUT_USAGE_KEYCODE_E, + INPUT_USAGE_KEYCODE_F, + INPUT_USAGE_KEYCODE_G, + INPUT_USAGE_KEYCODE_H, + INPUT_USAGE_KEYCODE_I, + INPUT_USAGE_KEYCODE_J, + INPUT_USAGE_KEYCODE_K, + INPUT_USAGE_KEYCODE_L, + INPUT_USAGE_KEYCODE_M, + INPUT_USAGE_KEYCODE_N, + INPUT_USAGE_KEYCODE_O, + INPUT_USAGE_KEYCODE_P, + INPUT_USAGE_KEYCODE_Q, + INPUT_USAGE_KEYCODE_R, + INPUT_USAGE_KEYCODE_S, + INPUT_USAGE_KEYCODE_T, + INPUT_USAGE_KEYCODE_U, + INPUT_USAGE_KEYCODE_V, + INPUT_USAGE_KEYCODE_W, + INPUT_USAGE_KEYCODE_X, + INPUT_USAGE_KEYCODE_Y, + INPUT_USAGE_KEYCODE_Z, + INPUT_USAGE_KEYCODE_COMMA, + INPUT_USAGE_KEYCODE_PERIOD, + INPUT_USAGE_KEYCODE_ALT_LEFT, + INPUT_USAGE_KEYCODE_ALT_RIGHT, + INPUT_USAGE_KEYCODE_SHIFT_LEFT, + INPUT_USAGE_KEYCODE_SHIFT_RIGHT, + INPUT_USAGE_KEYCODE_TAB, + INPUT_USAGE_KEYCODE_SPACE, + INPUT_USAGE_KEYCODE_SYM, + INPUT_USAGE_KEYCODE_EXPLORER, + INPUT_USAGE_KEYCODE_ENVELOPE, + INPUT_USAGE_KEYCODE_ENTER, + INPUT_USAGE_KEYCODE_DEL, + INPUT_USAGE_KEYCODE_GRAVE, + INPUT_USAGE_KEYCODE_MINUS, + INPUT_USAGE_KEYCODE_EQUALS, + INPUT_USAGE_KEYCODE_LEFT_BRACKET, + INPUT_USAGE_KEYCODE_RIGHT_BRACKET, + INPUT_USAGE_KEYCODE_BACKSLASH, + INPUT_USAGE_KEYCODE_SEMICOLON, + INPUT_USAGE_KEYCODE_APOSTROPHE, + INPUT_USAGE_KEYCODE_SLASH, + INPUT_USAGE_KEYCODE_AT, + INPUT_USAGE_KEYCODE_NUM, + INPUT_USAGE_KEYCODE_HEADSETHOOK, + INPUT_USAGE_KEYCODE_FOCUS, // *Camera* focus + INPUT_USAGE_KEYCODE_PLUS, + INPUT_USAGE_KEYCODE_MENU, + INPUT_USAGE_KEYCODE_NOTIFICATION, + INPUT_USAGE_KEYCODE_SEARCH, + INPUT_USAGE_KEYCODE_MEDIA_PLAY_PAUSE, + INPUT_USAGE_KEYCODE_MEDIA_STOP, + INPUT_USAGE_KEYCODE_MEDIA_NEXT, + INPUT_USAGE_KEYCODE_MEDIA_PREVIOUS, + INPUT_USAGE_KEYCODE_MEDIA_REWIND, + INPUT_USAGE_KEYCODE_MEDIA_FAST_FORWARD, + INPUT_USAGE_KEYCODE_MUTE, + INPUT_USAGE_KEYCODE_PAGE_UP, + INPUT_USAGE_KEYCODE_PAGE_DOWN, + INPUT_USAGE_KEYCODE_PICTSYMBOLS, + INPUT_USAGE_KEYCODE_SWITCH_CHARSET, + INPUT_USAGE_KEYCODE_BUTTON_A, + INPUT_USAGE_KEYCODE_BUTTON_B, + INPUT_USAGE_KEYCODE_BUTTON_C, + INPUT_USAGE_KEYCODE_BUTTON_X, + INPUT_USAGE_KEYCODE_BUTTON_Y, + INPUT_USAGE_KEYCODE_BUTTON_Z, + INPUT_USAGE_KEYCODE_BUTTON_L1, + INPUT_USAGE_KEYCODE_BUTTON_R1, + INPUT_USAGE_KEYCODE_BUTTON_L2, + INPUT_USAGE_KEYCODE_BUTTON_R2, + INPUT_USAGE_KEYCODE_BUTTON_THUMBL, + INPUT_USAGE_KEYCODE_BUTTON_THUMBR, + INPUT_USAGE_KEYCODE_BUTTON_START, + INPUT_USAGE_KEYCODE_BUTTON_SELECT, + INPUT_USAGE_KEYCODE_BUTTON_MODE, + INPUT_USAGE_KEYCODE_ESCAPE, + INPUT_USAGE_KEYCODE_FORWARD_DEL, + INPUT_USAGE_KEYCODE_CTRL_LEFT, + INPUT_USAGE_KEYCODE_CTRL_RIGHT, + INPUT_USAGE_KEYCODE_CAPS_LOCK, + INPUT_USAGE_KEYCODE_SCROLL_LOCK, + INPUT_USAGE_KEYCODE_META_LEFT, + INPUT_USAGE_KEYCODE_META_RIGHT, + INPUT_USAGE_KEYCODE_FUNCTION, + INPUT_USAGE_KEYCODE_SYSRQ, + INPUT_USAGE_KEYCODE_BREAK, + INPUT_USAGE_KEYCODE_MOVE_HOME, + INPUT_USAGE_KEYCODE_MOVE_END, + INPUT_USAGE_KEYCODE_INSERT, + INPUT_USAGE_KEYCODE_FORWARD, + INPUT_USAGE_KEYCODE_MEDIA_PLAY, + INPUT_USAGE_KEYCODE_MEDIA_PAUSE, + INPUT_USAGE_KEYCODE_MEDIA_CLOSE, + INPUT_USAGE_KEYCODE_MEDIA_EJECT, + INPUT_USAGE_KEYCODE_MEDIA_RECORD, + INPUT_USAGE_KEYCODE_F1, + INPUT_USAGE_KEYCODE_F2, + INPUT_USAGE_KEYCODE_F3, + INPUT_USAGE_KEYCODE_F4, + INPUT_USAGE_KEYCODE_F5, + INPUT_USAGE_KEYCODE_F6, + INPUT_USAGE_KEYCODE_F7, + INPUT_USAGE_KEYCODE_F8, + INPUT_USAGE_KEYCODE_F9, + INPUT_USAGE_KEYCODE_F10, + INPUT_USAGE_KEYCODE_F11, + INPUT_USAGE_KEYCODE_F12, + INPUT_USAGE_KEYCODE_NUM_LOCK, + INPUT_USAGE_KEYCODE_NUMPAD_0, + INPUT_USAGE_KEYCODE_NUMPAD_1, + INPUT_USAGE_KEYCODE_NUMPAD_2, + INPUT_USAGE_KEYCODE_NUMPAD_3, + INPUT_USAGE_KEYCODE_NUMPAD_4, + INPUT_USAGE_KEYCODE_NUMPAD_5, + INPUT_USAGE_KEYCODE_NUMPAD_6, + INPUT_USAGE_KEYCODE_NUMPAD_7, + INPUT_USAGE_KEYCODE_NUMPAD_8, + INPUT_USAGE_KEYCODE_NUMPAD_9, + INPUT_USAGE_KEYCODE_NUMPAD_DIVIDE, + INPUT_USAGE_KEYCODE_NUMPAD_MULTIPLY, + INPUT_USAGE_KEYCODE_NUMPAD_SUBTRACT, + INPUT_USAGE_KEYCODE_NUMPAD_ADD, + INPUT_USAGE_KEYCODE_NUMPAD_DOT, + INPUT_USAGE_KEYCODE_NUMPAD_COMMA, + INPUT_USAGE_KEYCODE_NUMPAD_ENTER, + INPUT_USAGE_KEYCODE_NUMPAD_EQUALS, + INPUT_USAGE_KEYCODE_NUMPAD_LEFT_PAREN, + INPUT_USAGE_KEYCODE_NUMPAD_RIGHT_PAREN, + INPUT_USAGE_KEYCODE_VOLUME_MUTE, + INPUT_USAGE_KEYCODE_INFO, + INPUT_USAGE_KEYCODE_CHANNEL_UP, + INPUT_USAGE_KEYCODE_CHANNEL_DOWN, + INPUT_USAGE_KEYCODE_ZOOM_IN, + INPUT_USAGE_KEYCODE_ZOOM_OUT, + INPUT_USAGE_KEYCODE_TV, + INPUT_USAGE_KEYCODE_WINDOW, + INPUT_USAGE_KEYCODE_GUIDE, + INPUT_USAGE_KEYCODE_DVR, + INPUT_USAGE_KEYCODE_BOOKMARK, + INPUT_USAGE_KEYCODE_CAPTIONS, + INPUT_USAGE_KEYCODE_SETTINGS, + INPUT_USAGE_KEYCODE_TV_POWER, + INPUT_USAGE_KEYCODE_TV_INPUT, + INPUT_USAGE_KEYCODE_STB_POWER, + INPUT_USAGE_KEYCODE_STB_INPUT, + INPUT_USAGE_KEYCODE_AVR_POWER, + INPUT_USAGE_KEYCODE_AVR_INPUT, + INPUT_USAGE_KEYCODE_PROG_RED, + INPUT_USAGE_KEYCODE_PROG_GREEN, + INPUT_USAGE_KEYCODE_PROG_YELLOW, + INPUT_USAGE_KEYCODE_PROG_BLUE, + INPUT_USAGE_KEYCODE_APP_SWITCH, + INPUT_USAGE_KEYCODE_BUTTON_1, + INPUT_USAGE_KEYCODE_BUTTON_2, + INPUT_USAGE_KEYCODE_BUTTON_3, + INPUT_USAGE_KEYCODE_BUTTON_4, + INPUT_USAGE_KEYCODE_BUTTON_5, + INPUT_USAGE_KEYCODE_BUTTON_6, + INPUT_USAGE_KEYCODE_BUTTON_7, + INPUT_USAGE_KEYCODE_BUTTON_8, + INPUT_USAGE_KEYCODE_BUTTON_9, + INPUT_USAGE_KEYCODE_BUTTON_10, + INPUT_USAGE_KEYCODE_BUTTON_11, + INPUT_USAGE_KEYCODE_BUTTON_12, + INPUT_USAGE_KEYCODE_BUTTON_13, + INPUT_USAGE_KEYCODE_BUTTON_14, + INPUT_USAGE_KEYCODE_BUTTON_15, + INPUT_USAGE_KEYCODE_BUTTON_16, + INPUT_USAGE_KEYCODE_LANGUAGE_SWITCH, + INPUT_USAGE_KEYCODE_MANNER_MODE, + INPUT_USAGE_KEYCODE_3D_MODE, + INPUT_USAGE_KEYCODE_CONTACTS, + INPUT_USAGE_KEYCODE_CALENDAR, + INPUT_USAGE_KEYCODE_MUSIC, + INPUT_USAGE_KEYCODE_CALCULATOR, + INPUT_USAGE_KEYCODE_ZENKAKU_HANKAKU, + INPUT_USAGE_KEYCODE_EISU, + INPUT_USAGE_KEYCODE_MUHENKAN, + INPUT_USAGE_KEYCODE_HENKAN, + INPUT_USAGE_KEYCODE_KATAKANA_HIRAGANA, + INPUT_USAGE_KEYCODE_YEN, + INPUT_USAGE_KEYCODE_RO, + INPUT_USAGE_KEYCODE_KANA, + INPUT_USAGE_KEYCODE_ASSIST, + INPUT_USAGE_KEYCODE_BRIGHTNESS_DOWN, + INPUT_USAGE_KEYCODE_BRIGHTNESS_UP, + INPUT_USAGE_KEYCODE_MEDIA_AUDIO_TRACK, + INPUT_USAGE_KEYCODE_SLEEP, + INPUT_USAGE_KEYCODE_WAKEUP, + INPUT_USAGE_KEYCODE_PAIRING, + INPUT_USAGE_KEYCODE_MEDIA_TOP_MENU, + INPUT_USAGE_KEYCODE_11, + INPUT_USAGE_KEYCODE_12, + INPUT_USAGE_KEYCODE_LAST_CHANNEL, + INPUT_USAGE_KEYCODE_TV_DATA_SERVICE, + INPUT_USAGE_KEYCODE_VOICE_ASSIST, + INPUT_USAGE_KEYCODE_TV_RADIO_SERVICE, + INPUT_USAGE_KEYCODE_TV_TELETEXT, + INPUT_USAGE_KEYCODE_TV_NUMBER_ENTRY, + INPUT_USAGE_KEYCODE_TV_TERRESTRIAL_ANALOG, + INPUT_USAGE_KEYCODE_TV_TERRESTRIAL_DIGITAL, + INPUT_USAGE_KEYCODE_TV_SATELLITE, + INPUT_USAGE_KEYCODE_TV_SATELLITE_BS, + INPUT_USAGE_KEYCODE_TV_SATELLITE_CS, + INPUT_USAGE_KEYCODE_TV_SATELLITE_SERVICE, + INPUT_USAGE_KEYCODE_TV_NETWORK, + INPUT_USAGE_KEYCODE_TV_ANTENNA_CABLE, + INPUT_USAGE_KEYCODE_TV_INPUT_HDMI_1, + INPUT_USAGE_KEYCODE_TV_INPUT_HDMI_2, + INPUT_USAGE_KEYCODE_TV_INPUT_HDMI_3, + INPUT_USAGE_KEYCODE_TV_INPUT_HDMI_4, + INPUT_USAGE_KEYCODE_TV_INPUT_COMPOSITE_1, + INPUT_USAGE_KEYCODE_TV_INPUT_COMPOSITE_2, + INPUT_USAGE_KEYCODE_TV_INPUT_COMPONENT_1, + INPUT_USAGE_KEYCODE_TV_INPUT_COMPONENT_2, + INPUT_USAGE_KEYCODE_TV_INPUT_VGA_1, + INPUT_USAGE_KEYCODE_TV_AUDIO_DESCRIPTION, + INPUT_USAGE_KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP, + INPUT_USAGE_KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN, + INPUT_USAGE_KEYCODE_TV_ZOOM_MODE, + INPUT_USAGE_KEYCODE_TV_CONTENTS_MENU, + INPUT_USAGE_KEYCODE_TV_MEDIA_CONTEXT_MENU, + INPUT_USAGE_KEYCODE_TV_TIMER_PROGRAMMING, + INPUT_USAGE_KEYCODE_HELP, + + // axes + INPUT_USAGE_AXIS_X, + INPUT_USAGE_AXIS_Y, + INPUT_USAGE_AXIS_PRESSURE, + INPUT_USAGE_AXIS_SIZE, + INPUT_USAGE_AXIS_TOUCH_MAJOR, + INPUT_USAGE_AXIS_TOUCH_MINOR, + INPUT_USAGE_AXIS_TOOL_MAJOR, + INPUT_USAGE_AXIS_TOOL_MINOR, + INPUT_USAGE_AXIS_ORIENTATION, + INPUT_USAGE_AXIS_VSCROLL, + INPUT_USAGE_AXIS_HSCROLL, + INPUT_USAGE_AXIS_Z, + INPUT_USAGE_AXIS_RX, + INPUT_USAGE_AXIS_RY, + INPUT_USAGE_AXIS_RZ, + INPUT_USAGE_AXIS_HAT_X, + INPUT_USAGE_AXIS_HAT_Y, + INPUT_USAGE_AXIS_LTRIGGER, + INPUT_USAGE_AXIS_RTRIGGER, + INPUT_USAGE_AXIS_THROTTLE, + INPUT_USAGE_AXIS_RUDDER, + INPUT_USAGE_AXIS_WHEEL, + INPUT_USAGE_AXIS_GAS, + INPUT_USAGE_AXIS_BRAKE, + INPUT_USAGE_AXIS_DISTANCE, + INPUT_USAGE_AXIS_TILT, + INPUT_USAGE_AXIS_GENERIC_1, + INPUT_USAGE_AXIS_GENERIC_2, + INPUT_USAGE_AXIS_GENERIC_3, + INPUT_USAGE_AXIS_GENERIC_4, + INPUT_USAGE_AXIS_GENERIC_5, + INPUT_USAGE_AXIS_GENERIC_6, + INPUT_USAGE_AXIS_GENERIC_7, + INPUT_USAGE_AXIS_GENERIC_8, + INPUT_USAGE_AXIS_GENERIC_9, + INPUT_USAGE_AXIS_GENERIC_10, + INPUT_USAGE_AXIS_GENERIC_11, + INPUT_USAGE_AXIS_GENERIC_12, + INPUT_USAGE_AXIS_GENERIC_13, + INPUT_USAGE_AXIS_GENERIC_14, + INPUT_USAGE_AXIS_GENERIC_15, + INPUT_USAGE_AXIS_GENERIC_16, + + // leds + INPUT_USAGE_LED_NUM_LOCK, + INPUT_USAGE_LED_CAPS_LOCK, + INPUT_USAGE_LED_SCROLL_LOCK, + INPUT_USAGE_LED_COMPOSE, + INPUT_USAGE_LED_KANA, + INPUT_USAGE_LED_SLEEP, + INPUT_USAGE_LED_SUSPEND, + INPUT_USAGE_LED_MUTE, + INPUT_USAGE_LED_MISC, + INPUT_USAGE_LED_MAIL, + INPUT_USAGE_LED_CHARGING, + INPUT_USAGE_LED_CONTROLLER_1, + INPUT_USAGE_LED_CONTROLLER_2, + INPUT_USAGE_LED_CONTROLLER_3, + INPUT_USAGE_LED_CONTROLLER_4, +} input_usage_t; + +typedef enum { + INPUT_COLLECTION_ID_TOUCH, + INPUT_COLLECTION_ID_KEYBOARD, + INPUT_COLLECTION_ID_MOUSE, + INPUT_COLLECTION_ID_TOUCHPAD, + // etc +} input_collection_id_t; + +typedef struct input_message input_message_t; + +typedef struct input_host_callbacks { + + /** + * Creates a device identifier with the given properties. + * The unique ID should be a string that precisely identifies a given piece of hardware. For + * example, an input device connected via Bluetooth could use its MAC address as its unique ID. + */ + input_device_identifier_t* (*create_device_identifier)(input_host_t* host, + const char* name, int32_t product_id, int32_t vendor_id, + input_bus_t bus, const char* unique_id); + + /** + * Allocates the device definition which will describe the input capabilities of a device. A + * device definition may be used to register as many devices as desired. + */ + input_device_definition_t* (*create_device_definition)(input_host_t* host); + + /** + * Allocate either an input report, which the HAL will use to tell the host of incoming input + * events, or an output report, which the host will use to tell the HAL of desired state + * changes (e.g. setting an LED). + */ + input_report_definition_t* (*create_input_report_definition)(input_host_t* host); + input_report_definition_t* (*create_output_report_definition)(input_host_t* host); + + /** + * Append the report to the given input device. + */ + void (*input_device_definition_add_report)(input_host_t* host, + input_device_definition_t* d, input_report_definition_t* r); + + /** + * Add a collection with the given arity and ID. A collection describes a set + * of logically grouped properties such as the X and Y coordinates of a single finger touch or + * the set of keys on a keyboard. The arity declares how many repeated instances of this + * collection will appear in whatever report it is attached to. The ID describes the type of + * grouping being represented by the collection. For example, a touchscreen capable of + * reporting up to 2 fingers simultaneously might have a collection with the X and Y + * coordinates, an arity of 2, and an ID of INPUT_COLLECTION_USAGE_TOUCHSCREEN. Any given ID + * may only be present once for a given report. + */ + void (*input_report_definition_add_collection)(input_host_t* host, + input_report_definition_t* report, input_collection_id_t id, int32_t arity); + + /** + * Declare an int usage with the given properties. The report and collection defines where the + * usage is being declared. + */ + void (*input_report_definition_declare_usage_int)(input_host_t* host, + input_report_definition_t* report, input_collection_id_t id, + input_usage_t usage, int32_t min, int32_t max, float resolution); + + /** + * Declare a set of boolean usages with the given properties. The report and collection + * defines where the usages are being declared. + */ + void (*input_report_definition_declare_usages_bool)(input_host_t* host, + input_report_definition_t* report, input_collection_id_t id, + input_usage_t* usage, size_t usage_count); + + + /** + * Register a given input device definition. This notifies the host that an input device has + * been connected and gives a description of all its capabilities. + */ + input_device_handle_t* (*register_device)(input_host_t* host, + input_device_identifier_t* id, input_device_definition_t* d); + + /** Unregister the given device */ + void (*unregister_device)(input_host_t* host, input_device_handle_t* handle); + + /** + * Allocate a report that will contain all of the state as described by the given report. + */ + input_report_t* (*input_allocate_report)(input_host_t* host, input_report_definition_t* r); + + /** + * Add an int usage value to a report. + */ + void (*input_report_set_usage_int)(input_host_t* host, input_report_t* r, + input_collection_id_t id, input_usage_t usage, int32_t value, int32_t arity_index); + + /** + * Add a boolean usage value to a report. + */ + void (*input_report_set_usage_bool)(input_host_t* host, input_report_t* r, + input_collection_id_t id, input_usage_t usage, bool value, int32_t arity_index); + + void (*report_event)(input_host_t* host, input_device_handle_t* d, input_report_t* report); + + /** + * Retrieve the set of properties for the device. The returned + * input_property_map_t* may be used to query specific properties via the + * input_get_device_property callback. + */ + input_property_map_t* (*input_get_device_property_map)(input_host_t* host, + input_device_identifier_t* id); + /** + * Retrieve a property for the device with the given key. Returns NULL if + * the key does not exist, or an input_property_t* that must be freed using + * input_free_device_property(). Using an input_property_t after the + * corresponding input_property_map_t is freed is undefined. + */ + input_property_t* (*input_get_device_property)(input_host_t* host, + input_property_map_t* map, const char* key); + + /** + * Get the key for the input property. Returns NULL if the property is NULL. + * The returned const char* is owned by the input_property_t. + */ + const char* (*input_get_property_key)(input_host_t* host, input_property_t* property); + + /** + * Get the value for the input property. Returns NULL if the property is + * NULL. The returned const char* is owned by the input_property_t. + */ + const char* (*input_get_property_value)(input_host_t* host, input_property_t* property); + + /** + * Frees the input_property_t*. + */ + void (*input_free_device_property)(input_host_t* host, input_property_t* property); + + /** + * Frees the input_property_map_t*. + */ + void (*input_free_device_property_map)(input_host_t* host, input_property_map_t* map); +} input_host_callbacks_t; + +typedef struct input_module input_module_t; + +struct input_module { + /** + * Common methods of the input module. This *must* be the first member + * of input_module as users of this structure will cast a hw_module_t + * to input_module pointer in contexts where it's known + * the hw_module_t references a input_module. + */ + struct hw_module_t common; + + /** + * Initialize the module with host callbacks. At this point the HAL should start up whatever + * infrastructure it needs to in order to process input events. + */ + void (*init)(const input_module_t* module, input_host_t* host, input_host_callbacks_t cb); + + /** + * Sends an output report with a new set of state the host would like the given device to + * assume. + */ + void (*notify_report)(const input_module_t* module, input_report_t* report); +}; + +static inline int input_open(const struct hw_module_t** module, const char* type) { + return hw_get_module_by_class(INPUT_HARDWARE_MODULE_ID, type, module); +} + +__END_DECLS + +#endif /* ANDROID_INCLUDE_HARDWARE_INPUT_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/keymaster0.h b/phonelibs/android_hardware_libhardware/include/hardware/keymaster0.h new file mode 100644 index 0000000000..f020e5b188 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/keymaster0.h @@ -0,0 +1,149 @@ +/* + * 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_HARDWARE_KEYMASTER_0_H +#define ANDROID_HARDWARE_KEYMASTER_0_H + +#include + +__BEGIN_DECLS + +/** + * Keymaster0 device definition. + */ +struct keymaster0_device { + /** + * Common methods of the keymaster device. This *must* be the first member of + * keymaster0_device as users of this structure will cast a hw_device_t to + * keymaster0_device pointer in contexts where it's known the hw_device_t references a + * keymaster0_device. + */ + struct hw_device_t common; + + /** + * THIS IS DEPRECATED. Use the new "module_api_version" and "hal_api_version" + * fields in the keymaster_module initialization instead. + */ + uint32_t client_version; + + /** + * See flags defined for keymaster0_device::flags in keymaster_common.h + */ + uint32_t flags; + + void* context; + + /** + * Generates a public and private key. The key-blob returned is opaque + * and must subsequently provided for signing and verification. + * + * Returns: 0 on success or an error code less than 0. + */ + int (*generate_keypair)(const struct keymaster0_device* dev, + const keymaster_keypair_t key_type, const void* key_params, + uint8_t** key_blob, size_t* key_blob_length); + + /** + * Imports a public and private key pair. The imported keys will be in + * PKCS#8 format with DER encoding (Java standard). The key-blob + * returned is opaque and will be subsequently provided for signing + * and verification. + * + * Returns: 0 on success or an error code less than 0. + */ + int (*import_keypair)(const struct keymaster0_device* dev, + const uint8_t* key, const size_t key_length, + uint8_t** key_blob, size_t* key_blob_length); + + /** + * Gets the public key part of a key pair. The public key must be in + * X.509 format (Java standard) encoded byte array. + * + * Returns: 0 on success or an error code less than 0. + * On error, x509_data should not be allocated. + */ + int (*get_keypair_public)(const struct keymaster0_device* dev, + const uint8_t* key_blob, const size_t key_blob_length, + uint8_t** x509_data, size_t* x509_data_length); + + /** + * Deletes the key pair associated with the key blob. + * + * This function is optional and should be set to NULL if it is not + * implemented. + * + * Returns 0 on success or an error code less than 0. + */ + int (*delete_keypair)(const struct keymaster0_device* dev, + const uint8_t* key_blob, const size_t key_blob_length); + + /** + * Deletes all keys in the hardware keystore. Used when keystore is + * reset completely. + * + * This function is optional and should be set to NULL if it is not + * implemented. + * + * Returns 0 on success or an error code less than 0. + */ + int (*delete_all)(const struct keymaster0_device* dev); + + /** + * Signs data using a key-blob generated before. This can use either + * an asymmetric key or a secret key. + * + * Returns: 0 on success or an error code less than 0. + */ + int (*sign_data)(const struct keymaster0_device* dev, + const void* signing_params, + const uint8_t* key_blob, const size_t key_blob_length, + const uint8_t* data, const size_t data_length, + uint8_t** signed_data, size_t* signed_data_length); + + /** + * Verifies data signed with a key-blob. This can use either + * an asymmetric key or a secret key. + * + * Returns: 0 on successful verification or an error code less than 0. + */ + int (*verify_data)(const struct keymaster0_device* dev, + const void* signing_params, + const uint8_t* key_blob, const size_t key_blob_length, + const uint8_t* signed_data, const size_t signed_data_length, + const uint8_t* signature, const size_t signature_length); +}; +typedef struct keymaster0_device keymaster0_device_t; + + +/* Convenience API for opening and closing keymaster devices */ + +static inline int keymaster0_open(const struct hw_module_t* module, + keymaster0_device_t** device) +{ + int rc = module->methods->open(module, KEYSTORE_KEYMASTER, + (struct hw_device_t**) device); + + return rc; +} + +static inline int keymaster0_close(keymaster0_device_t* device) +{ + return device->common.close(&device->common); +} + +__END_DECLS + +#endif // ANDROID_HARDWARE_KEYMASTER_0_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/keymaster1.h b/phonelibs/android_hardware_libhardware/include/hardware/keymaster1.h new file mode 100644 index 0000000000..ac2cc2b408 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/keymaster1.h @@ -0,0 +1,597 @@ +/* + * 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_HARDWARE_KEYMASTER1_H +#define ANDROID_HARDWARE_KEYMASTER1_H + +#include +#include + +__BEGIN_DECLS + +/** + * Keymaster1 device definition + */ +struct keymaster1_device { + /** + * Common methods of the keymaster device. This *must* be the first member of + * keymaster_device as users of this structure will cast a hw_device_t to + * keymaster_device pointer in contexts where it's known the hw_device_t references a + * keymaster_device. + */ + struct hw_device_t common; + + /** + * THIS IS DEPRECATED. Use the new "module_api_version" and "hal_api_version" + * fields in the keymaster_module initialization instead. + */ + uint32_t client_version; + + /** + * See flags defined for keymaster0_devices::flags in keymaster_common.h + */ + uint32_t flags; + + void* context; + + /** + * \deprecated Generates a public and private key. The key-blob returned is opaque and must + * subsequently provided for signing and verification. + * + * Returns: 0 on success or an error code less than 0. + */ + int (*generate_keypair)(const struct keymaster1_device* dev, const keymaster_keypair_t key_type, + const void* key_params, uint8_t** key_blob, size_t* key_blob_length); + + /** + * \deprecated Imports a public and private key pair. The imported keys will be in PKCS#8 format + * with DER encoding (Java standard). The key-blob returned is opaque and will be subsequently + * provided for signing and verification. + * + * Returns: 0 on success or an error code less than 0. + */ + int (*import_keypair)(const struct keymaster1_device* dev, const uint8_t* key, + const size_t key_length, uint8_t** key_blob, size_t* key_blob_length); + + /** + * \deprecated Gets the public key part of a key pair. The public key must be in X.509 format + * (Java standard) encoded byte array. + * + * Returns: 0 on success or an error code less than 0. On error, x509_data + * should not be allocated. + */ + int (*get_keypair_public)(const struct keymaster1_device* dev, const uint8_t* key_blob, + const size_t key_blob_length, uint8_t** x509_data, + size_t* x509_data_length); + + /** + * \deprecated Deletes the key pair associated with the key blob. + * + * This function is optional and should be set to NULL if it is not + * implemented. + * + * Returns 0 on success or an error code less than 0. + */ + int (*delete_keypair)(const struct keymaster1_device* dev, const uint8_t* key_blob, + const size_t key_blob_length); + + /** + * \deprecated Deletes all keys in the hardware keystore. Used when keystore is reset + * completely. + * + * This function is optional and should be set to NULL if it is not + * implemented. + * + * Returns 0 on success or an error code less than 0. + */ + int (*delete_all)(const struct keymaster1_device* dev); + + /** + * \deprecated Signs data using a key-blob generated before. This can use either an asymmetric + * key or a secret key. + * + * Returns: 0 on success or an error code less than 0. + */ + int (*sign_data)(const struct keymaster1_device* dev, const void* signing_params, + const uint8_t* key_blob, const size_t key_blob_length, const uint8_t* data, + const size_t data_length, uint8_t** signed_data, size_t* signed_data_length); + + /** + * \deprecated Verifies data signed with a key-blob. This can use either an asymmetric key or a + * secret key. + * + * Returns: 0 on successful verification or an error code less than 0. + */ + int (*verify_data)(const struct keymaster1_device* dev, const void* signing_params, + const uint8_t* key_blob, const size_t key_blob_length, + const uint8_t* signed_data, const size_t signed_data_length, + const uint8_t* signature, const size_t signature_length); + + /** + * Gets algorithms supported. + * + * \param[in] dev The keymaster device structure. + * + * \param[out] algorithms Array of algorithms supported. The caller takes ownership of the + * array and must free() it. + * + * \param[out] algorithms_length Length of \p algorithms. + */ + keymaster_error_t (*get_supported_algorithms)(const struct keymaster1_device* dev, + keymaster_algorithm_t** algorithms, + size_t* algorithms_length); + + /** + * Gets the block modes supported for the specified algorithm. + * + * \param[in] dev The keymaster device structure. + * + * \param[in] algorithm The algorithm for which supported modes will be returned. + * + * \param[out] modes Array of modes supported. The caller takes ownership of the array and must + * free() it. + * + * \param[out] modes_length Length of \p modes. + */ + keymaster_error_t (*get_supported_block_modes)(const struct keymaster1_device* dev, + keymaster_algorithm_t algorithm, + keymaster_purpose_t purpose, + keymaster_block_mode_t** modes, + size_t* modes_length); + + /** + * Gets the padding modes supported for the specified algorithm. Caller assumes ownership of + * the allocated array. + * + * \param[in] dev The keymaster device structure. + * + * \param[in] algorithm The algorithm for which supported padding modes will be returned. + * + * \param[out] modes Array of padding modes supported. The caller takes ownership of the array + * and must free() it. + * + * \param[out] modes_length Length of \p modes. + */ + keymaster_error_t (*get_supported_padding_modes)(const struct keymaster1_device* dev, + keymaster_algorithm_t algorithm, + keymaster_purpose_t purpose, + keymaster_padding_t** modes, + size_t* modes_length); + + /** + * Gets the digests supported for the specified algorithm. Caller assumes ownership of the + * allocated array. + * + * \param[in] dev The keymaster device structure. + * + * \param[in] algorithm The algorithm for which supported digests will be returned. + * + * \param[out] digests Array of digests supported. The caller takes ownership of the array and + * must free() it. + * + * \param[out] digests_length Length of \p digests. + */ + keymaster_error_t (*get_supported_digests)(const struct keymaster1_device* dev, + keymaster_algorithm_t algorithm, + keymaster_purpose_t purpose, + keymaster_digest_t** digests, + size_t* digests_length); + + /** + * Gets the key import formats supported for keys of the specified algorithm. Caller assumes + * ownership of the allocated array. + * + * \param[in] dev The keymaster device structure. + * + * \param[in] algorithm The algorithm for which supported formats will be returned. + * + * \param[out] formats Array of formats supported. The caller takes ownership of the array and + * must free() it. + * + * \param[out] formats_length Length of \p formats. + */ + keymaster_error_t (*get_supported_import_formats)(const struct keymaster1_device* dev, + keymaster_algorithm_t algorithm, + keymaster_key_format_t** formats, + size_t* formats_length); + + /** + * Gets the key export formats supported for keys of the specified algorithm. Caller assumes + * ownership of the allocated array. + * + * \param[in] dev The keymaster device structure. + * + * \param[in] algorithm The algorithm for which supported formats will be returned. + * + * \param[out] formats Array of formats supported. The caller takes ownership of the array and + * must free() it. + * + * \param[out] formats_length Length of \p formats. + */ + keymaster_error_t (*get_supported_export_formats)(const struct keymaster1_device* dev, + keymaster_algorithm_t algorithm, + keymaster_key_format_t** formats, + size_t* formats_length); + + /** + * Adds entropy to the RNG used by keymaster. Entropy added through this method is guaranteed + * not to be the only source of entropy used, and the mixing function is required to be secure, + * in the sense that if the RNG is seeded (from any source) with any data the attacker cannot + * predict (or control), then the RNG output is indistinguishable from random. Thus, if the + * entropy from any source is good, the output will be good. + * + * \param[in] dev The keymaster device structure. + * + * \param[in] data Random data to be mixed in. + * + * \param[in] data_length Length of \p data. + */ + keymaster_error_t (*add_rng_entropy)(const struct keymaster1_device* dev, const uint8_t* data, + size_t data_length); + + /** + * Generates a key, or key pair, returning a key blob and/or a description of the key. + * + * Key generation parameters are defined as keymaster tag/value pairs, provided in \p params. + * See keymaster_tag_t for the full list. Some values that are always required for generation + * of useful keys are: + * + * - KM_TAG_ALGORITHM; + * - KM_TAG_PURPOSE; and + * - (KM_TAG_USER_SECURE_ID and KM_TAG_USER_AUTH_TYPE) or KM_TAG_NO_AUTH_REQUIRED. + * + * KM_TAG_AUTH_TIMEOUT should generally be specified unless KM_TAG_NO_AUTH_REQUIRED is present, + * or the user will have to authenticate for every use. + * + * KM_TAG_BLOCK_MODE, KM_TAG_PADDING, KM_TAG_MAC_LENGTH and KM_TAG_DIGEST must be specified for + * algorithms that require them. + * + * The following tags may not be specified; their values will be provided by the implementation. + * + * - KM_TAG_ORIGIN, + * - KM_TAG_ROLLBACK_RESISTANT, + * - KM_TAG_CREATION_DATETIME + * + * \param[in] dev The keymaster device structure. + * + * \param[in] params Array of key generation parameters. + * + * \param[in] params_count Length of \p params. + * + * \param[out] key_blob returns the generated key. \p key_blob must not be NULL. The caller + * assumes ownership key_blob->key_material and must free() it. + * + * \param[out] characteristics returns the characteristics of the key that was, generated, if + * non-NULL. If non-NULL, the caller assumes ownership and must deallocate with + * keymaster_free_characteristics(). Note that KM_TAG_ROOT_OF_TRUST, KM_TAG_APPLICATION_ID and + * KM_TAG_APPLICATION_DATA are never returned. + */ + keymaster_error_t (*generate_key)(const struct keymaster1_device* dev, + const keymaster_key_param_set_t* params, + keymaster_key_blob_t* key_blob, + keymaster_key_characteristics_t** characteristics); + + /** + * Returns the characteristics of the specified key, or KM_ERROR_INVALID_KEY_BLOB if the + * key_blob is invalid (implementations must fully validate the integrity of the key). + * client_id and app_data must be the ID and data provided when the key was generated or + * imported, or empty if KM_TAG_APPLICATION_ID and/or KM_TAG_APPLICATION_DATA were not provided + * during generation. Those values are not included in the returned characteristics. The + * caller assumes ownership of the allocated characteristics object, which must be deallocated + * with keymaster_free_characteristics(). + * + * Note that KM_TAG_ROOT_OF_TRUST, KM_TAG_APPLICATION_ID and KM_TAG_APPLICATION_DATA are never + * returned. + * + * \param[in] dev The keymaster device structure. + * + * \param[in] key_blob The key to retreive characteristics from. + * + * \param[in] client_id The client ID data, or NULL if none associated. + * + * \param[in] app_id The app data, or NULL if none associated. + * + * \param[out] characteristics The key characteristics. + */ + keymaster_error_t (*get_key_characteristics)(const struct keymaster1_device* dev, + const keymaster_key_blob_t* key_blob, + const keymaster_blob_t* client_id, + const keymaster_blob_t* app_data, + keymaster_key_characteristics_t** characteristics); + + /** + * Imports a key, or key pair, returning a key blob and/or a description of the key. + * + * Most key import parameters are defined as keymaster tag/value pairs, provided in "params". + * See keymaster_tag_t for the full list. Values that are always required for import of useful + * keys are: + * + * - KM_TAG_ALGORITHM; + * - KM_TAG_PURPOSE; and + * - (KM_TAG_USER_SECURE_ID and KM_TAG_USER_AUTH_TYPE) or KM_TAG_NO_AUTH_REQUIRED. + * + * KM_TAG_AUTH_TIMEOUT should generally be specified. If unspecified, the user will have to + * authenticate for every use. + * + * The following tags will take default values if unspecified: + * + * - KM_TAG_KEY_SIZE will default to the size of the key provided. + * - KM_TAG_RSA_PUBLIC_EXPONENT will default to the value in the key provided (for RSA keys) + * + * The following tags may not be specified; their values will be provided by the implementation. + * + * - KM_TAG_ORIGIN, + * - KM_TAG_ROLLBACK_RESISTANT, + * - KM_TAG_CREATION_DATETIME + * + * \param[in] dev The keymaster device structure. + * + * \param[in] params Parameters defining the imported key. + * + * \param[in] params_count The number of entries in \p params. + * + * \param[in] key_format specifies the format of the key data in key_data. + * + * \param[out] key_blob Used to return the opaque key blob. Must be non-NULL. The caller + * assumes ownership of the contained key_material. + * + * \param[out] characteristics Used to return the characteristics of the imported key. May be + * NULL, in which case no characteristics will be returned. If non-NULL, the caller assumes + * ownership and must deallocate with keymaster_free_characteristics(). Note that + * KM_TAG_ROOT_OF_TRUST, KM_TAG_APPLICATION_ID and + * KM_TAG_APPLICATION_DATA are never returned. + */ + keymaster_error_t (*import_key)(const struct keymaster1_device* dev, + const keymaster_key_param_set_t* params, + keymaster_key_format_t key_format, + const keymaster_blob_t* key_data, + keymaster_key_blob_t* key_blob, + keymaster_key_characteristics_t** characteristics); + + /** + * Exports a public key, returning a byte array in the specified format. + * + * \param[in] dev The keymaster device structure. + * + * \param[in] export_format The format to be used for exporting the key. + * + * \param[in] key_to_export The key to export. + * + * \param[out] export_data The exported key material. The caller assumes ownership. + * + * \param[out] export_data_length The length of \p export_data. + */ + keymaster_error_t (*export_key)(const struct keymaster1_device* dev, + keymaster_key_format_t export_format, + const keymaster_key_blob_t* key_to_export, + const keymaster_blob_t* client_id, + const keymaster_blob_t* app_data, + keymaster_blob_t* export_data); + + /** + * Deletes the key, or key pair, associated with the key blob. After calling this function it + * will be impossible to use the key for any other operations. May be applied to keys from + * foreign roots of trust (keys not usable under the current root of trust). + * + * This function is optional and should be set to NULL if it is not implemented. + * + * \param[in] dev The keymaster device structure. + * + * \param[in] key The key to be deleted. + */ + keymaster_error_t (*delete_key)(const struct keymaster1_device* dev, + const keymaster_key_blob_t* key); + + /** + * Deletes all keys in the hardware keystore. Used when keystore is reset completely. After + * calling this function it will be impossible to use any previously generated or imported key + * blobs for any operations. + * + * This function is optional and should be set to NULL if it is not implemented. + * + * \param[in] dev The keymaster device structure. + */ + keymaster_error_t (*delete_all_keys)(const struct keymaster1_device* dev); + + /** + * Begins a cryptographic operation using the specified key. If all is well, begin() will + * return KM_ERROR_OK and create an operation handle which must be passed to subsequent calls to + * update(), finish() or abort(). + * + * It is critical that each call to begin() be paired with a subsequent call to finish() or + * abort(), to allow the keymaster implementation to clean up any internal operation state. + * Failure to do this may leak internal state space or other internal resources and may + * eventually cause begin() to return KM_ERROR_TOO_MANY_OPERATIONS when it runs out of space for + * operations. Any result other than KM_ERROR_OK from begin(), update() or finish() implicitly + * aborts the operation, in which case abort() need not be called (and will return + * KM_ERROR_INVALID_OPERATION_HANDLE if called). + * + * \param[in] dev The keymaster device structure. + * + * \param[in] purpose The purpose of the operation, one of KM_PURPOSE_ENCRYPT, + * KM_PURPOSE_DECRYPT, KM_PURPOSE_SIGN or KM_PURPOSE_VERIFY. Note that for AEAD modes, + * encryption and decryption imply signing and verification, respectively, but should be + * specified as KM_PURPOSE_ENCRYPT and KM_PURPOSE_DECRYPT. + * + * \param[in] key The key to be used for the operation. \p key must have a purpose compatible + * with \p purpose and all of its usage requirements must be satisfied, or begin() will return + * an appropriate error code. + * + * \param[in] in_params Additional parameters for the operation. This is typically used to + * provide authentication data, with KM_TAG_AUTH_TOKEN. If KM_TAG_APPLICATION_ID or + * KM_TAG_APPLICATION_DATA were provided during generation, they must be provided here, or the + * operation will fail with KM_ERROR_INVALID_KEY_BLOB. For operations that require a nonce or + * IV, on keys that were generated with KM_TAG_CALLER_NONCE, in_params may contain a tag + * KM_TAG_NONCE. For AEAD operations KM_TAG_CHUNK_SIZE is specified here. + * + * \param[out] out_params Output parameters. Used to return additional data from the operation + * initialization, notably to return the IV or nonce from operations that generate an IV or + * nonce. The caller takes ownership of the output parameters array and must free it with + * keymaster_free_param_set(). out_params may be set to NULL if no output parameters are + * expected. If out_params is NULL, and output paramaters are generated, begin() will return + * KM_ERROR_OUTPUT_PARAMETER_NULL. + * + * \param[out] operation_handle The newly-created operation handle which must be passed to + * update(), finish() or abort(). If operation_handle is NULL, begin() will return + * KM_ERROR_OUTPUT_PARAMETER_NULL. + */ + keymaster_error_t (*begin)(const struct keymaster1_device* dev, keymaster_purpose_t purpose, + const keymaster_key_blob_t* key, + const keymaster_key_param_set_t* in_params, + keymaster_key_param_set_t* out_params, + keymaster_operation_handle_t* operation_handle); + + /** + * Provides data to, and possibly receives output from, an ongoing cryptographic operation begun + * with begin(). + * + * If operation_handle is invalid, update() will return KM_ERROR_INVALID_OPERATION_HANDLE. + * + * update() may not consume all of the data provided in the data buffer. update() will return + * the amount consumed in *data_consumed. The caller should provide the unconsumed data in a + * subsequent call. + * + * \param[in] dev The keymaster device structure. + * + * \param[in] operation_handle The operation handle returned by begin(). + * + * \param[in] in_params Additional parameters for the operation. For AEAD modes, this is used + * to specify KM_TAG_ADDITIONAL_DATA. Note that additional data may be provided in multiple + * calls to update(), but only until input data has been provided. + * + * \param[in] input Data to be processed, per the parameters established in the call to begin(). + * Note that update() may or may not consume all of the data provided. See \p input_consumed. + * + * \param[out] input_consumed Amount of data that was consumed by update(). If this is less + * than the amount provided, the caller should provide the remainder in a subsequent call to + * update(). + * + * \param[out] out_params Output parameters. Used to return additional data from the operation + * The caller takes ownership of the output parameters array and must free it with + * keymaster_free_param_set(). out_params may be set to NULL if no output parameters are + * expected. If out_params is NULL, and output paramaters are generated, begin() will return + * KM_ERROR_OUTPUT_PARAMETER_NULL. + * + * \param[out] output The output data, if any. The caller assumes ownership of the allocated + * buffer. output must not be NULL. + * + * Note that update() may not provide any output, in which case output->data_length will be + * zero, and output->data may be either NULL or zero-length (so the caller should always free() + * it). + */ + keymaster_error_t (*update)(const struct keymaster1_device* dev, + keymaster_operation_handle_t operation_handle, + const keymaster_key_param_set_t* in_params, + const keymaster_blob_t* input, size_t* input_consumed, + keymaster_key_param_set_t* out_params, keymaster_blob_t* output); + + /** + * Finalizes a cryptographic operation begun with begin() and invalidates \p operation_handle. + * + * \param[in] dev The keymaster device structure. + * + * \param[in] operation_handle The operation handle returned by begin(). This handle will be + * invalidated. + * + * \param[in] params Additional parameters for the operation. For AEAD modes, this is used to + * specify KM_TAG_ADDITIONAL_DATA, but only if no input data was provided to update(). + * + * \param[in] signature The signature to be verified if the purpose specified in the begin() + * call was KM_PURPOSE_VERIFY. + * + * \param[out] output The output data, if any. The caller assumes ownership of the allocated + * buffer. + * + * If the operation being finished is a signature verification or an AEAD-mode decryption and + * verification fails then finish() will return KM_ERROR_VERIFICATION_FAILED. + */ + keymaster_error_t (*finish)(const struct keymaster1_device* dev, + keymaster_operation_handle_t operation_handle, + const keymaster_key_param_set_t* in_params, + const keymaster_blob_t* signature, + keymaster_key_param_set_t* out_params, keymaster_blob_t* output); + + /** + * Aborts a cryptographic operation begun with begin(), freeing all internal resources and + * invalidating \p operation_handle. + */ + keymaster_error_t (*abort)(const struct keymaster1_device* dev, + keymaster_operation_handle_t operation_handle); + + /** + * Generates a pair of ATTK defined in SOTER. Save the private key into RPMB. + * Note that the ATTK generated will never be touched outside the keymaster. + * + * \param[in] dev The keymaster device structure. + * + * \param[in] copy_num The number of copies that will be saved in the RPMB. + */ + keymaster_error_t (*generate_attk_key_pair)(const struct keymaster1_device* dev, + const uint8_t copy_num); + + /** + * Verify the existance ATTK defined in SOTER. + * + * \param[in] dev The keymaster device structure. + * + * Returns: 0 if the ATTK exists. + */ + keymaster_error_t (*verify_attk_key_pair)(const struct keymaster1_device* dev); + + /** + * Export the public key of ATTK in PEM format. + * + * \param[in] dev The keymaster device structure. + * + * \param[out] pub_key_data The public key data in X.509v3 format PEM encoded + * + * \param[out] pub_key_data_length The length of the public key data. + */ + keymaster_error_t (*export_attk_public_key)(const struct keymaster1_device* dev, + const uint8_t* pub_key_data, + const size_t pub_key_data_length); + + /** + * Get Unique device ID. + * + * \param[in] dev The keymaster device structure. + * + * \param[out] device_id The unique id for each device, format as below: + * 1.bytes 0-3: Identify each silicon provider id. + * 2.bytes 4-7: SoC model ID, defined by each silicon provider + * 3.bytes 8-15: Public Chip Serial *Number of SoC, defined by each silicon provider + * + * \param[out] device_id_length The length of the device id. + */ + keymaster_error_t (*get_device_id)(const struct keymaster1_device* dev, + const uint8_t* device_id, + const size_t device_id_length); +}; +typedef struct keymaster1_device keymaster1_device_t; + +/* Convenience API for opening and closing keymaster devices */ + +static inline int keymaster1_open(const struct hw_module_t* module, keymaster1_device_t** device) { + return module->methods->open(module, KEYSTORE_KEYMASTER, (struct hw_device_t**)device); +} + +static inline int keymaster1_close(keymaster1_device_t* device) { + return device->common.close(&device->common); +} + +__END_DECLS + +#endif // ANDROID_HARDWARE_KEYMASTER1_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/keymaster_common.h b/phonelibs/android_hardware_libhardware/include/hardware/keymaster_common.h new file mode 100644 index 0000000000..772d7e4d23 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/keymaster_common.h @@ -0,0 +1,185 @@ +/* + * 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_HARDWARE_KEYMASTER_COMMON_H +#define ANDROID_HARDWARE_KEYMASTER_COMMON_H + +#include +#include +#include + +#include + +__BEGIN_DECLS + +/** + * The id of this module + */ +#define KEYSTORE_HARDWARE_MODULE_ID "keystore" + +#define KEYSTORE_KEYMASTER "keymaster" + + +/** + * Settings for "module_api_version" and "hal_api_version" + * fields in the keymaster_module initialization. + */ + +/** + * Keymaster 0.X module version provide the same APIs, but later versions add more options + * for algorithms and flags. + */ +#define KEYMASTER_MODULE_API_VERSION_0_2 HARDWARE_MODULE_API_VERSION(0, 2) +#define KEYMASTER_DEVICE_API_VERSION_0_2 HARDWARE_DEVICE_API_VERSION(0, 2) + +#define KEYMASTER_MODULE_API_VERSION_0_3 HARDWARE_MODULE_API_VERSION(0, 3) +#define KEYMASTER_DEVICE_API_VERSION_0_3 HARDWARE_DEVICE_API_VERSION(0, 3) + +/** + * Keymaster 1.0 module version provides a completely different API, incompatible with 0.X. + */ +#define KEYMASTER_MODULE_API_VERSION_1_0 HARDWARE_MODULE_API_VERSION(1, 0) +#define KEYMASTER_DEVICE_API_VERSION_1_0 HARDWARE_DEVICE_API_VERSION(1, 0) + +struct keystore_module { + /** + * Common methods of the keystore module. This *must* be the first member of keystore_module as + * users of this structure will cast a hw_module_t to keystore_module pointer in contexts where + * it's known the hw_module_t references a keystore_module. + */ + hw_module_t common; + + /* There are no keystore module methods other than the common ones. */ +}; + +/** + * Flags for keymaster0_device::flags + */ +enum { + /* + * Indicates this keymaster implementation does not have hardware that + * keeps private keys out of user space. + * + * This should not be implemented on anything other than the default + * implementation. + */ + KEYMASTER_SOFTWARE_ONLY = 1 << 0, + + /* + * This indicates that the key blobs returned via all the primitives + * are sufficient to operate on their own without the trusted OS + * querying userspace to retrieve some other data. Key blobs of + * this type are normally returned encrypted with a + * Key Encryption Key (KEK). + * + * This is currently used by "vold" to know whether the whole disk + * encryption secret can be unwrapped without having some external + * service started up beforehand since the "/data" partition will + * be unavailable at that point. + */ + KEYMASTER_BLOBS_ARE_STANDALONE = 1 << 1, + + /* + * Indicates that the keymaster module supports DSA keys. + */ + KEYMASTER_SUPPORTS_DSA = 1 << 2, + + /* + * Indicates that the keymaster module supports EC keys. + */ + KEYMASTER_SUPPORTS_EC = 1 << 3, +}; + +/** + * Asymmetric key pair types. + */ +typedef enum { + TYPE_RSA = 1, + TYPE_DSA = 2, + TYPE_EC = 3, +} keymaster_keypair_t; + +/** + * Parameters needed to generate an RSA key. + */ +typedef struct { + uint32_t modulus_size; + uint64_t public_exponent; +} keymaster_rsa_keygen_params_t; + +/** + * Parameters needed to generate a DSA key. + */ +typedef struct { + uint32_t key_size; + uint32_t generator_len; + uint32_t prime_p_len; + uint32_t prime_q_len; + const uint8_t* generator; + const uint8_t* prime_p; + const uint8_t* prime_q; +} keymaster_dsa_keygen_params_t; + +/** + * Parameters needed to generate an EC key. + * + * Field size is the only parameter in version 2. The sizes correspond to these required curves: + * + * 192 = NIST P-192 + * 224 = NIST P-224 + * 256 = NIST P-256 + * 384 = NIST P-384 + * 521 = NIST P-521 + * + * The parameters for these curves are available at: http://www.nsa.gov/ia/_files/nist-routines.pdf + * in Chapter 4. + */ +typedef struct { + uint32_t field_size; +} keymaster_ec_keygen_params_t; + + +/** + * Digest type. + */ +typedef enum { + DIGEST_NONE, +} keymaster_digest_algorithm_t; + +/** + * Type of padding used for RSA operations. + */ +typedef enum { + PADDING_NONE, +} keymaster_rsa_padding_t; + + +typedef struct { + keymaster_digest_algorithm_t digest_type; +} keymaster_dsa_sign_params_t; + +typedef struct { + keymaster_digest_algorithm_t digest_type; +} keymaster_ec_sign_params_t; + +typedef struct { + keymaster_digest_algorithm_t digest_type; + keymaster_rsa_padding_t padding_type; +} keymaster_rsa_sign_params_t; + +__END_DECLS + +#endif // ANDROID_HARDWARE_KEYMASTER_COMMON_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/keymaster_defs.h b/phonelibs/android_hardware_libhardware/include/hardware/keymaster_defs.h new file mode 100644 index 0000000000..1a723c94a8 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/keymaster_defs.h @@ -0,0 +1,539 @@ +/* + * Copyright (C) 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_HARDWARE_KEYMASTER_DEFS_H +#define ANDROID_HARDWARE_KEYMASTER_DEFS_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +/** + * Authorization tags each have an associated type. This enumeration facilitates tagging each with + * a type, by using the high four bits (of an implied 32-bit unsigned enum value) to specify up to + * 16 data types. These values are ORed with tag IDs to generate the final tag ID values. + */ +typedef enum { + KM_INVALID = 0 << 28, /* Invalid type, used to designate a tag as uninitialized */ + KM_ENUM = 1 << 28, + KM_ENUM_REP = 2 << 28, /* Repeatable enumeration value. */ + KM_UINT = 3 << 28, + KM_UINT_REP = 4 << 28, /* Repeatable integer value */ + KM_ULONG = 5 << 28, + KM_DATE = 6 << 28, + KM_BOOL = 7 << 28, + KM_BIGNUM = 8 << 28, + KM_BYTES = 9 << 28, + KM_ULONG_REP = 10 << 28, /* Repeatable long value */ +} keymaster_tag_type_t; + +typedef enum { + KM_TAG_INVALID = KM_INVALID | 0, + + /* + * Tags that must be semantically enforced by hardware and software implementations. + */ + + /* Crypto parameters */ + KM_TAG_PURPOSE = KM_ENUM_REP | 1, /* keymaster_purpose_t. */ + KM_TAG_ALGORITHM = KM_ENUM | 2, /* keymaster_algorithm_t. */ + KM_TAG_KEY_SIZE = KM_UINT | 3, /* Key size in bits. */ + KM_TAG_BLOCK_MODE = KM_ENUM_REP | 4, /* keymaster_block_mode_t. */ + KM_TAG_DIGEST = KM_ENUM_REP | 5, /* keymaster_digest_t. */ + KM_TAG_PADDING = KM_ENUM_REP | 6, /* keymaster_padding_t. */ + KM_TAG_CALLER_NONCE = KM_BOOL | 7, /* Allow caller to specify nonce or IV. */ + KM_TAG_MIN_MAC_LENGTH = KM_UINT | 8, /* Minimum length of MAC or AEAD authentication tag in + * bits. */ + + /* Algorithm-specific. */ + KM_TAG_RSA_PUBLIC_EXPONENT = KM_ULONG | 200, + + /* Other hardware-enforced. */ + KM_TAG_BLOB_USAGE_REQUIREMENTS = KM_ENUM | 301, /* keymaster_key_blob_usage_requirements_t */ + KM_TAG_BOOTLOADER_ONLY = KM_BOOL | 302, /* Usable only by bootloader */ + + /* + * Tags that should be semantically enforced by hardware if possible and will otherwise be + * enforced by software (keystore). + */ + + /* Key validity period */ + KM_TAG_ACTIVE_DATETIME = KM_DATE | 400, /* Start of validity */ + KM_TAG_ORIGINATION_EXPIRE_DATETIME = KM_DATE | 401, /* Date when new "messages" should no + longer be created. */ + KM_TAG_USAGE_EXPIRE_DATETIME = KM_DATE | 402, /* Date when existing "messages" should no + longer be trusted. */ + KM_TAG_MIN_SECONDS_BETWEEN_OPS = KM_UINT | 403, /* Minimum elapsed time between + cryptographic operations with the key. */ + KM_TAG_MAX_USES_PER_BOOT = KM_UINT | 404, /* Number of times the key can be used per + boot. */ + + /* User authentication */ + KM_TAG_ALL_USERS = KM_BOOL | 500, /* Reserved for future use -- ignore */ + KM_TAG_USER_ID = KM_UINT | 501, /* Reserved for future use -- ignore */ + KM_TAG_USER_SECURE_ID = KM_ULONG_REP | 502, /* Secure ID of authorized user or authenticator(s). + Disallowed if KM_TAG_ALL_USERS or + KM_TAG_NO_AUTH_REQUIRED is present. */ + KM_TAG_NO_AUTH_REQUIRED = KM_BOOL | 503, /* If key is usable without authentication. */ + KM_TAG_USER_AUTH_TYPE = KM_ENUM | 504, /* Bitmask of authenticator types allowed when + * KM_TAG_USER_SECURE_ID contains a secure user ID, + * rather than a secure authenticator ID. Defined in + * hw_authenticator_type_t in hw_auth_token.h. */ + KM_TAG_AUTH_TIMEOUT = KM_UINT | 505, /* Required freshness of user authentication for + private/secret key operations, in seconds. + Public key operations require no authentication. + If absent, authentication is required for every + use. Authentication state is lost when the + device is powered off. */ + + /* Application access control */ + KM_TAG_ALL_APPLICATIONS = KM_BOOL | 600, /* Reserved for future use -- ignore */ + KM_TAG_APPLICATION_ID = KM_BYTES | 601, /* Reserved for fugure use -- ignore */ + + /* + * Semantically unenforceable tags, either because they have no specific meaning or because + * they're informational only. + */ + KM_TAG_APPLICATION_DATA = KM_BYTES | 700, /* Data provided by authorized application. */ + KM_TAG_CREATION_DATETIME = KM_DATE | 701, /* Key creation time */ + KM_TAG_ORIGIN = KM_ENUM | 702, /* keymaster_key_origin_t. */ + KM_TAG_ROLLBACK_RESISTANT = KM_BOOL | 703, /* Whether key is rollback-resistant. */ + KM_TAG_ROOT_OF_TRUST = KM_BYTES | 704, /* Root of trust ID. */ + + /* Tags used only to provide data to or receive data from operations */ + KM_TAG_ASSOCIATED_DATA = KM_BYTES | 1000, /* Used to provide associated data for AEAD modes. */ + KM_TAG_NONCE = KM_BYTES | 1001, /* Nonce or Initialization Vector */ + KM_TAG_AUTH_TOKEN = KM_BYTES | 1002, /* Authentication token that proves secure user + authentication has been performed. Structure + defined in hw_auth_token_t in hw_auth_token.h. */ + KM_TAG_MAC_LENGTH = KM_UINT | 1003, /* MAC or AEAD authentication tag length in bits. */ + + /* Tags used only for SOTER */ + /* Tags used only to check if the key is for SOTER */ + KM_TAG_SOTER_IS_FROM_SOTER = KM_BOOL | 11000, + /* Attach signature signed with ATTK[pri] while exporting public key */ + KM_TAG_SOTER_IS_AUTO_SIGNED_WITH_ATTK_WHEN_GET_PUBLIC_KEY = KM_BOOL | 11001, + /* Attach signature signed with specified private key while exporting public key */ + KM_TAG_SOTER_IS_AUTO_SIGNED_WITH_COMMON_KEY_WHEN_GET_PUBLIC_KEY = KM_BOOL | 11002, + /* keyalias for the keypair of KM_TAG_SOTER_IS_AUTO_SIGNED_WITH_COMMON_KEY_WHEN_GET_PUBLIC_KEY */ + KM_TAG_SOTER_AUTO_SIGNED_COMMON_KEY_WHEN_GET_PUBLIC_KEY = KM_BYTES | 11003, + /* Attach counter while exporting publick key */ + KM_TAG_SOTER_AUTO_ADD_COUNTER_WHEN_GET_PUBLIC_KEY = KM_BOOL | 11004, + /* Attach secmsg(TEE_Name, TEE_Version, Fingerprint_Sensor_Name, Fingerprint_Sensor_Version) + fingerprint_id and counter while signing */ + KM_TAG_SOTER_IS_SECMSG_FID_COUNTER_SIGNED_WHEN_SIGN = KM_BOOL | 11005, + /* use and set ATTK index to next backup ATTK */ + KM_TAG_SOTER_USE_NEXT_ATTK = KM_BOOL | 11006, + /* attach soter uid */ + KM_TAG_SOTER_UID = KM_UINT | 11007, + /* attach key blob of KM_TAG_SOTER_AUTO_SIGNED_COMMON_KEY_WHEN_GET_PUBLIC_KEY if needed */ + KM_TAG_SOTER_AUTO_SIGNED_COMMON_KEY_WHEN_GET_PUBLIC_KEY_BLOB = KM_BYTES | 11008, +} keymaster_tag_t; + +/** + * Algorithms that may be provided by keymaster implementations. Those that must be provided by all + * implementations are tagged as "required". + */ +typedef enum { + /* Asymmetric algorithms. */ + KM_ALGORITHM_RSA = 1, + // KM_ALGORITHM_DSA = 2, -- Removed, do not re-use value 2. + KM_ALGORITHM_EC = 3, + + /* Block ciphers algorithms */ + KM_ALGORITHM_AES = 32, + + /* MAC algorithms */ + KM_ALGORITHM_HMAC = 128, +} keymaster_algorithm_t; + +/** + * Symmetric block cipher modes provided by keymaster implementations. + */ +typedef enum { + /* Unauthenticated modes, usable only for encryption/decryption and not generally recommended + * except for compatibility with existing other protocols. */ + KM_MODE_ECB = 1, + KM_MODE_CBC = 2, + KM_MODE_CTR = 3, + + /* Authenticated modes, usable for encryption/decryption and signing/verification. Recommended + * over unauthenticated modes for all purposes. */ + KM_MODE_GCM = 32, +} keymaster_block_mode_t; + +/** + * Padding modes that may be applied to plaintext for encryption operations. This list includes + * padding modes for both symmetric and asymmetric algorithms. Note that implementations should not + * provide all possible combinations of algorithm and padding, only the + * cryptographically-appropriate pairs. + */ +typedef enum { + KM_PAD_NONE = 1, /* deprecated */ + KM_PAD_RSA_OAEP = 2, + KM_PAD_RSA_PSS = 3, + KM_PAD_RSA_PKCS1_1_5_ENCRYPT = 4, + KM_PAD_RSA_PKCS1_1_5_SIGN = 5, + KM_PAD_PKCS7 = 64, +} keymaster_padding_t; + +/** + * Digests provided by keymaster implementations. + */ +typedef enum { + KM_DIGEST_NONE = 0, + KM_DIGEST_MD5 = 1, /* Optional, may not be implemented in hardware, will be handled in software + * if needed. */ + KM_DIGEST_SHA1 = 2, + KM_DIGEST_SHA_2_224 = 3, + KM_DIGEST_SHA_2_256 = 4, + KM_DIGEST_SHA_2_384 = 5, + KM_DIGEST_SHA_2_512 = 6, +} keymaster_digest_t; + +/** + * The origin of a key (or pair), i.e. where it was generated. Note that KM_TAG_ORIGIN can be found + * in either the hardware-enforced or software-enforced list for a key, indicating whether the key + * is hardware or software-based. Specifically, a key with KM_ORIGIN_GENERATED in the + * hardware-enforced list is guaranteed never to have existed outide the secure hardware. + */ +typedef enum { + KM_ORIGIN_GENERATED = 0, /* Generated in keymaster */ + KM_ORIGIN_IMPORTED = 2, /* Imported, origin unknown */ + KM_ORIGIN_UNKNOWN = 3, /* Keymaster did not record origin. This value can only be seen on + * keys in a keymaster0 implementation. The keymaster0 adapter uses + * this value to document the fact that it is unkown whether the key + * was generated inside or imported into keymaster. */ +} keymaster_key_origin_t; + +/** + * Usability requirements of key blobs. This defines what system functionality must be available + * for the key to function. For example, key "blobs" which are actually handles referencing + * encrypted key material stored in the file system cannot be used until the file system is + * available, and should have BLOB_REQUIRES_FILE_SYSTEM. Other requirements entries will be added + * as needed for implementations. This type is new in 0_4. + */ +typedef enum { + KM_BLOB_STANDALONE = 0, + KM_BLOB_REQUIRES_FILE_SYSTEM = 1, +} keymaster_key_blob_usage_requirements_t; + +/** + * Possible purposes of a key (or pair). This type is new in 0_4. + */ +typedef enum { + KM_PURPOSE_ENCRYPT = 0, + KM_PURPOSE_DECRYPT = 1, + KM_PURPOSE_SIGN = 2, + KM_PURPOSE_VERIFY = 3, +} keymaster_purpose_t; + +typedef struct { + const uint8_t* data; + size_t data_length; +} keymaster_blob_t; + +typedef struct { + keymaster_tag_t tag; + union { + uint32_t enumerated; /* KM_ENUM and KM_ENUM_REP */ + bool boolean; /* KM_BOOL */ + uint32_t integer; /* KM_INT and KM_INT_REP */ + uint64_t long_integer; /* KM_LONG */ + uint64_t date_time; /* KM_DATE */ + keymaster_blob_t blob; /* KM_BIGNUM and KM_BYTES*/ + }; +} keymaster_key_param_t; + +typedef struct { + keymaster_key_param_t* params; /* may be NULL if length == 0 */ + size_t length; +} keymaster_key_param_set_t; + +/** + * Parameters that define a key's characteristics, including authorized modes of usage and access + * control restrictions. The parameters are divided into two categories, those that are enforced by + * secure hardware, and those that are not. For a software-only keymaster implementation the + * enforced array must NULL. Hardware implementations must enforce everything in the enforced + * array. + */ +typedef struct { + keymaster_key_param_set_t hw_enforced; + keymaster_key_param_set_t sw_enforced; +} keymaster_key_characteristics_t; + +typedef struct { + const uint8_t* key_material; + size_t key_material_size; +} keymaster_key_blob_t; + +/** + * Formats for key import and export. At present, only asymmetric key import/export is supported. + * In the future this list will expand greatly to accommodate asymmetric key import/export. + */ +typedef enum { + KM_KEY_FORMAT_X509 = 0, /* for public key export */ + KM_KEY_FORMAT_PKCS8 = 1, /* for asymmetric key pair import */ + KM_KEY_FORMAT_RAW = 3, /* for symmetric key import */ +} keymaster_key_format_t; + +/** + * The keymaster operation API consists of begin, update, finish and abort. This is the type of the + * handle used to tie the sequence of calls together. A 64-bit value is used because it's important + * that handles not be predictable. Implementations must use strong random numbers for handle + * values. + */ +typedef uint64_t keymaster_operation_handle_t; + +typedef enum { + KM_ERROR_OK = 0, + KM_ERROR_ROOT_OF_TRUST_ALREADY_SET = -1, + KM_ERROR_UNSUPPORTED_PURPOSE = -2, + KM_ERROR_INCOMPATIBLE_PURPOSE = -3, + KM_ERROR_UNSUPPORTED_ALGORITHM = -4, + KM_ERROR_INCOMPATIBLE_ALGORITHM = -5, + KM_ERROR_UNSUPPORTED_KEY_SIZE = -6, + KM_ERROR_UNSUPPORTED_BLOCK_MODE = -7, + KM_ERROR_INCOMPATIBLE_BLOCK_MODE = -8, + KM_ERROR_UNSUPPORTED_MAC_LENGTH = -9, + KM_ERROR_UNSUPPORTED_PADDING_MODE = -10, + KM_ERROR_INCOMPATIBLE_PADDING_MODE = -11, + KM_ERROR_UNSUPPORTED_DIGEST = -12, + KM_ERROR_INCOMPATIBLE_DIGEST = -13, + KM_ERROR_INVALID_EXPIRATION_TIME = -14, + KM_ERROR_INVALID_USER_ID = -15, + KM_ERROR_INVALID_AUTHORIZATION_TIMEOUT = -16, + KM_ERROR_UNSUPPORTED_KEY_FORMAT = -17, + KM_ERROR_INCOMPATIBLE_KEY_FORMAT = -18, + KM_ERROR_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM = -19, /* For PKCS8 & PKCS12 */ + KM_ERROR_UNSUPPORTED_KEY_VERIFICATION_ALGORITHM = -20, /* For PKCS8 & PKCS12 */ + KM_ERROR_INVALID_INPUT_LENGTH = -21, + KM_ERROR_KEY_EXPORT_OPTIONS_INVALID = -22, + KM_ERROR_DELEGATION_NOT_ALLOWED = -23, + KM_ERROR_KEY_NOT_YET_VALID = -24, + KM_ERROR_KEY_EXPIRED = -25, + KM_ERROR_KEY_USER_NOT_AUTHENTICATED = -26, + KM_ERROR_OUTPUT_PARAMETER_NULL = -27, + KM_ERROR_INVALID_OPERATION_HANDLE = -28, + KM_ERROR_INSUFFICIENT_BUFFER_SPACE = -29, + KM_ERROR_VERIFICATION_FAILED = -30, + KM_ERROR_TOO_MANY_OPERATIONS = -31, + KM_ERROR_UNEXPECTED_NULL_POINTER = -32, + KM_ERROR_INVALID_KEY_BLOB = -33, + KM_ERROR_IMPORTED_KEY_NOT_ENCRYPTED = -34, + KM_ERROR_IMPORTED_KEY_DECRYPTION_FAILED = -35, + KM_ERROR_IMPORTED_KEY_NOT_SIGNED = -36, + KM_ERROR_IMPORTED_KEY_VERIFICATION_FAILED = -37, + KM_ERROR_INVALID_ARGUMENT = -38, + KM_ERROR_UNSUPPORTED_TAG = -39, + KM_ERROR_INVALID_TAG = -40, + KM_ERROR_MEMORY_ALLOCATION_FAILED = -41, + KM_ERROR_IMPORT_PARAMETER_MISMATCH = -44, + KM_ERROR_SECURE_HW_ACCESS_DENIED = -45, + KM_ERROR_OPERATION_CANCELLED = -46, + KM_ERROR_CONCURRENT_ACCESS_CONFLICT = -47, + KM_ERROR_SECURE_HW_BUSY = -48, + KM_ERROR_SECURE_HW_COMMUNICATION_FAILED = -49, + KM_ERROR_UNSUPPORTED_EC_FIELD = -50, + KM_ERROR_MISSING_NONCE = -51, + KM_ERROR_INVALID_NONCE = -52, + KM_ERROR_MISSING_MAC_LENGTH = -53, + KM_ERROR_KEY_RATE_LIMIT_EXCEEDED = -54, + KM_ERROR_CALLER_NONCE_PROHIBITED = -55, + KM_ERROR_KEY_MAX_OPS_EXCEEDED = -56, + KM_ERROR_INVALID_MAC_LENGTH = -57, + KM_ERROR_MISSING_MIN_MAC_LENGTH = -58, + KM_ERROR_UNSUPPORTED_MIN_MAC_LENGTH = -59, + + KM_ERROR_UNIMPLEMENTED = -100, + KM_ERROR_VERSION_MISMATCH = -101, + + /* Additional error codes may be added by implementations, but implementers should coordinate + * with Google to avoid code collision. */ + KM_ERROR_UNKNOWN_ERROR = -1000, +} keymaster_error_t; + +/* Convenience functions for manipulating keymaster tag types */ + +static inline keymaster_tag_type_t keymaster_tag_get_type(keymaster_tag_t tag) { + return (keymaster_tag_type_t)(tag & (0xF << 28)); +} + +static inline uint32_t keymaster_tag_mask_type(keymaster_tag_t tag) { + return tag & 0x0FFFFFFF; +} + +static inline bool keymaster_tag_type_repeatable(keymaster_tag_type_t type) { + switch (type) { + case KM_UINT_REP: + case KM_ENUM_REP: + return true; + default: + return false; + } +} + +static inline bool keymaster_tag_repeatable(keymaster_tag_t tag) { + return keymaster_tag_type_repeatable(keymaster_tag_get_type(tag)); +} + +/* Convenience functions for manipulating keymaster_key_param_t structs */ + +inline keymaster_key_param_t keymaster_param_enum(keymaster_tag_t tag, uint32_t value) { + // assert(keymaster_tag_get_type(tag) == KM_ENUM || keymaster_tag_get_type(tag) == KM_ENUM_REP); + keymaster_key_param_t param; + memset(¶m, 0, sizeof(param)); + param.tag = tag; + param.enumerated = value; + return param; +} + +inline keymaster_key_param_t keymaster_param_int(keymaster_tag_t tag, uint32_t value) { + // assert(keymaster_tag_get_type(tag) == KM_INT || keymaster_tag_get_type(tag) == KM_INT_REP); + keymaster_key_param_t param; + memset(¶m, 0, sizeof(param)); + param.tag = tag; + param.integer = value; + return param; +} + +inline keymaster_key_param_t keymaster_param_long(keymaster_tag_t tag, uint64_t value) { + // assert(keymaster_tag_get_type(tag) == KM_LONG); + keymaster_key_param_t param; + memset(¶m, 0, sizeof(param)); + param.tag = tag; + param.long_integer = value; + return param; +} + +inline keymaster_key_param_t keymaster_param_blob(keymaster_tag_t tag, const uint8_t* bytes, + size_t bytes_len) { + // assert(keymaster_tag_get_type(tag) == KM_BYTES || keymaster_tag_get_type(tag) == KM_BIGNUM); + keymaster_key_param_t param; + memset(¶m, 0, sizeof(param)); + param.tag = tag; + param.blob.data = (uint8_t*)bytes; + param.blob.data_length = bytes_len; + return param; +} + +inline keymaster_key_param_t keymaster_param_bool(keymaster_tag_t tag) { + // assert(keymaster_tag_get_type(tag) == KM_BOOL); + keymaster_key_param_t param; + memset(¶m, 0, sizeof(param)); + param.tag = tag; + param.boolean = true; + return param; +} + +inline keymaster_key_param_t keymaster_param_date(keymaster_tag_t tag, uint64_t value) { + // assert(keymaster_tag_get_type(tag) == KM_DATE); + keymaster_key_param_t param; + memset(¶m, 0, sizeof(param)); + param.tag = tag; + param.date_time = value; + return param; +} + +#define KEYMASTER_SIMPLE_COMPARE(a, b) (a < b) ? -1 : ((a > b) ? 1 : 0) +inline int keymaster_param_compare(const keymaster_key_param_t* a, const keymaster_key_param_t* b) { + int retval = KEYMASTER_SIMPLE_COMPARE(a->tag, b->tag); + if (retval != 0) + return retval; + + switch (keymaster_tag_get_type(a->tag)) { + case KM_INVALID: + case KM_BOOL: + return 0; + case KM_ENUM: + case KM_ENUM_REP: + return KEYMASTER_SIMPLE_COMPARE(a->enumerated, b->enumerated); + case KM_UINT: + case KM_UINT_REP: + return KEYMASTER_SIMPLE_COMPARE(a->integer, b->integer); + case KM_ULONG: + case KM_ULONG_REP: + return KEYMASTER_SIMPLE_COMPARE(a->long_integer, b->long_integer); + case KM_DATE: + return KEYMASTER_SIMPLE_COMPARE(a->date_time, b->date_time); + case KM_BIGNUM: + case KM_BYTES: + // Handle the empty cases. + if (a->blob.data_length != 0 && b->blob.data_length == 0) + return -1; + if (a->blob.data_length == 0 && b->blob.data_length == 0) + return 0; + if (a->blob.data_length == 0 && b->blob.data_length > 0) + return 1; + + retval = memcmp(a->blob.data, b->blob.data, a->blob.data_length < b->blob.data_length + ? a->blob.data_length + : b->blob.data_length); + if (retval != 0) + return retval; + else if (a->blob.data_length != b->blob.data_length) { + // Equal up to the common length; longer one is larger. + if (a->blob.data_length < b->blob.data_length) + return -1; + if (a->blob.data_length > b->blob.data_length) + return 1; + }; + } + + return 0; +} +#undef KEYMASTER_SIMPLE_COMPARE + +inline void keymaster_free_param_values(keymaster_key_param_t* param, size_t param_count) { + while (param_count-- > 0) { + switch (keymaster_tag_get_type(param->tag)) { + case KM_BIGNUM: + case KM_BYTES: + free((void*)param->blob.data); + param->blob.data = NULL; + break; + default: + // NOP + break; + } + ++param; + } +} + +inline void keymaster_free_param_set(keymaster_key_param_set_t* set) { + if (set) { + keymaster_free_param_values(set->params, set->length); + free(set->params); + set->params = NULL; + } +} + +inline void keymaster_free_characteristics(keymaster_key_characteristics_t* characteristics) { + if (characteristics) { + keymaster_free_param_set(&characteristics->hw_enforced); + keymaster_free_param_set(&characteristics->sw_enforced); + } +} + +#ifdef __cplusplus +} // extern "C" +#endif // __cplusplus + +#endif // ANDROID_HARDWARE_KEYMASTER_DEFS_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/lights.h b/phonelibs/android_hardware_libhardware/include/hardware/lights.h new file mode 100644 index 0000000000..777c91593f --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/lights.h @@ -0,0 +1,157 @@ +/* + * 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_LIGHTS_INTERFACE_H +#define ANDROID_LIGHTS_INTERFACE_H + +#include +#include +#include + +#include + +__BEGIN_DECLS + +/** + * The id of this module + */ +#define LIGHTS_HARDWARE_MODULE_ID "lights" + +/* + * These light IDs correspond to logical lights, not physical. + * So for example, if your INDICATOR light is in line with your + * BUTTONS, it might make sense to also light the INDICATOR + * light to a reasonable color when the BUTTONS are lit. + */ +#define LIGHT_ID_BACKLIGHT "backlight" +#define LIGHT_ID_KEYBOARD "keyboard" +#define LIGHT_ID_BUTTONS "buttons" +#define LIGHT_ID_BATTERY "battery" +#define LIGHT_ID_NOTIFICATIONS "notifications" +#define LIGHT_ID_ATTENTION "attention" + +/* + * These lights aren't currently supported by the higher + * layers, but could be someday, so we have the constants + * here now. + */ +#define LIGHT_ID_BLUETOOTH "bluetooth" +#define LIGHT_ID_WIFI "wifi" + +/* + * Additional hardware-specific lights + */ +#define LIGHT_ID_CAPS "caps" +#define LIGHT_ID_FUNC "func" + +/* ************************************************************************ + * Flash modes for the flashMode field of light_state_t. + */ + +#define LIGHT_FLASH_NONE 0 + +/** + * To flash the light at a given rate, set flashMode to LIGHT_FLASH_TIMED, + * and then flashOnMS should be set to the number of milliseconds to turn + * the light on, followed by the number of milliseconds to turn the light + * off. + */ +#define LIGHT_FLASH_TIMED 1 + +/** + * To flash the light using hardware assist, set flashMode to + * the hardware mode. + */ +#define LIGHT_FLASH_HARDWARE 2 + +/** + * Light brightness is managed by a user setting. + */ +#define BRIGHTNESS_MODE_USER 0 + +/** + * Light brightness is managed by a light sensor. + */ +#define BRIGHTNESS_MODE_SENSOR 1 + +/** + * Light mode allows multiple LEDs + */ +#define LIGHT_MODE_MULTIPLE_LEDS 0x01 + +/** + * The parameters that can be set for a given light. + * + * Not all lights must support all parameters. If you + * can do something backward-compatible, you should. + */ +struct light_state_t { + /** + * The color of the LED in ARGB. + * + * Do your best here. + * - If your light can only do red or green, if they ask for blue, + * you should do green. + * - If you can only do a brightness ramp, then use this formula: + * unsigned char brightness = ((77*((color>>16)&0x00ff)) + * + (150*((color>>8)&0x00ff)) + (29*(color&0x00ff))) >> 8; + * - If you can only do on or off, 0 is off, anything else is on. + * + * The high byte should be ignored. Callers will set it to 0xff (which + * would correspond to 255 alpha). + * + * CyanogenMod: The high byte value can be implemented to control the LEDs + * Brightness from the Lights settings. The value goes from 0x01 to 0xFF. + */ + unsigned int color; + + /** + * See the LIGHT_FLASH_* constants + */ + int flashMode; + int flashOnMS; + int flashOffMS; + + /** + * Policy used by the framework to manage the light's brightness. + * Currently the values are BRIGHTNESS_MODE_USER and BRIGHTNESS_MODE_SENSOR. + */ + int brightnessMode; + + /** + * Define the LEDs modes (multiple, ...). + * See the LIGHTS_MODE_* mask constants. + */ + unsigned int ledsModes; +}; + +struct light_device_t { + struct hw_device_t common; + + /** + * Set the provided lights to the provided values. + * + * Returns: 0 on succes, error code on failure. + */ + int (*set_light)(struct light_device_t* dev, + struct light_state_t const* state); +}; + + +__END_DECLS + +#endif // ANDROID_LIGHTS_INTERFACE_H + diff --git a/phonelibs/android_hardware_libhardware/include/hardware/local_time_hal.h b/phonelibs/android_hardware_libhardware/include/hardware/local_time_hal.h new file mode 100644 index 0000000000..946e799783 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/local_time_hal.h @@ -0,0 +1,123 @@ +/* + * 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_LOCAL_TIME_HAL_INTERFACE_H +#define ANDROID_LOCAL_TIME_HAL_INTERFACE_H + +#include + +#include + +__BEGIN_DECLS + +/** + * The id of this module + */ +#define LOCAL_TIME_HARDWARE_MODULE_ID "local_time" + +/** + * Name of the local time devices to open + */ +#define LOCAL_TIME_HARDWARE_INTERFACE "local_time_hw_if" + +/**********************************************************************/ + +/** + * A structure used to collect low level sync data in a lab environment. Most + * HAL implementations will never need this structure. + */ +struct local_time_debug_event { + int64_t local_timesync_event_id; + int64_t local_time; +}; + +/** + * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM + * and the fields of this data structure must begin with hw_module_t + * followed by module specific information. + */ +struct local_time_module { + struct hw_module_t common; +}; + +struct local_time_hw_device { + /** + * Common methods of the local time hardware device. This *must* be the first member of + * local_time_hw_device as users of this structure will cast a hw_device_t to + * local_time_hw_device pointer in contexts where it's known the hw_device_t references a + * local_time_hw_device. + */ + struct hw_device_t common; + + /** + * + * Returns the current value of the system wide local time counter + */ + int64_t (*get_local_time)(struct local_time_hw_device* dev); + + /** + * + * Returns the nominal frequency (in hertz) of the system wide local time + * counter + */ + uint64_t (*get_local_freq)(struct local_time_hw_device* dev); + + /** + * + * Sets the HW slew rate of oscillator which drives the system wide local + * time counter. On success, platforms should return 0. Platforms which + * do not support HW slew should leave this method set to NULL. + * + * Valid values for rate range from MIN_INT16 to MAX_INT16. Platform + * implementations should attempt map this range linearly to the min/max + * slew rate of their hardware. + */ + int (*set_local_slew)(struct local_time_hw_device* dev, int16_t rate); + + /** + * + * A method used to collect low level sync data in a lab environments. + * Most HAL implementations will simply set this member to NULL, or return + * -EINVAL to indicate that this functionality is not supported. + * Production HALs should never support this method. + */ + int (*get_debug_log)(struct local_time_hw_device* dev, + struct local_time_debug_event* records, + int max_records); +}; + +typedef struct local_time_hw_device local_time_hw_device_t; + +/** convenience API for opening and closing a supported device */ + +static inline int local_time_hw_device_open( + const struct hw_module_t* module, + struct local_time_hw_device** device) +{ + return module->methods->open(module, LOCAL_TIME_HARDWARE_INTERFACE, + (struct hw_device_t**)device); +} + +static inline int local_time_hw_device_close(struct local_time_hw_device* device) +{ + return device->common.close(&device->common); +} + + +__END_DECLS + +#endif // ANDROID_LOCAL_TIME_INTERFACE_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/memtrack.h b/phonelibs/android_hardware_libhardware/include/hardware/memtrack.h new file mode 100644 index 0000000000..57ba4ad796 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/memtrack.h @@ -0,0 +1,160 @@ +/* + * 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_INCLUDE_HARDWARE_MEMTRACK_H +#define ANDROID_INCLUDE_HARDWARE_MEMTRACK_H + +#include +#include +#include + +#include + +__BEGIN_DECLS + +#define MEMTRACK_MODULE_API_VERSION_0_1 HARDWARE_MODULE_API_VERSION(0, 1) + +/** + * The id of this module + */ +#define MEMTRACK_HARDWARE_MODULE_ID "memtrack" + +/* + * The Memory Tracker HAL is designed to return information about device-specific + * memory usage. The primary goal is to be able to track memory that is not + * trackable in any other way, for example texture memory that is allocated by + * a process, but not mapped in to that process' address space. + * A secondary goal is to be able to categorize memory used by a process into + * GL, graphics, etc. All memory sizes should be in real memory usage, + * accounting for stride, bit depth, rounding up to page size, etc. + * + * A process collecting memory statistics will call getMemory for each + * combination of pid and memory type. For each memory type that it recognizes + * the HAL should fill out an array of memtrack_record structures breaking + * down the statistics of that memory type as much as possible. For example, + * getMemory(, MEMTRACK_TYPE_GL) might return: + * { { 4096, ACCOUNTED | PRIVATE | SYSTEM }, + * { 40960, UNACCOUNTED | PRIVATE | SYSTEM }, + * { 8192, ACCOUNTED | PRIVATE | DEDICATED }, + * { 8192, UNACCOUNTED | PRIVATE | DEDICATED } } + * If the HAL could not differentiate between SYSTEM and DEDICATED memory, it + * could return: + * { { 12288, ACCOUNTED | PRIVATE }, + * { 49152, UNACCOUNTED | PRIVATE } } + * + * Memory should not overlap between types. For example, a graphics buffer + * that has been mapped into the GPU as a surface should show up when + * MEMTRACK_TYPE_GRAPHICS is requested, and not when MEMTRACK_TYPE_GL + * is requested. + */ + +enum memtrack_type { + MEMTRACK_TYPE_OTHER = 0, + MEMTRACK_TYPE_GL = 1, + MEMTRACK_TYPE_GRAPHICS = 2, + MEMTRACK_TYPE_MULTIMEDIA = 3, + MEMTRACK_TYPE_CAMERA = 4, + MEMTRACK_NUM_TYPES, +}; + +struct memtrack_record { + size_t size_in_bytes; + unsigned int flags; +}; + +/** + * Flags to differentiate memory that can already be accounted for in + * /proc//smaps, + * (Shared_Clean + Shared_Dirty + Private_Clean + Private_Dirty = Size). + * In general, memory mapped in to a userspace process is accounted unless + * it was mapped with remap_pfn_range. + * Exactly one of these should be set. + */ +#define MEMTRACK_FLAG_SMAPS_ACCOUNTED (1 << 1) +#define MEMTRACK_FLAG_SMAPS_UNACCOUNTED (1 << 2) + +/** + * Flags to differentiate memory shared across multiple processes vs. memory + * used by a single process. Only zero or one of these may be set in a record. + * If none are set, record is assumed to count shared + private memory. + */ +#define MEMTRACK_FLAG_SHARED (1 << 3) +#define MEMTRACK_FLAG_SHARED_PSS (1 << 4) /* shared / num_procesess */ +#define MEMTRACK_FLAG_PRIVATE (1 << 5) + +/** + * Flags to differentiate memory taken from the kernel's allocation pool vs. + * memory that is dedicated to non-kernel allocations, for example a carveout + * or separate video memory. Only zero or one of these may be set in a record. + * If none are set, record is assumed to count system + dedicated memory. + */ +#define MEMTRACK_FLAG_SYSTEM (1 << 6) +#define MEMTRACK_FLAG_DEDICATED (1 << 7) + +/** + * Flags to differentiate memory accessible by the CPU in non-secure mode vs. + * memory that is protected. Only zero or one of these may be set in a record. + * If none are set, record is assumed to count secure + nonsecure memory. + */ +#define MEMTRACK_FLAG_NONSECURE (1 << 8) +#define MEMTRACK_FLAG_SECURE (1 << 9) + +/** + * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM + * and the fields of this data structure must begin with hw_module_t + * followed by module specific information. + */ +typedef struct memtrack_module { + struct hw_module_t common; + + /** + * (*init)() performs memtrack management setup actions and is called + * once before any calls to getMemory(). + * Returns 0 on success, -errno on error. + */ + int (*init)(const struct memtrack_module *module); + + /** + * (*getMemory)() expects an array of record objects and populates up to + * *num_record structures with the sizes of memory plus associated flags for + * that memory. It also updates *num_records with the total number of + * records it could return if *num_records was large enough when passed in. + * Returning records with size 0 is expected, the number of records should + * not vary between calls to getMemory for the same memory type, even + * for different pids. + * + * The caller will often call getMemory for a type and pid with + * *num_records == 0 to determine how many records to allocate room for, + * this case should be a fast-path in the HAL, returning a constant and + * not querying any kernel files. If *num_records passed in is 0, + * then records may be NULL. + * + * This function must be thread-safe, it may get called from multiple + * threads at the same time. + * + * Returns 0 on success, -ENODEV if the type is not supported, -errno + * on other errors. + */ + int (*getMemory)(const struct memtrack_module *module, + pid_t pid, + int type, + struct memtrack_record *records, + size_t *num_records); +} memtrack_module_t; + +__END_DECLS + +#endif // ANDROID_INCLUDE_HARDWARE_MEMTRACK_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/nfc.h b/phonelibs/android_hardware_libhardware/include/hardware/nfc.h new file mode 100644 index 0000000000..6002e34e83 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/nfc.h @@ -0,0 +1,302 @@ +/* + * Copyright (C) 2011, 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_NFC_HAL_INTERFACE_H +#define ANDROID_NFC_HAL_INTERFACE_H + +#include +#include +#include +#include + +#include + +__BEGIN_DECLS + + +/* NFC device HAL for NCI-based NFC controllers. + * + * This HAL allows NCI silicon vendors to make use + * of the core NCI stack in Android for their own silicon. + * + * The responibilities of the NCI HAL implementation + * are as follows: + * + * - Implement the transport to the NFC controller + * - Implement each of the HAL methods specified below as applicable to their silicon + * - Pass up received NCI messages from the controller to the stack + * + * A simplified timeline of NCI HAL method calls: + * 1) Core NCI stack calls open() + * 2) Core NCI stack executes CORE_RESET and CORE_INIT through calls to write() + * 3) Core NCI stack calls core_initialized() to allow HAL to do post-init configuration + * 4) Core NCI stack calls pre_discover() to allow HAL to prepare for RF discovery + * 5) Core NCI stack starts discovery through calls to write() + * 6) Core NCI stack stops discovery through calls to write() (e.g. screen turns off) + * 7) Core NCI stack calls pre_discover() to prepare for RF discovery (e.g. screen turned back on) + * 8) Core NCI stack starts discovery through calls to write() + * ... + * ... + * 9) Core NCI stack calls close() + */ +#define NFC_NCI_HARDWARE_MODULE_ID "nfc_nci" +#define NFC_NCI_BCM2079X_HARDWARE_MODULE_ID "nfc_nci.bcm2079x" +#define NFC_NCI_NXP_PN54X_HARDWARE_MODULE_ID "nfc_nci.pn54x" +#define NFC_NCI_CONTROLLER "nci" + +/* + * nfc_nci_module_t should contain module-specific parameters + */ +typedef struct nfc_nci_module_t { + /** + * Common methods of the NFC NCI module. This *must* be the first member of + * nfc_nci_module_t as users of this structure will cast a hw_module_t to + * nfc_nci_module_t pointer in contexts where it's known the hw_module_t references a + * nfc_nci_module_t. + */ + struct hw_module_t common; +} nfc_nci_module_t; + +/* + * HAL events that can be passed back to the stack + */ +typedef uint8_t nfc_event_t; + +enum { + HAL_NFC_OPEN_CPLT_EVT = 0x00, + HAL_NFC_CLOSE_CPLT_EVT = 0x01, + HAL_NFC_POST_INIT_CPLT_EVT = 0x02, + HAL_NFC_PRE_DISCOVER_CPLT_EVT = 0x03, + HAL_NFC_REQUEST_CONTROL_EVT = 0x04, + HAL_NFC_RELEASE_CONTROL_EVT = 0x05, + HAL_NFC_ERROR_EVT = 0x06 +}; + +/* + * Allowed status return values for each of the HAL methods + */ +typedef uint8_t nfc_status_t; + +enum { + HAL_NFC_STATUS_OK = 0x00, + HAL_NFC_STATUS_FAILED = 0x01, + HAL_NFC_STATUS_ERR_TRANSPORT = 0x02, + HAL_NFC_STATUS_ERR_CMD_TIMEOUT = 0x03, + HAL_NFC_STATUS_REFUSED = 0x04 +}; + +/* + * The callback passed in from the NFC stack that the HAL + * can use to pass events back to the stack. + */ +typedef void (nfc_stack_callback_t) (nfc_event_t event, nfc_status_t event_status); + +/* + * The callback passed in from the NFC stack that the HAL + * can use to pass incomming data to the stack. + */ +typedef void (nfc_stack_data_callback_t) (uint16_t data_len, uint8_t* p_data); + +/* nfc_nci_device_t starts with a hw_device_t struct, + * followed by device-specific methods and members. + * + * All methods in the NCI HAL are asynchronous. + */ +typedef struct nfc_nci_device { + /** + * Common methods of the NFC NCI device. This *must* be the first member of + * nfc_nci_device_t as users of this structure will cast a hw_device_t to + * nfc_nci_device_t pointer in contexts where it's known the hw_device_t references a + * nfc_nci_device_t. + */ + struct hw_device_t common; + /* + * (*open)() Opens the NFC controller device and performs initialization. + * This may include patch download and other vendor-specific initialization. + * + * If open completes successfully, the controller should be ready to perform + * NCI initialization - ie accept CORE_RESET and subsequent commands through + * the write() call. + * + * If open() returns 0, the NCI stack will wait for a HAL_NFC_OPEN_CPLT_EVT + * before continuing. + * + * If open() returns any other value, the NCI stack will stop. + * + */ + int (*open)(const struct nfc_nci_device *p_dev, nfc_stack_callback_t *p_cback, + nfc_stack_data_callback_t *p_data_cback); + + /* + * (*write)() Performs an NCI write. + * + * This method may queue writes and return immediately. The only + * requirement is that the writes are executed in order. + */ + int (*write)(const struct nfc_nci_device *p_dev, uint16_t data_len, const uint8_t *p_data); + + /* + * (*core_initialized)() is called after the CORE_INIT_RSP is received from the NFCC. + * At this time, the HAL can do any chip-specific configuration. + * + * If core_initialized() returns 0, the NCI stack will wait for a HAL_NFC_POST_INIT_CPLT_EVT + * before continuing. + * + * If core_initialized() returns any other value, the NCI stack will continue + * immediately. + */ + int (*core_initialized)(const struct nfc_nci_device *p_dev, uint8_t* p_core_init_rsp_params); + + /* + * (*pre_discover)() Is called every time before starting RF discovery. + * It is a good place to do vendor-specific configuration that must be + * performed every time RF discovery is about to be started. + * + * If pre_discover() returns 0, the NCI stack will wait for a HAL_NFC_PRE_DISCOVER_CPLT_EVT + * before continuing. + * + * If pre_discover() returns any other value, the NCI stack will start + * RF discovery immediately. + */ + int (*pre_discover)(const struct nfc_nci_device *p_dev); + + /* + * (*close)() Closed the NFC controller. Should free all resources. + */ + int (*close)(const struct nfc_nci_device *p_dev); + + /* + * (*control_granted)() Grant HAL the exclusive control to send NCI commands. + * Called in response to HAL_REQUEST_CONTROL_EVT. + * Must only be called when there are no NCI commands pending. + * HAL_RELEASE_CONTROL_EVT will notify when HAL no longer needs exclusive control. + */ + int (*control_granted)(const struct nfc_nci_device *p_dev); + + /* + * (*power_cycle)() Restart controller by power cyle; + * HAL_OPEN_CPLT_EVT will notify when operation is complete. + */ + int (*power_cycle)(const struct nfc_nci_device *p_dev); +} nfc_nci_device_t; + +/* + * Convenience methods that the NFC stack can use to open + * and close an NCI device + */ +static inline int nfc_nci_open(const struct hw_module_t* module, + nfc_nci_device_t** dev) { + return module->methods->open(module, NFC_NCI_CONTROLLER, + (struct hw_device_t**) dev); +} + +static inline int nfc_nci_close(nfc_nci_device_t* dev) { + return dev->common.close(&dev->common); +} +/* + * End NFC NCI HAL + */ + +/* + * This is a limited NFC HAL for NXP PN544-based devices. + * This HAL as Android is moving to + * an NCI-based NFC stack. + * + * All NCI-based NFC controllers should use the NFC-NCI + * HAL instead. + * Begin PN544 specific HAL + */ +#define NFC_HARDWARE_MODULE_ID "nfc" + +#define NFC_PN544_CONTROLLER "pn544" + +typedef struct nfc_module_t { + /** + * Common methods of the NFC NXP PN544 module. This *must* be the first member of + * nfc_module_t as users of this structure will cast a hw_module_t to + * nfc_module_t pointer in contexts where it's known the hw_module_t references a + * nfc_module_t. + */ + struct hw_module_t common; +} nfc_module_t; + +/* + * PN544 linktypes. + * UART + * I2C + * USB (uses UART DAL) + */ +typedef enum { + PN544_LINK_TYPE_UART, + PN544_LINK_TYPE_I2C, + PN544_LINK_TYPE_USB, + PN544_LINK_TYPE_INVALID, +} nfc_pn544_linktype; + +typedef struct { + /** + * Common methods of the NFC NXP PN544 device. This *must* be the first member of + * nfc_pn544_device_t as users of this structure will cast a hw_device_t to + * nfc_pn544_device_t pointer in contexts where it's known the hw_device_t references a + * nfc_pn544_device_t. + */ + struct hw_device_t common; + + /* The number of EEPROM registers to write */ + uint32_t num_eeprom_settings; + + /* The actual EEPROM settings + * For PN544, each EEPROM setting is a 4-byte entry, + * of the format [0x00, addr_msb, addr_lsb, value]. + */ + uint8_t* eeprom_settings; + + /* The link type to which the PN544 is connected */ + nfc_pn544_linktype linktype; + + /* The device node to which the PN544 is connected */ + const char* device_node; + + /* On Crespo we had an I2C issue that would cause us to sometimes read + * the I2C slave address (0x57) over the bus. libnfc contains + * a hack to ignore this byte and try to read the length byte + * again. + * Set to 0 to disable the workaround, 1 to enable it. + */ + uint8_t enable_i2c_workaround; + /* I2C slave address. Multiple I2C addresses are + * possible for PN544 module. Configure address according to + * board design. + */ + uint8_t i2c_device_address; +} nfc_pn544_device_t; + +static inline int nfc_pn544_open(const struct hw_module_t* module, + nfc_pn544_device_t** dev) { + return module->methods->open(module, NFC_PN544_CONTROLLER, + (struct hw_device_t**) dev); +} + +static inline int nfc_pn544_close(nfc_pn544_device_t* dev) { + return dev->common.close(&dev->common); +} +/* + * End PN544 specific HAL + */ + +__END_DECLS + +#endif // ANDROID_NFC_HAL_INTERFACE_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/nfc_tag.h b/phonelibs/android_hardware_libhardware/include/hardware/nfc_tag.h new file mode 100644 index 0000000000..040a07d8cb --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/nfc_tag.h @@ -0,0 +1,95 @@ +/* + * 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_NFC_TAG_HAL_INTERFACE_H +#define ANDROID_NFC_TAG_HAL_INTERFACE_H + +#include + +#include + +__BEGIN_DECLS + +/* + * HAL for programmable NFC tags. + * + */ + +#define NFC_TAG_HARDWARE_MODULE_ID "nfc_tag" +#define NFC_TAG_ID "tag" + +typedef struct nfc_tag_module_t { + /** + * Common methods of the NFC tag module. This *must* be the first member of + * nfc_tag_module_t as users of this structure will cast a hw_module_t to + * nfc_tag_module_t pointer in contexts where it's known the hw_module_t references a + * nfc_tag_module_t. + */ + struct hw_module_t common; +} nfc_tag_module_t; + +typedef struct nfc_tag_device { + /** + * Common methods of the NFC tag device. This *must* be the first member of + * nfc_tag_device_t as users of this structure will cast a hw_device_t to + * nfc_tag_device_t pointer in contexts where it's known the hw_device_t references a + * nfc_tag_device_t. + */ + struct hw_device_t common; + + /** + * Initialize the NFC tag. + * + * The driver must: + * * Set the static lock bytes to read only + * * Configure the Capability Container to disable write acess + * eg: 0xE1 0x10 0x0F + * + * This function is called once before any calls to setContent(). + * + * Return 0 on success or -errno on error. + */ + int (*init)(const struct nfc_tag_device *dev); + + /** + * Set the NFC tag content. + * + * The driver must write in the data area of the tag starting at + * byte 0 of block 4 and zero the rest of the data area. + * + * Returns 0 on success or -errno on error. + */ + int (*setContent)(const struct nfc_tag_device *dev, const uint8_t *data, size_t len); + + /** + * Returns the memory size of the data area. + */ + int (*getMemorySize)(const struct nfc_tag_device *dev); +} nfc_tag_device_t; + +static inline int nfc_tag_open(const struct hw_module_t* module, + nfc_tag_device_t** dev) { + return module->methods->open(module, NFC_TAG_ID, + (struct hw_device_t**)dev); +} + +static inline int nfc_tag_close(nfc_tag_device_t* dev) { + return dev->common.close(&dev->common); +} + +__END_DECLS + +#endif // ANDROID_NFC_TAG_HAL_INTERFACE_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/power.h b/phonelibs/android_hardware_libhardware/include/hardware/power.h new file mode 100644 index 0000000000..2eb98fe966 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/power.h @@ -0,0 +1,184 @@ +/* + * 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_INCLUDE_HARDWARE_POWER_H +#define ANDROID_INCLUDE_HARDWARE_POWER_H + +#include +#include +#include + +#include + +__BEGIN_DECLS + +#define POWER_MODULE_API_VERSION_0_1 HARDWARE_MODULE_API_VERSION(0, 1) +#define POWER_MODULE_API_VERSION_0_2 HARDWARE_MODULE_API_VERSION(0, 2) +#define POWER_MODULE_API_VERSION_0_3 HARDWARE_MODULE_API_VERSION(0, 3) + +/** + * The id of this module + */ +#define POWER_HARDWARE_MODULE_ID "power" + +/* + * Power hint identifiers passed to (*powerHint) + */ + +typedef enum { + POWER_HINT_VSYNC = 0x00000001, + POWER_HINT_INTERACTION = 0x00000002, + /* DO NOT USE POWER_HINT_VIDEO_ENCODE/_DECODE! They will be removed in + * KLP. + */ + POWER_HINT_VIDEO_ENCODE = 0x00000003, + POWER_HINT_VIDEO_DECODE = 0x00000004, + POWER_HINT_LOW_POWER = 0x00000005, + POWER_HINT_CAM_PREVIEW = 0x00000006, + + POWER_HINT_CPU_BOOST = 0x00000010, + POWER_HINT_LAUNCH_BOOST = 0x00000011, + POWER_HINT_AUDIO = 0x00000020, + POWER_HINT_SET_PROFILE = 0x00000030 + +} power_hint_t; + +typedef enum { + POWER_FEATURE_DOUBLE_TAP_TO_WAKE = 0x00000001, + POWER_FEATURE_SUPPORTED_PROFILES = 0x00001000 +} feature_t; + +/** + * Process info, passed as an opaque handle when + * using POWER_HINT_LAUNCH_BOOST. + */ +typedef struct launch_boost_info { + pid_t pid; + const char* packageName; +} launch_boost_info_t; + +/** + * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM + * and the fields of this data structure must begin with hw_module_t + * followed by module specific information. + */ +typedef struct power_module { + struct hw_module_t common; + + /* + * (*init)() performs power management setup actions at runtime + * startup, such as to set default cpufreq parameters. This is + * called only by the Power HAL instance loaded by + * PowerManagerService. + */ + void (*init)(struct power_module *module); + + /* + * (*setInteractive)() performs power management actions upon the + * system entering interactive state (that is, the system is awake + * and ready for interaction, often with UI devices such as + * display and touchscreen enabled) or non-interactive state (the + * system appears asleep, display usually turned off). The + * non-interactive state is usually entered after a period of + * inactivity, in order to conserve battery power during + * such inactive periods. + * + * Typical actions are to turn on or off devices and adjust + * cpufreq parameters. This function may also call the + * appropriate interfaces to allow the kernel to suspend the + * system to low-power sleep state when entering non-interactive + * state, and to disallow low-power suspend when the system is in + * interactive state. When low-power suspend state is allowed, the + * kernel may suspend the system whenever no wakelocks are held. + * + * on is non-zero when the system is transitioning to an + * interactive / awake state, and zero when transitioning to a + * non-interactive / asleep state. + * + * This function is called to enter non-interactive state after + * turning off the screen (if present), and called to enter + * interactive state prior to turning on the screen. + */ + void (*setInteractive)(struct power_module *module, int on); + + /* + * (*powerHint) is called to pass hints on power requirements, which + * may result in adjustment of power/performance parameters of the + * cpufreq governor and other controls. The possible hints are: + * + * POWER_HINT_VSYNC + * + * Foreground app has started or stopped requesting a VSYNC pulse + * from SurfaceFlinger. If the app has started requesting VSYNC + * then CPU and GPU load is expected soon, and it may be appropriate + * to raise speeds of CPU, memory bus, etc. The data parameter is + * non-zero to indicate VSYNC pulse is now requested, or zero for + * VSYNC pulse no longer requested. + * + * POWER_HINT_INTERACTION + * + * User is interacting with the device, for example, touchscreen + * events are incoming. CPU and GPU load may be expected soon, + * and it may be appropriate to raise speeds of CPU, memory bus, + * etc. The data parameter is the estimated length of the interaction + * in milliseconds, or 0 if unknown. + * + * POWER_HINT_LOW_POWER + * + * Low power mode is activated or deactivated. Low power mode + * is intended to save battery at the cost of performance. The data + * parameter is non-zero when low power mode is activated, and zero + * when deactivated. + * + * POWER_HINT_CPU_BOOST + * + * An operation is happening where it would be ideal for the CPU to + * be boosted for a specific duration. The data parameter is an + * integer value of the boost duration in microseconds. + * + * A particular platform may choose to ignore any hint. + * + * availability: version 0.2 + * + */ + void (*powerHint)(struct power_module *module, power_hint_t hint, + void *data); + + /* + * (*setFeature) is called to turn on or off a particular feature + * depending on the state parameter. The possible features are: + * + * FEATURE_DOUBLE_TAP_TO_WAKE + * + * Enabling/Disabling this feature will allow/disallow the system + * to wake up by tapping the screen twice. + * + * availability: version 0.3 + * + */ + void (*setFeature)(struct power_module *module, feature_t feature, int state); + + /* + * (*getFeature) is called to get the current value of a particular + * feature or capability from the hardware or PowerHAL + */ + int (*getFeature)(struct power_module *module, feature_t feature); + +} power_module_t; + +__END_DECLS + +#endif // ANDROID_INCLUDE_HARDWARE_POWER_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/qemu_pipe.h b/phonelibs/android_hardware_libhardware/include/hardware/qemu_pipe.h new file mode 100644 index 0000000000..53aec97a08 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/qemu_pipe.h @@ -0,0 +1,94 @@ +/* + * 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_INCLUDE_HARDWARE_QEMU_PIPE_H +#define ANDROID_INCLUDE_HARDWARE_QEMU_PIPE_H + +#include +#include +#include +#include +#include /* for pthread_once() */ +#include +#include +#include +#include + +#ifndef D +# define D(...) do{}while(0) +#endif + +/* Try to open a new Qemu fast-pipe. This function returns a file descriptor + * that can be used to communicate with a named service managed by the + * emulator. + * + * This file descriptor can be used as a standard pipe/socket descriptor. + * + * 'pipeName' is the name of the emulator service you want to connect to. + * E.g. 'opengles' or 'camera'. + * + * On success, return a valid file descriptor + * Returns -1 on error, and errno gives the error code, e.g.: + * + * EINVAL -> unknown/unsupported pipeName + * ENOSYS -> fast pipes not available in this system. + * + * ENOSYS should never happen, except if you're trying to run within a + * misconfigured emulator. + * + * You should be able to open several pipes to the same pipe service, + * except for a few special cases (e.g. GSM modem), where EBUSY will be + * returned if more than one client tries to connect to it. + */ +static __inline__ int +qemu_pipe_open(const char* pipeName) +{ + char buff[256]; + int buffLen; + int fd, ret; + + if (pipeName == NULL || pipeName[0] == '\0') { + errno = EINVAL; + return -1; + } + + snprintf(buff, sizeof buff, "pipe:%s", pipeName); + + fd = open("/dev/qemu_pipe", O_RDWR); + if (fd < 0 && errno == ENOENT) + fd = open("/dev/goldfish_pipe", O_RDWR); + if (fd < 0) { + D("%s: Could not open /dev/qemu_pipe: %s", __FUNCTION__, strerror(errno)); + //errno = ENOSYS; + return -1; + } + + buffLen = strlen(buff); + + ret = TEMP_FAILURE_RETRY(write(fd, buff, buffLen+1)); + if (ret != buffLen+1) { + D("%s: Could not connect to %s pipe service: %s", __FUNCTION__, pipeName, strerror(errno)); + if (ret == 0) { + errno = ECONNRESET; + } else if (ret > 0) { + errno = EINVAL; + } + return -1; + } + + return fd; +} + +#endif /* ANDROID_INCLUDE_HARDWARE_QEMUD_PIPE_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/qemud.h b/phonelibs/android_hardware_libhardware/include/hardware/qemud.h new file mode 100644 index 0000000000..5c39f9c939 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/qemud.h @@ -0,0 +1,153 @@ +/* + * 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_INCLUDE_HARDWARE_QEMUD_H +#define ANDROID_INCLUDE_HARDWARE_QEMUD_H + +#include +#include "qemu_pipe.h" + +/* the following is helper code that is used by the QEMU-specific + * hardware HAL modules to communicate with the emulator program + * through the 'qemud' multiplexing daemon, or through the qemud + * pipe. + * + * see the documentation comments for details in + * development/emulator/qemud/qemud.c + * + * all definitions here are built into the HAL module to avoid + * having to write a tiny shared library for this. + */ + +/* we expect the D macro to be defined to a function macro + * that sends its formatted string argument(s) to the log. + * If not, ignore the traces. + */ +#ifndef D +# define D(...) ((void)0) +#endif + +static __inline__ int +qemud_fd_write(int fd, const void* buff, int len) +{ + int len2; + do { + len2 = write(fd, buff, len); + } while (len2 < 0 && errno == EINTR); + return len2; +} + +static __inline__ int +qemud_fd_read(int fd, void* buff, int len) +{ + int len2; + do { + len2 = read(fd, buff, len); + } while (len2 < 0 && errno == EINTR); + return len2; +} + +static __inline__ int +qemud_channel_open(const char* name) +{ + int fd; + int namelen = strlen(name); + char answer[2]; + char pipe_name[256]; + + /* First, try to connect to the pipe. */ + snprintf(pipe_name, sizeof(pipe_name), "qemud:%s", name); + fd = qemu_pipe_open(pipe_name); + if (fd < 0) { + D("QEMUD pipe is not available for %s: %s", name, strerror(errno)); + /* If pipe is not available, connect to qemud control socket */ + fd = socket_local_client( "qemud", + ANDROID_SOCKET_NAMESPACE_RESERVED, + SOCK_STREAM ); + if (fd < 0) { + D("no qemud control socket: %s", strerror(errno)); + return -1; + } + + /* send service name to connect */ + if (qemud_fd_write(fd, name, namelen) != namelen) { + D("can't send service name to qemud: %s", + strerror(errno)); + close(fd); + return -1; + } + + /* read answer from daemon */ + if (qemud_fd_read(fd, answer, 2) != 2 || + answer[0] != 'O' || answer[1] != 'K') { + D("cant' connect to %s service through qemud", name); + close(fd); + return -1; + } + } + return fd; +} + +static __inline__ int +qemud_channel_send(int fd, const void* msg, int msglen) +{ + char header[5]; + + if (msglen < 0) + msglen = strlen((const char*)msg); + + if (msglen == 0) + return 0; + + snprintf(header, sizeof header, "%04x", msglen); + if (qemud_fd_write(fd, header, 4) != 4) { + D("can't write qemud frame header: %s", strerror(errno)); + return -1; + } + + if (qemud_fd_write(fd, msg, msglen) != msglen) { + D("can4t write qemud frame payload: %s", strerror(errno)); + return -1; + } + return 0; +} + +static __inline__ int +qemud_channel_recv(int fd, void* msg, int msgsize) +{ + char header[5]; + int size, avail; + + if (qemud_fd_read(fd, header, 4) != 4) { + D("can't read qemud frame header: %s", strerror(errno)); + return -1; + } + header[4] = 0; + if (sscanf(header, "%04x", &size) != 1) { + D("malformed qemud frame header: '%.*s'", 4, header); + return -1; + } + if (size > msgsize) + return -1; + + if (qemud_fd_read(fd, msg, size) != size) { + D("can't read qemud frame payload: %s", strerror(errno)); + return -1; + } + return size; +} + +#endif /* ANDROID_INCLUDE_HARDWARE_QEMUD_H */ diff --git a/phonelibs/android_hardware_libhardware/include/hardware/radio.h b/phonelibs/android_hardware_libhardware/include/hardware/radio.h new file mode 100644 index 0000000000..145deb5737 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/radio.h @@ -0,0 +1,298 @@ +/* + * 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. + */ + +#include +#include + +#ifndef ANDROID_RADIO_HAL_H +#define ANDROID_RADIO_HAL_H + + +__BEGIN_DECLS + +/** + * The id of this module + */ +#define RADIO_HARDWARE_MODULE_ID "radio" + +/** + * Name of the audio devices to open + */ +#define RADIO_HARDWARE_DEVICE "radio_hw_device" + +#define RADIO_MODULE_API_VERSION_1_0 HARDWARE_MODULE_API_VERSION(1, 0) +#define RADIO_MODULE_API_VERSION_CURRENT RADIO_MODULE_API_VERSION_1_0 + + +#define RADIO_DEVICE_API_VERSION_1_0 HARDWARE_DEVICE_API_VERSION(1, 0) +#define RADIO_DEVICE_API_VERSION_CURRENT RADIO_DEVICE_API_VERSION_1_0 + +/** + * List of known radio HAL modules. This is the base name of the radio HAL + * library composed of the "radio." prefix, one of the base names below and + * a suffix specific to the device. + * E.g: radio.fm.default.so + */ + +#define RADIO_HARDWARE_MODULE_ID_FM "fm" /* corresponds to RADIO_CLASS_AM_FM */ +#define RADIO_HARDWARE_MODULE_ID_SAT "sat" /* corresponds to RADIO_CLASS_SAT */ +#define RADIO_HARDWARE_MODULE_ID_DT "dt" /* corresponds to RADIO_CLASS_DT */ + + +/** + * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM + * and the fields of this data structure must begin with hw_module_t + * followed by module specific information. + */ +struct radio_module { + struct hw_module_t common; +}; + +/* + * Callback function called by the HAL when one of the following occurs: + * - event RADIO_EVENT_HW_FAILURE: radio chip of driver failure requiring + * closing and reopening of the tuner interface. + * - event RADIO_EVENT_CONFIG: new configuration applied in response to open_tuner(), + * or set_configuration(). The event status is 0 (no error) if the configuration has been applied, + * -EINVAL is not or -ETIMEDOUT in case of time out. + * - event RADIO_EVENT_TUNED: tune locked on new station/frequency following scan(), + * step(), tune() or auto AF switching. The event status is 0 (no error) if in tune, + * -EINVAL is not tuned and data in radio_program_info is not valid or -ETIMEDOUT if scan() + * timed out. + * - event RADIO_EVENT_TA: at the beginning and end of traffic announcement if current + * configuration enables TA. + * - event RADIO_EVENT_AF: after automatic switching to alternate frequency if current + * configuration enables AF switching. + * - event RADIO_EVENT_ANTENNA: when the antenna is connected or disconnected. + * - event RADIO_EVENT_METADATA: when new meta data are received from the tuned station. + * The callback MUST NOT be called synchronously while executing a HAL function but from + * a separate thread. + */ +typedef void (*radio_callback_t)(radio_hal_event_t *event, void *cookie); + +/* control interface for a radio tuner */ +struct radio_tuner { + /* + * Apply current radio band configuration (band, range, channel spacing ...). + * + * arguments: + * - config: the band configuration to apply + * + * returns: + * 0 if configuration could be applied + * -EINVAL if configuration requested is invalid + * + * Automatically cancels pending scan, step or tune. + * + * Callback function with event RADIO_EVENT_CONFIG MUST be called once the + * configuration is applied or a failure occurs or after a time out. + */ + int (*set_configuration)(const struct radio_tuner *tuner, + const radio_hal_band_config_t *config); + + /* + * Retrieve current radio band configuration. + * + * arguments: + * - config: where to return the band configuration + * + * returns: + * 0 if valid configuration is returned + * -EINVAL if invalid arguments are passed + */ + int (*get_configuration)(const struct radio_tuner *tuner, + radio_hal_band_config_t *config); + + /* + * Start scanning up to next valid station. + * Must be called when a valid configuration has been applied. + * + * arguments: + * - direction: RADIO_DIRECTION_UP or RADIO_DIRECTION_DOWN + * - skip_sub_channel: valid for HD radio or digital radios only: ignore sub channels + * (e.g SPS for HD radio). + * + * returns: + * 0 if scan successfully started + * -ENOSYS if called out of sequence + * -ENODEV if another error occurs + * + * Automatically cancels pending scan, step or tune. + * + * Callback function with event RADIO_EVENT_TUNED MUST be called once + * locked on a station or after a time out or full frequency scan if + * no station found. The event status should indicate if a valid station + * is tuned or not. + */ + int (*scan)(const struct radio_tuner *tuner, + radio_direction_t direction, bool skip_sub_channel); + + /* + * Move one channel spacing up or down. + * Must be called when a valid configuration has been applied. + * + * arguments: + * - direction: RADIO_DIRECTION_UP or RADIO_DIRECTION_DOWN + * - skip_sub_channel: valid for HD radio or digital radios only: ignore sub channels + * (e.g SPS for HD radio). + * + * returns: + * 0 if step successfully started + * -ENOSYS if called out of sequence + * -ENODEV if another error occurs + * + * Automatically cancels pending scan, step or tune. + * + * Callback function with event RADIO_EVENT_TUNED MUST be called once + * step completed or after a time out. The event status should indicate + * if a valid station is tuned or not. + */ + int (*step)(const struct radio_tuner *tuner, + radio_direction_t direction, bool skip_sub_channel); + + /* + * Tune to specified frequency. + * Must be called when a valid configuration has been applied. + * + * arguments: + * - channel: channel to tune to. A frequency in kHz for AM/FM/HD Radio bands. + * - sub_channel: valid for HD radio or digital radios only: (e.g SPS number for HD radio). + * + * returns: + * 0 if tune successfully started + * -ENOSYS if called out of sequence + * -EINVAL if invalid arguments are passed + * -ENODEV if another error occurs + * + * Automatically cancels pending scan, step or tune. + * + * Callback function with event RADIO_EVENT_TUNED MUST be called once + * tuned or after a time out. The event status should indicate + * if a valid station is tuned or not. + */ + int (*tune)(const struct radio_tuner *tuner, + unsigned int channel, unsigned int sub_channel); + + /* + * Cancel a scan, step or tune operation. + * Must be called while a scan, step or tune operation is pending + * (callback not yet sent). + * + * returns: + * 0 if successful + * -ENOSYS if called out of sequence + * -ENODEV if another error occurs + * + * The callback is not sent. + */ + int (*cancel)(const struct radio_tuner *tuner); + + /* + * Retrieve current station information. + * + * arguments: + * - info: where to return the program info. + * If info->metadata is NULL. no meta data should be returned. + * If meta data must be returned, they should be added to or cloned to + * info->metadata, not passed from a newly created meta data buffer. + * + * returns: + * 0 if tuned and information available + * -EINVAL if invalid arguments are passed + * -ENODEV if another error occurs + */ + int (*get_program_information)(const struct radio_tuner *tuner, + radio_program_info_t *info); +}; + +struct radio_hw_device { + struct hw_device_t common; + + /* + * Retrieve implementation properties. + * + * arguments: + * - properties: where to return the module properties + * + * returns: + * 0 if no error + * -EINVAL if invalid arguments are passed + */ + int (*get_properties)(const struct radio_hw_device *dev, + radio_hal_properties_t *properties); + + /* + * Open a tuner interface for the requested configuration. + * If no other tuner is opened, this will activate the radio module. + * + * arguments: + * - config: the band configuration to apply + * - audio: this tuner will be used for live radio listening and should be connected to + * the radio audio source. + * - callback: the event callback + * - cookie: the cookie to pass when calling the callback + * - tuner: where to return the tuner interface + * + * returns: + * 0 if HW was powered up and configuration could be applied + * -EINVAL if configuration requested is invalid + * -ENOSYS if called out of sequence + * + * Callback function with event RADIO_EVENT_CONFIG MUST be called once the + * configuration is applied or a failure occurs or after a time out. + */ + int (*open_tuner)(const struct radio_hw_device *dev, + const radio_hal_band_config_t *config, + bool audio, + radio_callback_t callback, + void *cookie, + const struct radio_tuner **tuner); + + /* + * Close a tuner interface. + * If the last tuner is closed, the radio module is deactivated. + * + * arguments: + * - tuner: the tuner interface to close + * + * returns: + * 0 if powered down successfully. + * -EINVAL if an invalid argument is passed + * -ENOSYS if called out of sequence + */ + int (*close_tuner)(const struct radio_hw_device *dev, const struct radio_tuner *tuner); + +}; + +typedef struct radio_hw_device radio_hw_device_t; + +/** convenience API for opening and closing a supported device */ + +static inline int radio_hw_device_open(const struct hw_module_t* module, + struct radio_hw_device** device) +{ + return module->methods->open(module, RADIO_HARDWARE_DEVICE, + (struct hw_device_t**)device); +} + +static inline int radio_hw_device_close(const struct radio_hw_device* device) +{ + return device->common.close((struct hw_device_t *)&device->common); +} + +__END_DECLS + +#endif // ANDROID_RADIO_HAL_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/sensors.h b/phonelibs/android_hardware_libhardware/include/hardware/sensors.h new file mode 100644 index 0000000000..51bffe1196 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/sensors.h @@ -0,0 +1,1096 @@ +/* + * 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_SENSORS_INTERFACE_H +#define ANDROID_SENSORS_INTERFACE_H + +#include +#include +#include + +#include +#include + +__BEGIN_DECLS + +/*****************************************************************************/ + +#define SENSORS_HEADER_VERSION 1 +#define SENSORS_MODULE_API_VERSION_0_1 HARDWARE_MODULE_API_VERSION(0, 1) +#define SENSORS_DEVICE_API_VERSION_0_1 HARDWARE_DEVICE_API_VERSION_2(0, 1, SENSORS_HEADER_VERSION) +#define SENSORS_DEVICE_API_VERSION_1_0 HARDWARE_DEVICE_API_VERSION_2(1, 0, SENSORS_HEADER_VERSION) +#define SENSORS_DEVICE_API_VERSION_1_1 HARDWARE_DEVICE_API_VERSION_2(1, 1, SENSORS_HEADER_VERSION) +#define SENSORS_DEVICE_API_VERSION_1_2 HARDWARE_DEVICE_API_VERSION_2(1, 2, SENSORS_HEADER_VERSION) +#define SENSORS_DEVICE_API_VERSION_1_3 HARDWARE_DEVICE_API_VERSION_2(1, 3, SENSORS_HEADER_VERSION) +#define SENSORS_DEVICE_API_VERSION_1_4 HARDWARE_DEVICE_API_VERSION_2(1, 4, SENSORS_HEADER_VERSION) + +/** + * Please see the Sensors section of source.android.com for an + * introduction to and detailed descriptions of Android sensor types: + * http://source.android.com/devices/sensors/index.html + */ + +/** + * The id of this module + */ +#define SENSORS_HARDWARE_MODULE_ID "sensors" + +/** + * Name of the sensors device to open + */ +#define SENSORS_HARDWARE_POLL "poll" + +/** + * Handles must be higher than SENSORS_HANDLE_BASE and must be unique. + * A Handle identifies a given sensors. The handle is used to activate + * and/or deactivate sensors. + * In this version of the API there can only be 256 handles. + */ +#define SENSORS_HANDLE_BASE 0 +#define SENSORS_HANDLE_BITS 8 +#define SENSORS_HANDLE_COUNT (1< 35 degrees + * + * Large accelerations without a change in phone orientation should not trigger a tilt event. + * For example, a sharp turn or strong acceleration while driving a car should not trigger a tilt + * event, even though the angle of the average acceleration might vary by more than 35 degrees. + * + * Typically, this sensor is implemented with the help of only an accelerometer. Other sensors can + * be used as well if they do not increase the power consumption significantly. This is a low power + * sensor that should allow the AP to go into suspend mode. Do not emulate this sensor in the HAL. + * Like other wake up sensors, the driver is expected to a hold a wake_lock with a timeout of 200 ms + * while reporting this event. The only allowed return value is 1.0. + * + * Implement only the wake-up version of this sensor. + */ +#define SENSOR_TYPE_TILT_DETECTOR (22) +#define SENSOR_STRING_TYPE_TILT_DETECTOR "android.sensor.tilt_detector" + +/* + * SENSOR_TYPE_WAKE_GESTURE + * reporting-mode: one-shot + * + * A sensor enabling waking up the device based on a device specific motion. + * + * When this sensor triggers, the device behaves as if the power button was + * pressed, turning the screen on. This behavior (turning on the screen when + * this sensor triggers) might be deactivated by the user in the device + * settings. Changes in settings do not impact the behavior of the sensor: + * only whether the framework turns the screen on when it triggers. + * + * The actual gesture to be detected is not specified, and can be chosen by + * the manufacturer of the device. + * This sensor must be low power, as it is likely to be activated 24/7. + * The only allowed value to return is 1.0. + * + * Implement only the wake-up version of this sensor. + */ +#define SENSOR_TYPE_WAKE_GESTURE (23) +#define SENSOR_STRING_TYPE_WAKE_GESTURE "android.sensor.wake_gesture" + +/* + * SENSOR_TYPE_GLANCE_GESTURE + * reporting-mode: one-shot + * + * A sensor enabling briefly turning the screen on to enable the user to + * glance content on screen based on a specific motion. The device should + * turn the screen off after a few moments. + * + * When this sensor triggers, the device turns the screen on momentarily + * to allow the user to glance notifications or other content while the + * device remains locked in a non-interactive state (dozing). This behavior + * (briefly turning on the screen when this sensor triggers) might be deactivated + * by the user in the device settings. Changes in settings do not impact the + * behavior of the sensor: only whether the framework briefly turns the screen on + * when it triggers. + * + * The actual gesture to be detected is not specified, and can be chosen by + * the manufacturer of the device. + * This sensor must be low power, as it is likely to be activated 24/7. + * The only allowed value to return is 1.0. + * + * Implement only the wake-up version of this sensor. + */ +#define SENSOR_TYPE_GLANCE_GESTURE (24) +#define SENSOR_STRING_TYPE_GLANCE_GESTURE "android.sensor.glance_gesture" + +/** + * SENSOR_TYPE_PICK_UP_GESTURE + * reporting-mode: one-shot + * + * A sensor of this type triggers when the device is picked up regardless of wherever is was + * before (desk, pocket, bag). The only allowed return value is 1.0. + * This sensor de-activates itself immediately after it triggers. + * + * Implement only the wake-up version of this sensor. + */ +#define SENSOR_TYPE_PICK_UP_GESTURE (25) +#define SENSOR_STRING_TYPE_PICK_UP_GESTURE "android.sensor.pick_up_gesture" + +/* + * SENSOR_TYPE_WRIST_TILT_GESTURE + * trigger-mode: special + * wake-up sensor: yes + * + * A sensor of this type triggers an event each time a tilt of the wrist-worn + * device is detected. + * + * This sensor must be low power, as it is likely to be activated 24/7. + * The only allowed value to return is 1.0. + * + * Implement only the wake-up version of this sensor. + */ +#define SENSOR_TYPE_WRIST_TILT_GESTURE (26) +#define SENSOR_STRING_TYPE_WRIST_TILT_GESTURE "android.sensor.wrist_tilt_gesture" + +/** + * Values returned by the accelerometer in various locations in the universe. + * all values are in SI units (m/s^2) + */ +#define GRAVITY_SUN (275.0f) +#define GRAVITY_EARTH (9.80665f) + +/** Maximum magnetic field on Earth's surface */ +#define MAGNETIC_FIELD_EARTH_MAX (60.0f) + +/** Minimum magnetic field on Earth's surface */ +#define MAGNETIC_FIELD_EARTH_MIN (30.0f) + +/** + * Possible values of the status field of sensor events. + */ +#define SENSOR_STATUS_NO_CONTACT -1 +#define SENSOR_STATUS_UNRELIABLE 0 +#define SENSOR_STATUS_ACCURACY_LOW 1 +#define SENSOR_STATUS_ACCURACY_MEDIUM 2 +#define SENSOR_STATUS_ACCURACY_HIGH 3 + +/** + * sensor event data + */ +typedef struct { + 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]; +} sensors_vec_t; + +/** + * uncalibrated gyroscope and magnetometer event data + */ +typedef struct { + 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; + }; + }; +} uncalibrated_event_t; + +/** + * Meta data event data + */ +typedef struct meta_data_event { + int32_t what; + int32_t sensor; +} meta_data_event_t; + +/** + * Heart rate event data + */ +typedef struct { + // Heart rate in beats per minute. + // Set to 0 when status is SENSOR_STATUS_UNRELIABLE or ..._NO_CONTACT + float bpm; + // Status of the sensor for this reading. Set to one SENSOR_STATUS_... + // Note that this value should only be set for sensors that explicitly define + // the meaning of this field. This field is not piped through the framework + // for other sensors. + int8_t status; +} heart_rate_event_t; + +/** + * Union of the various types of sensor data + * that can be returned. + */ +typedef struct sensors_event_t { + /* must be sizeof(struct sensors_event_t) */ + int32_t version; + + /* sensor identifier */ + int32_t sensor; + + /* sensor type */ + int32_t type; + + /* reserved */ + int32_t reserved0; + + /* time is in nanosecond */ + int64_t timestamp; + + union { + union { + float data[16]; + + /* acceleration values are in meter per second per second (m/s^2) */ + sensors_vec_t acceleration; + + /* magnetic vector values are in micro-Tesla (uT) */ + sensors_vec_t magnetic; + + /* orientation values are in degrees */ + sensors_vec_t orientation; + + /* gyroscope values are in rad/s */ + sensors_vec_t gyro; + + /* temperature is in degrees centigrade (Celsius) */ + float temperature; + + /* distance in centimeters */ + float distance; + + /* light in SI lux units */ + float light; + + /* pressure in hectopascal (hPa) */ + float pressure; + + /* relative humidity in percent */ + float relative_humidity; + + /* uncalibrated gyroscope values are in rad/s */ + uncalibrated_event_t uncalibrated_gyro; + + /* uncalibrated magnetometer values are in micro-Teslas */ + uncalibrated_event_t uncalibrated_magnetic; + + /* heart rate data containing value in bpm and status */ + heart_rate_event_t heart_rate; + + /* this is a special event. see SENSOR_TYPE_META_DATA above. + * sensors_meta_data_event_t events are all reported with a type of + * SENSOR_TYPE_META_DATA. The handle is ignored and must be zero. + */ + meta_data_event_t meta_data; + }; + + union { + uint64_t data[8]; + + /* step-counter */ + uint64_t step_counter; + } u64; + }; + + /* Reserved flags for internal use. Set to zero. */ + uint32_t flags; + + uint32_t reserved1[3]; +} sensors_event_t; + + +/* see SENSOR_TYPE_META_DATA */ +typedef sensors_event_t sensors_meta_data_event_t; + + +struct sensor_t; + +/** + * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM + * and the fields of this data structure must begin with hw_module_t + * followed by module specific information. + */ +struct sensors_module_t { + struct hw_module_t common; + + /** + * Enumerate all available sensors. The list is returned in "list". + * @return number of sensors in the list + */ + int (*get_sensors_list)(struct sensors_module_t* module, + struct sensor_t const** list); + + /** + * Place the module in a specific mode. The following modes are defined + * + * 0 - Normal operation. Default state of the module. + * 1 - Loopback mode. Data is injected for the the supported + * sensors by the sensor service in this mode. + * @return 0 on success + * -EINVAL if requested mode is not supported + * -EPERM if operation is not allowed + */ + int (*set_operation_mode)(unsigned int mode); +}; + +struct sensor_t { + + /* Name of this sensor. + * All sensors of the same "type" must have a different "name". + */ + const char* name; + + /* vendor of the hardware part */ + const char* vendor; + + /* version of the hardware part + driver. The value of this field + * must increase when the driver is updated in a way that changes the + * output of this sensor. This is important for fused sensors when the + * fusion algorithm is updated. + */ + int version; + + /* handle that identifies this sensors. This handle is used to reference + * this sensor throughout the HAL API. + */ + int handle; + + /* this sensor's type. */ + int type; + + /* maximum range of this sensor's value in SI units */ + float maxRange; + + /* smallest difference between two values reported by this sensor */ + float resolution; + + /* rough estimate of this sensor's power consumption in mA */ + float power; + + /* this value depends on the reporting mode: + * + * continuous: minimum sample period allowed in microseconds + * on-change : 0 + * one-shot :-1 + * special : 0, unless otherwise noted + */ + int32_t minDelay; + + /* number of events reserved for this sensor in the batch mode FIFO. + * If there is a dedicated FIFO for this sensor, then this is the + * size of this FIFO. If the FIFO is shared with other sensors, + * this is the size reserved for that sensor and it can be zero. + */ + uint32_t fifoReservedEventCount; + + /* maximum number of events of this sensor that could be batched. + * This is especially relevant when the FIFO is shared between + * several sensors; this value is then set to the size of that FIFO. + */ + uint32_t fifoMaxEventCount; + + /* type of this sensor as a string. Set to corresponding + * SENSOR_STRING_TYPE_*. + * When defining an OEM specific sensor or sensor manufacturer specific + * sensor, use your reserve domain name as a prefix. + * ex: com.google.glass.onheaddetector + * For sensors of known type, the android framework might overwrite this + * string automatically. + */ + const char* stringType; + + /* permission required to see this sensor, register to it and receive data. + * Set to "" if no permission is required. Some sensor types like the + * heart rate monitor have a mandatory require_permission. + * For sensors that always require a specific permission, like the heart + * rate monitor, the android framework might overwrite this string + * automatically. + */ + const char* requiredPermission; + + /* This value is defined only for continuous mode and on-change sensors. It is the delay between + * two sensor events corresponding to the lowest frequency that this sensor supports. When lower + * frequencies are requested through batch()/setDelay() the events will be generated at this + * frequency instead. It can be used by the framework or applications to estimate when the batch + * FIFO may be full. + * + * NOTE: 1) period_ns is in nanoseconds where as maxDelay/minDelay are in microseconds. + * continuous, on-change: maximum sampling period allowed in microseconds. + * one-shot, special : 0 + * 2) maxDelay should always fit within a 32 bit signed integer. It is declared as 64 bit + * on 64 bit architectures only for binary compatibility reasons. + * Availability: SENSORS_DEVICE_API_VERSION_1_3 + */ + #ifdef __LP64__ + int64_t maxDelay; + #else + int32_t maxDelay; + #endif + + /* Flags for sensor. See SENSOR_FLAG_* above. Only the least significant 32 bits are used here. + * It is declared as 64 bit on 64 bit architectures only for binary compatibility reasons. + * Availability: SENSORS_DEVICE_API_VERSION_1_3 + */ + #ifdef __LP64__ + uint64_t flags; + #else + uint32_t flags; + #endif + + /* reserved fields, must be zero */ + void* reserved[2]; +}; + + +/* + * sensors_poll_device_t is used with SENSORS_DEVICE_API_VERSION_0_1 + * and is present for backward binary and source compatibility. + * See the Sensors HAL interface section for complete descriptions of the + * following functions: + * http://source.android.com/devices/sensors/index.html#hal + */ +struct sensors_poll_device_t { + struct hw_device_t common; + int (*activate)(struct sensors_poll_device_t *dev, + int sensor_handle, int enabled); + int (*setDelay)(struct sensors_poll_device_t *dev, + int sensor_handle, int64_t sampling_period_ns); + int (*poll)(struct sensors_poll_device_t *dev, + sensors_event_t* data, int count); +}; + +/* + * struct sensors_poll_device_1 is used in HAL versions >= SENSORS_DEVICE_API_VERSION_1_0 + */ +typedef struct sensors_poll_device_1 { + union { + /* sensors_poll_device_1 is compatible with sensors_poll_device_t, + * and can be down-cast to it + */ + struct sensors_poll_device_t v0; + + struct { + struct hw_device_t common; + + /* Activate/de-activate one sensor. Return 0 on success, negative + * + * sensor_handle is the handle of the sensor to change. + * enabled set to 1 to enable, or 0 to disable the sensor. + * + * Return 0 on success, negative errno code otherwise. + */ + int (*activate)(struct sensors_poll_device_t *dev, + int sensor_handle, int enabled); + + /** + * Set the events's period in nanoseconds for a given sensor. + * If sampling_period_ns > max_delay it will be truncated to + * max_delay and if sampling_period_ns < min_delay it will be + * replaced by min_delay. + */ + int (*setDelay)(struct sensors_poll_device_t *dev, + int sensor_handle, int64_t sampling_period_ns); + + /** + * Returns an array of sensor data. + */ + int (*poll)(struct sensors_poll_device_t *dev, + sensors_event_t* data, int count); + }; + }; + + + /* + * Sets a sensor’s parameters, including sampling frequency and maximum + * report latency. This function can be called while the sensor is + * activated, in which case it must not cause any sensor measurements to + * be lost: transitioning from one sampling rate to the other cannot cause + * lost events, nor can transitioning from a high maximum report latency to + * a low maximum report latency. + * See the Batching sensor results page for details: + * http://source.android.com/devices/sensors/batching.html + */ + int (*batch)(struct sensors_poll_device_1* dev, + int sensor_handle, int flags, int64_t sampling_period_ns, + int64_t max_report_latency_ns); + + /* + * Flush adds a META_DATA_FLUSH_COMPLETE event (sensors_event_meta_data_t) + * to the end of the "batch mode" FIFO for the specified sensor and flushes + * the FIFO. + * If the FIFO is empty or if the sensor doesn't support batching (FIFO size zero), + * it should return SUCCESS along with a trivial META_DATA_FLUSH_COMPLETE event added to the + * event stream. This applies to all sensors other than one-shot sensors. + * If the sensor is a one-shot sensor, flush must return -EINVAL and not generate + * any flush complete metadata. + * If the sensor is not active at the time flush() is called, flush() should return + * -EINVAL. + */ + int (*flush)(struct sensors_poll_device_1* dev, int sensor_handle); + + /* + * Inject a single sensor sample to be to this device. + * data points to the sensor event to be injected + * @return 0 on success + * -EPERM if operation is not allowed + * -EINVAL if sensor event cannot be injected + */ + int (*inject_sensor_data)(struct sensors_poll_device_1 *dev, const sensors_event_t *data); + + void (*reserved_procs[7])(void); + +} sensors_poll_device_1_t; + + +/** convenience API for opening and closing a device */ + +static inline int sensors_open(const struct hw_module_t* module, + struct sensors_poll_device_t** device) { + return module->methods->open(module, + SENSORS_HARDWARE_POLL, (struct hw_device_t**)device); +} + +static inline int sensors_close(struct sensors_poll_device_t* device) { + return device->common.close(&device->common); +} + +static inline int sensors_open_1(const struct hw_module_t* module, + sensors_poll_device_1_t** device) { + return module->methods->open(module, + SENSORS_HARDWARE_POLL, (struct hw_device_t**)device); +} + +static inline int sensors_close_1(sensors_poll_device_1_t* device) { + return device->common.close(&device->common); +} + +__END_DECLS + +#endif // ANDROID_SENSORS_INTERFACE_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/sound_trigger.h b/phonelibs/android_hardware_libhardware/include/hardware/sound_trigger.h new file mode 100644 index 0000000000..2a8db87caa --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/sound_trigger.h @@ -0,0 +1,130 @@ +/* + * Copyright (C) 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. + */ + +#include +#include +#include + +#ifndef ANDROID_SOUND_TRIGGER_HAL_H +#define ANDROID_SOUND_TRIGGER_HAL_H + + +__BEGIN_DECLS + +/** + * The id of this module + */ +#define SOUND_TRIGGER_HARDWARE_MODULE_ID "sound_trigger" + +/** + * Name of the audio devices to open + */ +#define SOUND_TRIGGER_HARDWARE_INTERFACE "sound_trigger_hw_if" + +#define SOUND_TRIGGER_MODULE_API_VERSION_1_0 HARDWARE_MODULE_API_VERSION(1, 0) +#define SOUND_TRIGGER_MODULE_API_VERSION_CURRENT SOUND_TRIGGER_MODULE_API_VERSION_1_0 + + +#define SOUND_TRIGGER_DEVICE_API_VERSION_1_0 HARDWARE_DEVICE_API_VERSION(1, 0) +#define SOUND_TRIGGER_DEVICE_API_VERSION_CURRENT SOUND_TRIGGER_DEVICE_API_VERSION_1_0 + +/** + * List of known sound trigger HAL modules. This is the base name of the sound_trigger HAL + * library composed of the "sound_trigger." prefix, one of the base names below and + * a suffix specific to the device. + * e.g: sondtrigger.primary.goldfish.so or sound_trigger.primary.default.so + */ + +#define SOUND_TRIGGER_HARDWARE_MODULE_ID_PRIMARY "primary" + + +/** + * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM + * and the fields of this data structure must begin with hw_module_t + * followed by module specific information. + */ +struct sound_trigger_module { + struct hw_module_t common; +}; + +typedef void (*recognition_callback_t)(struct sound_trigger_recognition_event *event, void *cookie); +typedef void (*sound_model_callback_t)(struct sound_trigger_model_event *event, void *cookie); + +struct sound_trigger_hw_device { + struct hw_device_t common; + + /* + * Retrieve implementation properties. + */ + int (*get_properties)(const struct sound_trigger_hw_device *dev, + struct sound_trigger_properties *properties); + + /* + * Load a sound model. Once loaded, recognition of this model can be started and stopped. + * Only one active recognition per model at a time. The SoundTrigger service will handle + * concurrent recognition requests by different users/applications on the same model. + * The implementation returns a unique handle used by other functions (unload_sound_model(), + * start_recognition(), etc... + */ + int (*load_sound_model)(const struct sound_trigger_hw_device *dev, + struct sound_trigger_sound_model *sound_model, + sound_model_callback_t callback, + void *cookie, + sound_model_handle_t *handle); + + /* + * Unload a sound model. A sound model can be unloaded to make room for a new one to overcome + * implementation limitations. + */ + int (*unload_sound_model)(const struct sound_trigger_hw_device *dev, + sound_model_handle_t handle); + + /* Start recognition on a given model. Only one recognition active at a time per model. + * Once recognition succeeds of fails, the callback is called. + * TODO: group recognition configuration parameters into one struct and add key phrase options. + */ + int (*start_recognition)(const struct sound_trigger_hw_device *dev, + sound_model_handle_t sound_model_handle, + const struct sound_trigger_recognition_config *config, + recognition_callback_t callback, + void *cookie); + + /* Stop recognition on a given model. + * The implementation does not have to call the callback when stopped via this method. + */ + int (*stop_recognition)(const struct sound_trigger_hw_device *dev, + sound_model_handle_t sound_model_handle); +}; + +typedef struct sound_trigger_hw_device sound_trigger_hw_device_t; + +/** convenience API for opening and closing a supported device */ + +static inline int sound_trigger_hw_device_open(const struct hw_module_t* module, + struct sound_trigger_hw_device** device) +{ + return module->methods->open(module, SOUND_TRIGGER_HARDWARE_INTERFACE, + (struct hw_device_t**)device); +} + +static inline int sound_trigger_hw_device_close(struct sound_trigger_hw_device* device) +{ + return device->common.close(&device->common); +} + +__END_DECLS + +#endif // ANDROID_SOUND_TRIGGER_HAL_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/tv_input.h b/phonelibs/android_hardware_libhardware/include/hardware/tv_input.h new file mode 100644 index 0000000000..456b06e1fd --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/tv_input.h @@ -0,0 +1,408 @@ +/* + * 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_TV_INPUT_INTERFACE_H +#define ANDROID_TV_INPUT_INTERFACE_H + +#include +#include +#include + +#include +#include +#include + +__BEGIN_DECLS + +/* + * Module versioning information for the TV input hardware module, based on + * tv_input_module_t.common.module_api_version. + * + * Version History: + * + * TV_INPUT_MODULE_API_VERSION_0_1: + * Initial TV input hardware module API. + * + */ + +#define TV_INPUT_MODULE_API_VERSION_0_1 HARDWARE_MODULE_API_VERSION(0, 1) + +#define TV_INPUT_DEVICE_API_VERSION_0_1 HARDWARE_DEVICE_API_VERSION(0, 1) + +/* + * The id of this module + */ +#define TV_INPUT_HARDWARE_MODULE_ID "tv_input" + +#define TV_INPUT_DEFAULT_DEVICE "default" + +/*****************************************************************************/ + +/* + * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM + * and the fields of this data structure must begin with hw_module_t + * followed by module specific information. + */ +typedef struct tv_input_module { + struct hw_module_t common; +} tv_input_module_t; + +/*****************************************************************************/ + +enum { + /* Generic hardware. */ + TV_INPUT_TYPE_OTHER_HARDWARE = 1, + /* Tuner. (e.g. built-in terrestrial tuner) */ + TV_INPUT_TYPE_TUNER = 2, + TV_INPUT_TYPE_COMPOSITE = 3, + TV_INPUT_TYPE_SVIDEO = 4, + TV_INPUT_TYPE_SCART = 5, + TV_INPUT_TYPE_COMPONENT = 6, + TV_INPUT_TYPE_VGA = 7, + TV_INPUT_TYPE_DVI = 8, + /* Physical HDMI port. (e.g. HDMI 1) */ + TV_INPUT_TYPE_HDMI = 9, + TV_INPUT_TYPE_DISPLAY_PORT = 10, +}; +typedef uint32_t tv_input_type_t; + +typedef struct tv_input_device_info { + /* Device ID */ + int device_id; + + /* Type of physical TV input. */ + tv_input_type_t type; + + union { + struct { + /* HDMI port ID number */ + uint32_t port_id; + } hdmi; + + /* TODO: add other type specific information. */ + + int32_t type_info_reserved[16]; + }; + + /* TODO: Add capability if necessary. */ + + /* + * Audio info + * + * audio_type == AUDIO_DEVICE_NONE if this input has no audio. + */ + audio_devices_t audio_type; + const char* audio_address; + + int32_t reserved[16]; +} tv_input_device_info_t; + +/* See tv_input_event_t for more details. */ +enum { + /* + * Hardware notifies the framework that a device is available. + * + * Note that DEVICE_AVAILABLE and DEVICE_UNAVAILABLE events do not represent + * hotplug events (i.e. plugging cable into or out of the physical port). + * These events notify the framework whether the port is available or not. + * For a concrete example, when a user plugs in or pulls out the HDMI cable + * from a HDMI port, it does not generate DEVICE_AVAILABLE and/or + * DEVICE_UNAVAILABLE events. However, if a user inserts a pluggable USB + * tuner into the Android device, it will generate a DEVICE_AVAILABLE event + * and when the port is removed, it should generate a DEVICE_UNAVAILABLE + * event. + * + * For hotplug events, please see STREAM_CONFIGURATION_CHANGED for more + * details. + * + * HAL implementation should register devices by using this event when the + * device boots up. The framework will recognize device reported via this + * event only. In addition, the implementation could use this event to + * notify the framework that a removable TV input device (such as USB tuner + * as stated in the example above) is attached. + */ + TV_INPUT_EVENT_DEVICE_AVAILABLE = 1, + /* + * Hardware notifies the framework that a device is unavailable. + * + * HAL implementation should generate this event when a device registered + * by TV_INPUT_EVENT_DEVICE_AVAILABLE is no longer available. For example, + * the event can indicate that a USB tuner is plugged out from the Android + * device. + * + * Note that this event is not for indicating cable plugged out of the port; + * for that purpose, the implementation should use + * STREAM_CONFIGURATION_CHANGED event. This event represents the port itself + * being no longer available. + */ + TV_INPUT_EVENT_DEVICE_UNAVAILABLE = 2, + /* + * Stream configurations are changed. Client should regard all open streams + * at the specific device are closed, and should call + * get_stream_configurations() again, opening some of them if necessary. + * + * HAL implementation should generate this event when the available stream + * configurations change for any reason. A typical use case of this event + * would be to notify the framework that the input signal has changed + * resolution, or that the cable is plugged out so that the number of + * available streams is 0. + * + * The implementation may use this event to indicate hotplug status of the + * port. the framework regards input devices with no available streams as + * disconnected, so the implementation can generate this event with no + * available streams to indicate that this device is disconnected, and vice + * versa. + */ + TV_INPUT_EVENT_STREAM_CONFIGURATIONS_CHANGED = 3, + /* + * Hardware is done with capture request with the buffer. Client can assume + * ownership of the buffer again. + * + * HAL implementation should generate this event after request_capture() if + * it succeeded. The event shall have the buffer with the captured image. + */ + TV_INPUT_EVENT_CAPTURE_SUCCEEDED = 4, + /* + * Hardware met a failure while processing a capture request or client + * canceled the request. Client can assume ownership of the buffer again. + * + * The event is similar to TV_INPUT_EVENT_CAPTURE_SUCCEEDED, but HAL + * implementation generates this event upon a failure to process + * request_capture(), or a request cancellation. + */ + TV_INPUT_EVENT_CAPTURE_FAILED = 5, +}; +typedef uint32_t tv_input_event_type_t; + +typedef struct tv_input_capture_result { + /* Device ID */ + int device_id; + + /* Stream ID */ + int stream_id; + + /* Sequence number of the request */ + uint32_t seq; + + /* + * The buffer passed to hardware in request_capture(). The content of + * buffer is undefined (although buffer itself is valid) for + * TV_INPUT_CAPTURE_FAILED event. + */ + buffer_handle_t buffer; + + /* + * Error code for the request. -ECANCELED if request is cancelled; other + * error codes are unknown errors. + */ + int error_code; +} tv_input_capture_result_t; + +typedef struct tv_input_event { + tv_input_event_type_t type; + + union { + /* + * TV_INPUT_EVENT_DEVICE_AVAILABLE: all fields are relevant + * TV_INPUT_EVENT_DEVICE_UNAVAILABLE: only device_id is relevant + * TV_INPUT_EVENT_STREAM_CONFIGURATIONS_CHANGED: only device_id is + * relevant + */ + tv_input_device_info_t device_info; + /* + * TV_INPUT_EVENT_CAPTURE_SUCCEEDED: error_code is not relevant + * TV_INPUT_EVENT_CAPTURE_FAILED: all fields are relevant + */ + tv_input_capture_result_t capture_result; + }; +} tv_input_event_t; + +typedef struct tv_input_callback_ops { + /* + * event contains the type of the event and additional data if necessary. + * The event object is guaranteed to be valid only for the duration of the + * call. + * + * data is an object supplied at device initialization, opaque to the + * hardware. +     */ + void (*notify)(struct tv_input_device* dev, + tv_input_event_t* event, void* data); +} tv_input_callback_ops_t; + +enum { + TV_STREAM_TYPE_INDEPENDENT_VIDEO_SOURCE = 1, + TV_STREAM_TYPE_BUFFER_PRODUCER = 2, +}; +typedef uint32_t tv_stream_type_t; + +typedef struct tv_stream_config { + /* + * ID number of the stream. This value is used to identify the whole stream + * configuration. + */ + int stream_id; + + /* Type of the stream */ + tv_stream_type_t type; + + /* Max width/height of the stream. */ + uint32_t max_video_width; + uint32_t max_video_height; +} tv_stream_config_t; + +typedef struct buffer_producer_stream { + /* + * IN/OUT: Width / height of the stream. Client may request for specific + * size but hardware may change it. Client must allocate buffers with + * specified width and height. + */ + uint32_t width; + uint32_t height; + + /* OUT: Client must set this usage when allocating buffer. */ + uint32_t usage; + + /* OUT: Client must allocate a buffer with this format. */ + uint32_t format; + + /* OUT: Client must allocate buffers based on this count. */ + uint32_t buffer_count; +} buffer_producer_stream_t; + +typedef struct tv_stream { + /* IN: ID in the stream configuration */ + int stream_id; + + /* OUT: Type of the stream (for convenience) */ + tv_stream_type_t type; + + /* Data associated with the stream for client's use */ + union { + /* OUT: A native handle describing the sideband stream source */ + native_handle_t* sideband_stream_source_handle; + + /* IN/OUT: Details are in buffer_producer_stream_t */ + buffer_producer_stream_t buffer_producer; + }; +} tv_stream_t; + +/* + * Every device data structure must begin with hw_device_t + * followed by module specific public methods and attributes. + */ +typedef struct tv_input_device { + struct hw_device_t common; + + /* + * initialize: + * + * Provide callbacks to the device and start operation. At first, no device + * is available and after initialize() completes, currently available + * devices including static devices should notify via callback. + * + * Framework owns callbacks object. + * + * data is a framework-owned object which would be sent back to the + * framework for each callback notifications. + * + * Return 0 on success. + */ + int (*initialize)(struct tv_input_device* dev, + const tv_input_callback_ops_t* callback, void* data); + + /* + * get_stream_configurations: + * + * Get stream configurations for a specific device. An input device may have + * multiple configurations. + * + * The configs object is guaranteed to be valid only until the next call to + * get_stream_configurations() or STREAM_CONFIGURATIONS_CHANGED event. + * + * Return 0 on success. + */ + int (*get_stream_configurations)(const struct tv_input_device* dev, + int device_id, int* num_configurations, + const tv_stream_config_t** configs); + + /* + * open_stream: + * + * Open a stream with given stream ID. Caller owns stream object, and the + * populated data is only valid until the stream is closed. + * + * Return 0 on success; -EBUSY if the client should close other streams to + * open the stream; -EEXIST if the stream with the given ID is already open; + * -EINVAL if device_id and/or stream_id are invalid; other non-zero value + * denotes unknown error. + */ + int (*open_stream)(struct tv_input_device* dev, int device_id, + tv_stream_t* stream); + + /* + * close_stream: + * + * Close a stream to a device. data in tv_stream_t* object associated with + * the stream_id is obsolete once this call finishes. + * + * Return 0 on success; -ENOENT if the stream is not open; -EINVAL if + * device_id and/or stream_id are invalid. + */ + int (*close_stream)(struct tv_input_device* dev, int device_id, + int stream_id); + + /* + * request_capture: + * + * Request buffer capture for a stream. This is only valid for buffer + * producer streams. The buffer should be created with size, format and + * usage specified in the stream. Framework provides seq in an + * increasing sequence per each stream. Hardware should provide the picture + * in a chronological order according to seq. For example, if two + * requests are being processed at the same time, the request with the + * smaller seq should get an earlier frame. + * + * The framework releases the ownership of the buffer upon calling this + * function. When the buffer is filled, hardware notifies the framework + * via TV_INPUT_EVENT_CAPTURE_FINISHED callback, and the ownership is + * transferred back to framework at that time. + * + * Return 0 on success; -ENOENT if the stream is not open; -EINVAL if + * device_id and/or stream_id are invalid; -EWOULDBLOCK if HAL cannot take + * additional requests until it releases a buffer. + */ + int (*request_capture)(struct tv_input_device* dev, int device_id, + int stream_id, buffer_handle_t buffer, uint32_t seq); + + /* + * cancel_capture: + * + * Cancel an ongoing capture. Hardware should release the buffer as soon as + * possible via TV_INPUT_EVENT_CAPTURE_FAILED callback. + * + * Return 0 on success; -ENOENT if the stream is not open; -EINVAL if + * device_id, stream_id, and/or seq are invalid. + */ + int (*cancel_capture)(struct tv_input_device* dev, int device_id, + int stream_id, uint32_t seq); + + void* reserved[16]; +} tv_input_device_t; + +__END_DECLS + +#endif // ANDROID_TV_INPUT_INTERFACE_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/vibrator.h b/phonelibs/android_hardware_libhardware/include/hardware/vibrator.h new file mode 100644 index 0000000000..92b1fd0051 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/vibrator.h @@ -0,0 +1,74 @@ +/* + * 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 _HARDWARE_VIBRATOR_H +#define _HARDWARE_VIBRATOR_H + +#include + +__BEGIN_DECLS + +#define VIBRATOR_API_VERSION HARDWARE_MODULE_API_VERSION(1,0) + +/** + * The id of this module + */ +#define VIBRATOR_HARDWARE_MODULE_ID "vibrator" + +/** + * The id of the main vibrator device + */ +#define VIBRATOR_DEVICE_ID_MAIN "main_vibrator" + +struct vibrator_device; +typedef struct vibrator_device { + /** + * Common methods of the vibrator device. This *must* be the first member of + * vibrator_device as users of this structure will cast a hw_device_t to + * vibrator_device pointer in contexts where it's known the hw_device_t references a + * vibrator_device. + */ + struct hw_device_t common; + + /** Turn on vibrator + * + * What happens when this function is called while the the timeout of a + * previous call has not expired is implementation dependent. + * + * @param timeout_ms number of milliseconds to vibrate + * + * @return 0 in case of success, negative errno code else + */ + int (*vibrator_on)(struct vibrator_device* vibradev, unsigned int timeout_ms); + + /** Turn off vibrator + * + * It is not guaranteed that the vibrator will be immediately stopped: the + * behaviour is implementation dependent. + * + * @return 0 in case of success, negative errno code else + */ + int (*vibrator_off)(struct vibrator_device* vibradev); +} vibrator_device_t; + +static inline int vibrator_open(const struct hw_module_t* module, vibrator_device_t** device) +{ + return module->methods->open(module, VIBRATOR_DEVICE_ID_MAIN, (struct hw_device_t**)device); +} + +__END_DECLS + +#endif // _HARDWARE_VIBRATOR_H diff --git a/phonelibs/android_hardware_libhardware/include/hardware/wipower.h b/phonelibs/android_hardware_libhardware/include/hardware/wipower.h new file mode 100644 index 0000000000..eb3a0ee0d5 --- /dev/null +++ b/phonelibs/android_hardware_libhardware/include/hardware/wipower.h @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2013-2015, The Linux Foundation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of The Linux Foundation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef ANDROID_INCLUDE_WIPOWER_H +#define ANDROID_INCLUDE_WIPOWER_H + +#include +#include +#include +#include + +#include +#include + +__BEGIN_DECLS + +typedef enum { + OFF =0, + ON +} wipower_state_t; + + +typedef struct { + +unsigned char optional; +unsigned short rect_voltage; +unsigned short rect_current; +unsigned short out_voltage; +unsigned short out_current; +unsigned char temp; +unsigned short rect_voltage_min; +unsigned short rect_voltage_set; +unsigned short rect_voltage_max; +unsigned char alert; +unsigned short rfu1; +unsigned char rfu2; + +}__attribute__((packed)) wipower_dyn_data_t; + +/** Bluetooth Enable/Disable Callback. */ +typedef void (*wipower_state_changed_callback)(wipower_state_t state); + + +typedef void (*wipower_alerts)(unsigned char alert); + + +typedef void (*wipower_dynamic_data)(wipower_dyn_data_t* alert_data); + + +typedef void (*wipower_power_apply)(unsigned char power_flag); + +typedef void (*callback_thread_event)(bt_cb_thread_evt evt); + +/** Bluetooth DM callback structure. */ +typedef struct { + /** set to sizeof(wipower_callbacks_t) */ + size_t size; + wipower_state_changed_callback wipower_state_changed_cb; + wipower_alerts wipower_alert; + wipower_dynamic_data wipower_data; + wipower_power_apply wipower_power_event; + callback_thread_event callback_thread_event; +} wipower_callbacks_t; + + +/** Represents the standard Wipower interface. */ +typedef struct { + /** set to sizeof(wipower_interface_t) */ + size_t size; + + /** Initialize Wipower modules*/ + int (*init)(wipower_callbacks_t *wp_callbacks); + + /** Enable/Disable Wipower charging */ + int (*enable)(bool enable); + + int (*set_current_limit)(short value); + + unsigned char (*get_current_limit)(void); + + wipower_state_t (*get_state)(void); + + /** Enable/Disable Wipower charging */ + int (*enable_alerts)(bool enable); + + int (*enable_data_notify)(bool enable); + int (*enable_power_apply)(bool enable, bool on, bool time_flag); +} wipower_interface_t; + + +__END_DECLS + +#endif /* ANDROID_INCLUDE_WIPOWER_H */ diff --git a/phonelibs/android_system_core/include/cutils/android_reboot.h b/phonelibs/android_system_core/include/cutils/android_reboot.h new file mode 100644 index 0000000000..a3861a02dc --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/android_reboot.h @@ -0,0 +1,39 @@ +/* + * Copyright 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 __CUTILS_ANDROID_REBOOT_H__ +#define __CUTILS_ANDROID_REBOOT_H__ + +#include + +__BEGIN_DECLS + +/* Commands */ +#define ANDROID_RB_RESTART 0xDEAD0001 +#define ANDROID_RB_POWEROFF 0xDEAD0002 +#define ANDROID_RB_RESTART2 0xDEAD0003 + +/* Properties */ +#define ANDROID_RB_PROPERTY "sys.powerctl" + +int android_reboot(int cmd, int flags, const char *arg); +int android_reboot_with_callback( + int cmd, int flags, const char *arg, + void (*cb_on_remount)(const struct mntent*)); + +__END_DECLS + +#endif /* __CUTILS_ANDROID_REBOOT_H__ */ diff --git a/phonelibs/android_system_core/include/cutils/aref.h b/phonelibs/android_system_core/include/cutils/aref.h new file mode 100644 index 0000000000..3bd36ea04c --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/aref.h @@ -0,0 +1,58 @@ +/* + * 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 _CUTILS_AREF_H_ +#define _CUTILS_AREF_H_ + +#include +#include + +#include + +__BEGIN_DECLS + +#define AREF_TO_ITEM(aref, container, member) \ + (container *) (((char*) (aref)) - offsetof(container, member)) + +struct aref +{ + volatile int32_t count; +}; + +static inline void aref_init(struct aref *r) +{ + r->count = 1; +} + +static inline int32_t aref_count(struct aref *r) +{ + return r->count; +} + +static inline void aref_get(struct aref *r) +{ + android_atomic_inc(&r->count); +} + +static inline void aref_put(struct aref *r, void (*release)(struct aref *)) +{ + if (android_atomic_dec(&r->count) == 1) + release(r); +} + +__END_DECLS + +#endif // _CUTILS_AREF_H_ diff --git a/phonelibs/android_system_core/include/cutils/ashmem.h b/phonelibs/android_system_core/include/cutils/ashmem.h new file mode 100644 index 0000000000..25b233e6a1 --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/ashmem.h @@ -0,0 +1,45 @@ +/* cutils/ashmem.h + ** + ** Copyright 2008 The Android Open Source Project + ** + ** This file is dual licensed. It may be redistributed and/or modified + ** under the terms of the Apache 2.0 License OR version 2 of the GNU + ** General Public License. + */ + +#ifndef _CUTILS_ASHMEM_H +#define _CUTILS_ASHMEM_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +int ashmem_create_region(const char *name, size_t size); +int ashmem_set_prot_region(int fd, int prot); +int ashmem_pin_region(int fd, size_t offset, size_t len); +int ashmem_unpin_region(int fd, size_t offset, size_t len); +int ashmem_get_size_region(int fd); + +#ifdef __cplusplus +} +#endif + +#ifndef __ASHMEMIOC /* in case someone included too */ + +#define ASHMEM_NAME_LEN 256 + +#define ASHMEM_NAME_DEF "dev/ashmem" + +/* Return values from ASHMEM_PIN: Was the mapping purged while unpinned? */ +#define ASHMEM_NOT_PURGED 0 +#define ASHMEM_WAS_PURGED 1 + +/* Return values from ASHMEM_UNPIN: Is the mapping now pinned or unpinned? */ +#define ASHMEM_IS_UNPINNED 0 +#define ASHMEM_IS_PINNED 1 + +#endif /* ! __ASHMEMIOC */ + +#endif /* _CUTILS_ASHMEM_H */ diff --git a/phonelibs/android_system_core/include/cutils/atomic.h b/phonelibs/android_system_core/include/cutils/atomic.h new file mode 100644 index 0000000000..ded972acb2 --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/atomic.h @@ -0,0 +1,237 @@ +/* + * 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_CUTILS_ATOMIC_H +#define ANDROID_CUTILS_ATOMIC_H + +#include +#include +#include + +#ifndef ANDROID_ATOMIC_INLINE +#define ANDROID_ATOMIC_INLINE static inline +#endif + +/* + * A handful of basic atomic operations. + * THESE ARE HERE FOR LEGACY REASONS ONLY. AVOID. + * + * PREFERRED ALTERNATIVES: + * - Use C++/C/pthread locks/mutexes whenever there is not a + * convincing reason to do otherwise. Note that very clever and + * complicated, but correct, lock-free code is often slower than + * using locks, especially where nontrivial data structures + * are involved. + * - C11 stdatomic.h. + * - Where supported, C++11 std::atomic . + * + * PLEASE STOP READING HERE UNLESS YOU ARE TRYING TO UNDERSTAND + * OR UPDATE OLD CODE. + * + * The "acquire" and "release" terms can be defined intuitively in terms + * of the placement of memory barriers in a simple lock implementation: + * - wait until compare-and-swap(lock-is-free --> lock-is-held) succeeds + * - barrier + * - [do work] + * - barrier + * - store(lock-is-free) + * In very crude terms, the initial (acquire) barrier prevents any of the + * "work" from happening before the lock is held, and the later (release) + * barrier ensures that all of the work happens before the lock is released. + * (Think of cached writes, cache read-ahead, and instruction reordering + * around the CAS and store instructions.) + * + * The barriers must apply to both the compiler and the CPU. Note it is + * legal for instructions that occur before an "acquire" barrier to be + * moved down below it, and for instructions that occur after a "release" + * barrier to be moved up above it. + * + * The ARM-driven implementation we use here is short on subtlety, + * and actually requests a full barrier from the compiler and the CPU. + * The only difference between acquire and release is in whether they + * are issued before or after the atomic operation with which they + * are associated. To ease the transition to C/C++ atomic intrinsics, + * you should not rely on this, and instead assume that only the minimal + * acquire/release protection is provided. + * + * NOTE: all int32_t* values are expected to be aligned on 32-bit boundaries. + * If they are not, atomicity is not guaranteed. + */ + +/* + * Basic arithmetic and bitwise operations. These all provide a + * barrier with "release" ordering, and return the previous value. + * + * These have the same characteristics (e.g. what happens on overflow) + * as the equivalent non-atomic C operations. + */ +ANDROID_ATOMIC_INLINE +int32_t android_atomic_inc(volatile int32_t* addr) +{ + volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr; + /* Int32_t, if it exists, is the same as int_least32_t. */ + return atomic_fetch_add_explicit(a, 1, memory_order_release); +} + +ANDROID_ATOMIC_INLINE +int32_t android_atomic_dec(volatile int32_t* addr) +{ + volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr; + return atomic_fetch_sub_explicit(a, 1, memory_order_release); +} + +ANDROID_ATOMIC_INLINE +int32_t android_atomic_add(int32_t value, volatile int32_t* addr) +{ + volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr; + return atomic_fetch_add_explicit(a, value, memory_order_release); +} + +ANDROID_ATOMIC_INLINE +int32_t android_atomic_and(int32_t value, volatile int32_t* addr) +{ + volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr; + return atomic_fetch_and_explicit(a, value, memory_order_release); +} + +ANDROID_ATOMIC_INLINE +int32_t android_atomic_or(int32_t value, volatile int32_t* addr) +{ + volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr; + return atomic_fetch_or_explicit(a, value, memory_order_release); +} + +/* + * Perform an atomic load with "acquire" or "release" ordering. + * + * Note that the notion of a "release" ordering for a load does not + * really fit into the C11 or C++11 memory model. The extra ordering + * is normally observable only by code using memory_order_relaxed + * atomics, or data races. In the rare cases in which such ordering + * is called for, use memory_order_relaxed atomics and a leading + * atomic_thread_fence (typically with memory_order_acquire, + * not memory_order_release!) instead. If you do not understand + * this comment, you are in the vast majority, and should not be + * using release loads or replacing them with anything other than + * locks or default sequentially consistent atomics. + */ +ANDROID_ATOMIC_INLINE +int32_t android_atomic_acquire_load(volatile const int32_t* addr) +{ + volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr; + return atomic_load_explicit(a, memory_order_acquire); +} + +ANDROID_ATOMIC_INLINE +int32_t android_atomic_release_load(volatile const int32_t* addr) +{ + volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr; + atomic_thread_fence(memory_order_seq_cst); + /* Any reasonable clients of this interface would probably prefer */ + /* something weaker. But some remaining clients seem to be */ + /* abusing this API in strange ways, e.g. by using it as a fence. */ + /* Thus we are conservative until we can get rid of remaining */ + /* clients (and this function). */ + return atomic_load_explicit(a, memory_order_relaxed); +} + +/* + * Perform an atomic store with "acquire" or "release" ordering. + * + * Note that the notion of an "acquire" ordering for a store does not + * really fit into the C11 or C++11 memory model. The extra ordering + * is normally observable only by code using memory_order_relaxed + * atomics, or data races. In the rare cases in which such ordering + * is called for, use memory_order_relaxed atomics and a trailing + * atomic_thread_fence (typically with memory_order_release, + * not memory_order_acquire!) instead. + */ +ANDROID_ATOMIC_INLINE +void android_atomic_acquire_store(int32_t value, volatile int32_t* addr) +{ + volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr; + atomic_store_explicit(a, value, memory_order_relaxed); + atomic_thread_fence(memory_order_seq_cst); + /* Again overly conservative to accomodate weird clients. */ +} + +ANDROID_ATOMIC_INLINE +void android_atomic_release_store(int32_t value, volatile int32_t* addr) +{ + volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr; + atomic_store_explicit(a, value, memory_order_release); +} + +/* + * Compare-and-set operation with "acquire" or "release" ordering. + * + * This returns zero if the new value was successfully stored, which will + * only happen when *addr == oldvalue. + * + * (The return value is inverted from implementations on other platforms, + * but matches the ARM ldrex/strex result.) + * + * Implementations that use the release CAS in a loop may be less efficient + * than possible, because we re-issue the memory barrier on each iteration. + */ +ANDROID_ATOMIC_INLINE +int android_atomic_acquire_cas(int32_t oldvalue, int32_t newvalue, + volatile int32_t* addr) +{ + volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr; + return (int)(!atomic_compare_exchange_strong_explicit( + a, &oldvalue, newvalue, + memory_order_acquire, + memory_order_acquire)); +} + +ANDROID_ATOMIC_INLINE +int android_atomic_release_cas(int32_t oldvalue, int32_t newvalue, + volatile int32_t* addr) +{ + volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr; + return (int)(!atomic_compare_exchange_strong_explicit( + a, &oldvalue, newvalue, + memory_order_release, + memory_order_relaxed)); +} + +/* + * Fence primitives. + */ +ANDROID_ATOMIC_INLINE +void android_compiler_barrier(void) +{ + __asm__ __volatile__ ("" : : : "memory"); + /* Could probably also be: */ + /* atomic_signal_fence(memory_order_seq_cst); */ +} + +ANDROID_ATOMIC_INLINE +void android_memory_barrier(void) +{ + atomic_thread_fence(memory_order_seq_cst); +} + +/* + * Aliases for code using an older version of this header. These are now + * deprecated and should not be used. The definitions will be removed + * in a future release. + */ +#define android_atomic_write android_atomic_release_store +#define android_atomic_cmpxchg android_atomic_release_cas + +#endif // ANDROID_CUTILS_ATOMIC_H diff --git a/phonelibs/android_system_core/include/cutils/bitops.h b/phonelibs/android_system_core/include/cutils/bitops.h new file mode 100644 index 0000000000..045830d90b --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/bitops.h @@ -0,0 +1,120 @@ +/* + * 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 __CUTILS_BITOPS_H +#define __CUTILS_BITOPS_H + +#include +#include +#include +#include + +__BEGIN_DECLS + +/* + * Bitmask Operations + * + * Note this doesn't provide any locking/exclusion, and isn't atomic. + * Additionally no bounds checking is done on the bitmask array. + * + * Example: + * + * int num_resources; + * unsigned int resource_bits[BITS_TO_WORDS(num_resources)]; + * bitmask_init(resource_bits, num_resources); + * ... + * int bit = bitmask_ffz(resource_bits, num_resources); + * bitmask_set(resource_bits, bit); + * ... + * if (bitmask_test(resource_bits, bit)) { ... } + * ... + * bitmask_clear(resource_bits, bit); + * + */ + +#define BITS_PER_WORD (sizeof(unsigned int) * 8) +#define BITS_TO_WORDS(x) (((x) + BITS_PER_WORD - 1) / BITS_PER_WORD) +#define BIT_IN_WORD(x) ((x) % BITS_PER_WORD) +#define BIT_WORD(x) ((x) / BITS_PER_WORD) +#define BIT_MASK(x) (1 << BIT_IN_WORD(x)) + +static inline void bitmask_init(unsigned int *bitmask, int num_bits) +{ + memset(bitmask, 0, BITS_TO_WORDS(num_bits)*sizeof(unsigned int)); +} + +static inline int bitmask_ffz(unsigned int *bitmask, int num_bits) +{ + int bit, result; + size_t i; + + for (i = 0; i < BITS_TO_WORDS(num_bits); i++) { + bit = ffs(~bitmask[i]); + if (bit) { + // ffs is 1-indexed, return 0-indexed result + bit--; + result = BITS_PER_WORD * i + bit; + if (result >= num_bits) + return -1; + return result; + } + } + return -1; +} + +static inline int bitmask_weight(unsigned int *bitmask, int num_bits) +{ + size_t i; + int weight = 0; + + for (i = 0; i < BITS_TO_WORDS(num_bits); i++) + weight += __builtin_popcount(bitmask[i]); + return weight; +} + +static inline void bitmask_set(unsigned int *bitmask, int bit) +{ + bitmask[BIT_WORD(bit)] |= BIT_MASK(bit); +} + +static inline void bitmask_clear(unsigned int *bitmask, int bit) +{ + bitmask[BIT_WORD(bit)] &= ~BIT_MASK(bit); +} + +static inline bool bitmask_test(unsigned int *bitmask, int bit) +{ + return bitmask[BIT_WORD(bit)] & BIT_MASK(bit); +} + +static inline int popcount(unsigned int x) +{ + return __builtin_popcount(x); +} + +static inline int popcountl(unsigned long x) +{ + return __builtin_popcountl(x); +} + +static inline int popcountll(unsigned long long x) +{ + return __builtin_popcountll(x); +} + +__END_DECLS + +#endif /* __CUTILS_BITOPS_H */ diff --git a/phonelibs/android_system_core/include/cutils/compiler.h b/phonelibs/android_system_core/include/cutils/compiler.h new file mode 100644 index 0000000000..70f884a1e7 --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/compiler.h @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_CUTILS_COMPILER_H +#define ANDROID_CUTILS_COMPILER_H + +/* + * helps the compiler's optimizer predicting branches + */ + +#ifdef __cplusplus +# define CC_LIKELY( exp ) (__builtin_expect( !!(exp), true )) +# define CC_UNLIKELY( exp ) (__builtin_expect( !!(exp), false )) +#else +# define CC_LIKELY( exp ) (__builtin_expect( !!(exp), 1 )) +# define CC_UNLIKELY( exp ) (__builtin_expect( !!(exp), 0 )) +#endif + +/** + * exports marked symbols + * + * if used on a C++ class declaration, this macro must be inserted + * after the "class" keyword. For instance: + * + * template + * class ANDROID_API Singleton { } + */ + +#define ANDROID_API __attribute__((visibility("default"))) + +#endif // ANDROID_CUTILS_COMPILER_H diff --git a/phonelibs/android_system_core/include/cutils/config_utils.h b/phonelibs/android_system_core/include/cutils/config_utils.h new file mode 100644 index 0000000000..2dea6f19fa --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/config_utils.h @@ -0,0 +1,64 @@ +/* + * 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 __CUTILS_CONFIG_UTILS_H +#define __CUTILS_CONFIG_UTILS_H + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct cnode cnode; + + +struct cnode +{ + cnode *next; + cnode *first_child; + cnode *last_child; + const char *name; + const char *value; +}; + +/* parse a text string into a config node tree */ +void config_load(cnode *root, char *data); + +/* parse a file into a config node tree */ +void config_load_file(cnode *root, const char *fn); + +/* create a single config node */ +cnode* config_node(const char *name, const char *value); + +/* locate a named child of a config node */ +cnode* config_find(cnode *root, const char *name); + +/* look up a child by name and return the boolean value */ +int config_bool(cnode *root, const char *name, int _default); + +/* look up a child by name and return the string value */ +const char* config_str(cnode *root, const char *name, const char *_default); + +/* add a named child to a config node (or modify it if it already exists) */ +void config_set(cnode *root, const char *name, const char *value); + +/* free a config node tree */ +void config_free(cnode *root); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/phonelibs/android_system_core/include/cutils/debugger.h b/phonelibs/android_system_core/include/cutils/debugger.h new file mode 100644 index 0000000000..285e1afcd7 --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/debugger.h @@ -0,0 +1,77 @@ +/* + * 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 __CUTILS_DEBUGGER_H +#define __CUTILS_DEBUGGER_H + +#include +#include + +__BEGIN_DECLS + +#define DEBUGGER_SOCKET_NAME "android:debuggerd" +#define DEBUGGER32_SOCKET_NAME "android:debuggerd32" +#define DEBUGGER64_SOCKET_NAME DEBUGGER_SOCKET_NAME + +typedef enum { + // dump a crash + DEBUGGER_ACTION_CRASH, + // dump a tombstone file + DEBUGGER_ACTION_DUMP_TOMBSTONE, + // dump a backtrace only back to the socket + DEBUGGER_ACTION_DUMP_BACKTRACE, +} debugger_action_t; + +// Make sure that all values have a fixed size so that this structure +// is the same for 32 bit and 64 bit processes. +// NOTE: Any changes to this structure must also be reflected in +// bionic/linker/debugger.cpp. +typedef struct __attribute__((packed)) { + int32_t action; + pid_t tid; + uint64_t abort_msg_address; + int32_t original_si_code; +} debugger_msg_t; + +/* Dumps a process backtrace, registers, and stack to a tombstone file (requires root). + * Stores the tombstone path in the provided buffer. + * Returns 0 on success, -1 on error. + */ +int dump_tombstone(pid_t tid, char* pathbuf, size_t pathlen); + +/* Dumps a process backtrace, registers, and stack to a tombstone file (requires root). + * Stores the tombstone path in the provided buffer. + * If reading debugger data from debuggerd ever takes longer than timeout_secs + * seconds, then stop and return an error. + * Returns 0 on success, -1 on error. + */ +int dump_tombstone_timeout(pid_t tid, char* pathbuf, size_t pathlen, int timeout_secs); + +/* Dumps a process backtrace only to the specified file (requires root). + * Returns 0 on success, -1 on error. + */ +int dump_backtrace_to_file(pid_t tid, int fd); + +/* Dumps a process backtrace only to the specified file (requires root). + * If reading debugger data from debuggerd ever takes longer than timeout_secs + * seconds, then stop and return an error. + * Returns 0 on success, -1 on error. + */ +int dump_backtrace_to_file_timeout(pid_t tid, int fd, int timeout_secs); + +__END_DECLS + +#endif /* __CUTILS_DEBUGGER_H */ diff --git a/phonelibs/android_system_core/include/cutils/fs.h b/phonelibs/android_system_core/include/cutils/fs.h new file mode 100644 index 0000000000..70f0b92919 --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/fs.h @@ -0,0 +1,71 @@ +/* + * 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 __CUTILS_FS_H +#define __CUTILS_FS_H + +#include +#include + +/* + * TEMP_FAILURE_RETRY is defined by some, but not all, versions of + * . (Alas, it is not as standard as we'd hoped!) So, if it's + * not already defined, then define it here. + */ +#ifndef TEMP_FAILURE_RETRY +/* Used to retry syscalls that can return EINTR. */ +#define TEMP_FAILURE_RETRY(exp) ({ \ + typeof (exp) _rc; \ + do { \ + _rc = (exp); \ + } while (_rc == -1 && errno == EINTR); \ + _rc; }) +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Ensure that directory exists with given mode and owners. + */ +extern int fs_prepare_dir(const char* path, mode_t mode, uid_t uid, gid_t gid); + +/* + * Read single plaintext integer from given file, correctly handling files + * partially written with fs_write_atomic_int(). + */ +extern int fs_read_atomic_int(const char* path, int* value); + +/* + * Write single plaintext integer to given file, creating backup while + * in progress. + */ +extern int fs_write_atomic_int(const char* path, int value); + +/* + * Ensure that all directories along given path exist, creating parent + * directories as needed. Validates that given path is absolute and that + * it contains no relative "." or ".." paths or symlinks. Last path segment + * is treated as filename and ignored, unless the path ends with "/". + */ +extern int fs_mkdirs(const char* path, mode_t mode); + +#ifdef __cplusplus +} +#endif + +#endif /* __CUTILS_FS_H */ diff --git a/phonelibs/android_system_core/include/cutils/hashmap.h b/phonelibs/android_system_core/include/cutils/hashmap.h new file mode 100644 index 0000000000..5cb344c152 --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/hashmap.h @@ -0,0 +1,150 @@ +/* + * 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. + */ + +/** + * Hash map. + */ + +#ifndef __HASHMAP_H +#define __HASHMAP_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** A hash map. */ +typedef struct Hashmap Hashmap; + +/** + * Creates a new hash map. Returns NULL if memory allocation fails. + * + * @param initialCapacity number of expected entries + * @param hash function which hashes keys + * @param equals function which compares keys for equality + */ +Hashmap* hashmapCreate(size_t initialCapacity, + int (*hash)(void* key), bool (*equals)(void* keyA, void* keyB)); + +/** + * Frees the hash map. Does not free the keys or values themselves. + */ +void hashmapFree(Hashmap* map); + +/** + * Hashes the memory pointed to by key with the given size. Useful for + * implementing hash functions. + */ +int hashmapHash(void* key, size_t keySize); + +/** + * Puts value for the given key in the map. Returns pre-existing value if + * any. + * + * If memory allocation fails, this function returns NULL, the map's size + * does not increase, and errno is set to ENOMEM. + */ +void* hashmapPut(Hashmap* map, void* key, void* value); + +/** + * Gets a value from the map. Returns NULL if no entry for the given key is + * found or if the value itself is NULL. + */ +void* hashmapGet(Hashmap* map, void* key); + +/** + * Returns true if the map contains an entry for the given key. + */ +bool hashmapContainsKey(Hashmap* map, void* key); + +/** + * Gets the value for a key. If a value is not found, this function gets a + * value and creates an entry using the given callback. + * + * If memory allocation fails, the callback is not called, this function + * returns NULL, and errno is set to ENOMEM. + */ +void* hashmapMemoize(Hashmap* map, void* key, + void* (*initialValue)(void* key, void* context), void* context); + +/** + * Removes an entry from the map. Returns the removed value or NULL if no + * entry was present. + */ +void* hashmapRemove(Hashmap* map, void* key); + +/** + * Gets the number of entries in this map. + */ +size_t hashmapSize(Hashmap* map); + +/** + * Invokes the given callback on each entry in the map. Stops iterating if + * the callback returns false. + */ +void hashmapForEach(Hashmap* map, + bool (*callback)(void* key, void* value, void* context), + void* context); + +/** + * Concurrency support. + */ + +/** + * Locks the hash map so only the current thread can access it. + */ +void hashmapLock(Hashmap* map); + +/** + * Unlocks the hash map so other threads can access it. + */ +void hashmapUnlock(Hashmap* map); + +/** + * Key utilities. + */ + +/** + * Hashes int keys. 'key' is a pointer to int. + */ +int hashmapIntHash(void* key); + +/** + * Compares two int keys for equality. + */ +bool hashmapIntEquals(void* keyA, void* keyB); + +/** + * For debugging. + */ + +/** + * Gets current capacity. + */ +size_t hashmapCurrentCapacity(Hashmap* map); + +/** + * Counts the number of entry collisions. + */ +size_t hashmapCountCollisions(Hashmap* map); + +#ifdef __cplusplus +} +#endif + +#endif /* __HASHMAP_H */ diff --git a/phonelibs/android_system_core/include/cutils/iosched_policy.h b/phonelibs/android_system_core/include/cutils/iosched_policy.h new file mode 100644 index 0000000000..25b87bac0a --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/iosched_policy.h @@ -0,0 +1,40 @@ +/* + * 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 __CUTILS_IOSCHED_POLICY_H +#define __CUTILS_IOSCHED_POLICY_H + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + IoSchedClass_NONE, + IoSchedClass_RT, + IoSchedClass_BE, + IoSchedClass_IDLE, +} IoSchedClass; + +extern int android_set_ioprio(int pid, IoSchedClass clazz, int ioprio); +extern int android_get_ioprio(int pid, IoSchedClass *clazz, int *ioprio); + +extern int android_set_rt_ioprio(int pid, int rt); + +#ifdef __cplusplus +} +#endif + +#endif /* __CUTILS_IOSCHED_POLICY_H */ diff --git a/phonelibs/android_system_core/include/cutils/jstring.h b/phonelibs/android_system_core/include/cutils/jstring.h new file mode 100644 index 0000000000..a3426081a0 --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/jstring.h @@ -0,0 +1,46 @@ +/* + * 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 __CUTILS_STRING16_H +#define __CUTILS_STRING16_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#if __STDC_VERSION__ < 201112L && __cplusplus < 201103L + typedef uint16_t char16_t; +#endif + // otherwise char16_t is a keyword with the right semantics + +extern char * strndup16to8 (const char16_t* s, size_t n); +extern size_t strnlen16to8 (const char16_t* s, size_t n); +extern char * strncpy16to8 (char *dest, const char16_t*s, size_t n); + +extern char16_t * strdup8to16 (const char* s, size_t *out_len); +extern size_t strlen8to16 (const char* utf8Str); +extern char16_t * strcpy8to16 (char16_t *dest, const char*s, size_t *out_len); +extern char16_t * strcpylen8to16 (char16_t *dest, const char*s, int length, + size_t *out_len); + +#ifdef __cplusplus +} +#endif + +#endif /* __CUTILS_STRING16_H */ diff --git a/phonelibs/android_system_core/include/cutils/klog.h b/phonelibs/android_system_core/include/cutils/klog.h new file mode 100644 index 0000000000..295d62be37 --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/klog.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _CUTILS_KLOG_H_ +#define _CUTILS_KLOG_H_ + +#include +#include +#include + +__BEGIN_DECLS + +void klog_init(void); +int klog_get_level(void); +void klog_set_level(int level); +/* TODO: void klog_close(void); - and make klog_fd users thread safe. */ + +void klog_write(int level, const char *fmt, ...) + __attribute__ ((format(printf, 2, 3))); +void klog_writev(int level, const struct iovec* iov, int iov_count); + +__END_DECLS + +#define KLOG_ERROR_LEVEL 3 +#define KLOG_WARNING_LEVEL 4 +#define KLOG_NOTICE_LEVEL 5 +#define KLOG_INFO_LEVEL 6 +#define KLOG_DEBUG_LEVEL 7 + +#define KLOG_ERROR(tag,x...) klog_write(KLOG_ERROR_LEVEL, "<3>" tag ": " x) +#define KLOG_WARNING(tag,x...) klog_write(KLOG_WARNING_LEVEL, "<4>" tag ": " x) +#define KLOG_NOTICE(tag,x...) klog_write(KLOG_NOTICE_LEVEL, "<5>" tag ": " x) +#define KLOG_INFO(tag,x...) klog_write(KLOG_INFO_LEVEL, "<6>" tag ": " x) +#define KLOG_DEBUG(tag,x...) klog_write(KLOG_DEBUG_LEVEL, "<7>" tag ": " x) + +#define KLOG_DEFAULT_LEVEL 3 /* messages <= this level are logged */ + +#endif diff --git a/phonelibs/android_system_core/include/cutils/list.h b/phonelibs/android_system_core/include/cutils/list.h new file mode 100644 index 0000000000..4ba2cfd499 --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/list.h @@ -0,0 +1,88 @@ +/* + * Copyright (C) 2008-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 _CUTILS_LIST_H_ +#define _CUTILS_LIST_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +struct listnode +{ + struct listnode *next; + struct listnode *prev; +}; + +#define node_to_item(node, container, member) \ + (container *) (((char*) (node)) - offsetof(container, member)) + +#define list_declare(name) \ + struct listnode name = { \ + .next = &name, \ + .prev = &name, \ + } + +#define list_for_each(node, list) \ + for (node = (list)->next; node != (list); node = node->next) + +#define list_for_each_reverse(node, list) \ + for (node = (list)->prev; node != (list); node = node->prev) + +#define list_for_each_safe(node, n, list) \ + for (node = (list)->next, n = node->next; \ + node != (list); \ + node = n, n = node->next) + +static inline void list_init(struct listnode *node) +{ + node->next = node; + node->prev = node; +} + +static inline void list_add_tail(struct listnode *head, struct listnode *item) +{ + item->next = head; + item->prev = head->prev; + head->prev->next = item; + head->prev = item; +} + +static inline void list_add_head(struct listnode *head, struct listnode *item) +{ + item->next = head->next; + item->prev = head; + head->next->prev = item; + head->next = item; +} + +static inline void list_remove(struct listnode *item) +{ + item->next->prev = item->prev; + item->prev->next = item->next; +} + +#define list_empty(list) ((list) == (list)->next) +#define list_head(list) ((list)->next) +#define list_tail(list) ((list)->prev) + +#ifdef __cplusplus +}; +#endif /* __cplusplus */ + +#endif diff --git a/phonelibs/android_system_core/include/cutils/log.h b/phonelibs/android_system_core/include/cutils/log.h new file mode 100644 index 0000000000..0e0248e50f --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/log.h @@ -0,0 +1 @@ +#include diff --git a/phonelibs/android_system_core/include/cutils/memory.h b/phonelibs/android_system_core/include/cutils/memory.h new file mode 100644 index 0000000000..4d26882556 --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/memory.h @@ -0,0 +1,42 @@ +/* + * 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_CUTILS_MEMORY_H +#define ANDROID_CUTILS_MEMORY_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* size is given in bytes and must be multiple of 2 */ +void android_memset16(uint16_t* dst, uint16_t value, size_t size); + +/* size is given in bytes and must be multiple of 4 */ +void android_memset32(uint32_t* dst, uint32_t value, size_t size); + +#if defined(__GLIBC__) || defined(_WIN32) +/* Declaration of strlcpy() for platforms that don't already have it. */ +size_t strlcpy(char *dst, const char *src, size_t size); +#endif + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // ANDROID_CUTILS_MEMORY_H diff --git a/phonelibs/android_system_core/include/cutils/misc.h b/phonelibs/android_system_core/include/cutils/misc.h new file mode 100644 index 0000000000..0de505f277 --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/misc.h @@ -0,0 +1,41 @@ +/* + * 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 __CUTILS_MISC_H +#define __CUTILS_MISC_H + +#ifdef __cplusplus +extern "C" { +#endif + + /* Load an entire file into a malloc'd chunk of memory + * that is length_of_file + 1 (null terminator). If + * sz is non-zero, return the size of the file via sz. + * Returns 0 on failure. + */ +extern void *load_file(const char *fn, unsigned *sz); + + /* This is the range of UIDs (and GIDs) that are reserved + * for assigning to applications. + */ +#define FIRST_APPLICATION_UID 10000 +#define LAST_APPLICATION_UID 99999 + +#ifdef __cplusplus +} +#endif + +#endif /* __CUTILS_MISC_H */ diff --git a/phonelibs/android_system_core/include/cutils/multiuser.h b/phonelibs/android_system_core/include/cutils/multiuser.h new file mode 100644 index 0000000000..635ddb1358 --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/multiuser.h @@ -0,0 +1,41 @@ +/* + * 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 __CUTILS_MULTIUSER_H +#define __CUTILS_MULTIUSER_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// NOTE: keep in sync with android.os.UserId + +#define MULTIUSER_APP_PER_USER_RANGE 100000 + +typedef uid_t userid_t; +typedef uid_t appid_t; + +extern userid_t multiuser_get_user_id(uid_t uid); +extern appid_t multiuser_get_app_id(uid_t uid); +extern uid_t multiuser_get_uid(userid_t userId, appid_t appId); + +#ifdef __cplusplus +} +#endif + +#endif /* __CUTILS_MULTIUSER_H */ diff --git a/phonelibs/android_system_core/include/cutils/native_handle.h b/phonelibs/android_system_core/include/cutils/native_handle.h new file mode 100644 index 0000000000..268c5d3f51 --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/native_handle.h @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_HANDLE_H_ +#define NATIVE_HANDLE_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct native_handle +{ + int version; /* sizeof(native_handle_t) */ + int numFds; /* number of file-descriptors at &data[0] */ + int numInts; /* number of ints at &data[numFds] */ + int data[0]; /* numFds + numInts ints */ +} native_handle_t; + +/* + * native_handle_close + * + * closes the file descriptors contained in this native_handle_t + * + * return 0 on success, or a negative error code on failure + * + */ +int native_handle_close(const native_handle_t* h); + + +/* + * native_handle_create + * + * creates a native_handle_t and initializes it. must be destroyed with + * native_handle_delete(). + * + */ +native_handle_t* native_handle_create(int numFds, int numInts); + +/* + * native_handle_delete + * + * frees a native_handle_t allocated with native_handle_create(). + * This ONLY frees the memory allocated for the native_handle_t, but doesn't + * close the file descriptors; which can be achieved with native_handle_close(). + * + * return 0 on success, or a negative error code on failure + * + */ +int native_handle_delete(native_handle_t* h); + + +#ifdef __cplusplus +} +#endif + +#endif /* NATIVE_HANDLE_H_ */ diff --git a/phonelibs/android_system_core/include/cutils/open_memstream.h b/phonelibs/android_system_core/include/cutils/open_memstream.h new file mode 100644 index 0000000000..c1a81ebbcb --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/open_memstream.h @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CUTILS_OPEN_MEMSTREAM_H__ +#define __CUTILS_OPEN_MEMSTREAM_H__ + +#include + +#if defined(__APPLE__) + +#ifdef __cplusplus +extern "C" { +#endif + +FILE* open_memstream(char** bufp, size_t* sizep); + +#ifdef __cplusplus +} +#endif + +#endif /* __APPLE__ */ + +#endif /*__CUTILS_OPEN_MEMSTREAM_H__*/ diff --git a/phonelibs/android_system_core/include/cutils/partition_utils.h b/phonelibs/android_system_core/include/cutils/partition_utils.h new file mode 100644 index 0000000000..72ca80d350 --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/partition_utils.h @@ -0,0 +1,26 @@ +/* + * Copyright 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 __CUTILS_PARTITION_WIPED_H__ +#define __CUTILS_PARTITION_WIPED_H__ + +__BEGIN_DECLS + +int partition_wiped(char *source); + +__END_DECLS + +#endif /* __CUTILS_PARTITION_WIPED_H__ */ diff --git a/phonelibs/android_system_core/include/cutils/process_name.h b/phonelibs/android_system_core/include/cutils/process_name.h new file mode 100644 index 0000000000..1e72e5c3ad --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/process_name.h @@ -0,0 +1,42 @@ +/* + * 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. + */ + +/** + * Gives the current process a name. + */ + +#ifndef __PROCESS_NAME_H +#define __PROCESS_NAME_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Sets the current process name. + * + * Warning: This leaks a string every time you call it. Use judiciously! + */ +void set_process_name(const char* process_name); + +/** Gets the current process name. */ +const char* get_process_name(void); + +#ifdef __cplusplus +} +#endif + +#endif /* __PROCESS_NAME_H */ diff --git a/phonelibs/android_system_core/include/cutils/properties.h b/phonelibs/android_system_core/include/cutils/properties.h new file mode 100644 index 0000000000..24aa224f64 --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/properties.h @@ -0,0 +1,133 @@ +/* + * 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 __CUTILS_PROPERTIES_H +#define __CUTILS_PROPERTIES_H + +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* System properties are *small* name value pairs managed by the +** property service. If your data doesn't fit in the provided +** space it is not appropriate for a system property. +** +** WARNING: system/bionic/include/sys/system_properties.h also defines +** these, but with different names. (TODO: fix that) +*/ +#define PROPERTY_KEY_MAX PROP_NAME_MAX +#define PROPERTY_VALUE_MAX PROP_VALUE_MAX + +/* property_get: returns the length of the value which will never be +** greater than PROPERTY_VALUE_MAX - 1 and will always be zero terminated. +** (the length does not include the terminating zero). +** +** If the property read fails or returns an empty value, the default +** value is used (if nonnull). +*/ +int property_get(const char *key, char *value, const char *default_value); + +/* property_get_bool: returns the value of key coerced into a +** boolean. If the property is not set, then the default value is returned. +** +* The following is considered to be true (1): +** "1", "true", "y", "yes", "on" +** +** The following is considered to be false (0): +** "0", "false", "n", "no", "off" +** +** The conversion is whitespace-sensitive (e.g. " off" will not be false). +** +** If no property with this key is set (or the key is NULL) or the boolean +** conversion fails, the default value is returned. +**/ +int8_t property_get_bool(const char *key, int8_t default_value); + +/* property_get_int64: returns the value of key truncated and coerced into a +** int64_t. If the property is not set, then the default value is used. +** +** The numeric conversion is identical to strtoimax with the base inferred: +** - All digits up to the first non-digit characters are read +** - The longest consecutive prefix of digits is converted to a long +** +** Valid strings of digits are: +** - An optional sign character + or - +** - An optional prefix indicating the base (otherwise base 10 is assumed) +** -- 0 prefix is octal +** -- 0x / 0X prefix is hex +** +** Leading/trailing whitespace is ignored. Overflow/underflow will cause +** numeric conversion to fail. +** +** If no property with this key is set (or the key is NULL) or the numeric +** conversion fails, the default value is returned. +**/ +int64_t property_get_int64(const char *key, int64_t default_value); + +/* property_get_int32: returns the value of key truncated and coerced into an +** int32_t. If the property is not set, then the default value is used. +** +** The numeric conversion is identical to strtoimax with the base inferred: +** - All digits up to the first non-digit characters are read +** - The longest consecutive prefix of digits is converted to a long +** +** Valid strings of digits are: +** - An optional sign character + or - +** - An optional prefix indicating the base (otherwise base 10 is assumed) +** -- 0 prefix is octal +** -- 0x / 0X prefix is hex +** +** Leading/trailing whitespace is ignored. Overflow/underflow will cause +** numeric conversion to fail. +** +** If no property with this key is set (or the key is NULL) or the numeric +** conversion fails, the default value is returned. +**/ +int32_t property_get_int32(const char *key, int32_t default_value); + +/* property_set: returns 0 on success, < 0 on failure +*/ +int property_set(const char *key, const char *value); + +int property_list(void (*propfn)(const char *key, const char *value, void *cookie), void *cookie); + +#if defined(__BIONIC_FORTIFY) + +extern int __property_get_real(const char *, char *, const char *) + __asm__(__USER_LABEL_PREFIX__ "property_get"); +__errordecl(__property_get_too_small_error, "property_get() called with too small of a buffer"); + +__BIONIC_FORTIFY_INLINE +int property_get(const char *key, char *value, const char *default_value) { + size_t bos = __bos(value); + if (bos < PROPERTY_VALUE_MAX) { + __property_get_too_small_error(); + } + return __property_get_real(key, value, default_value); +} + +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/phonelibs/android_system_core/include/cutils/qtaguid.h b/phonelibs/android_system_core/include/cutils/qtaguid.h new file mode 100644 index 0000000000..f8550fda83 --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/qtaguid.h @@ -0,0 +1,66 @@ +/* + * 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 __CUTILS_QTAGUID_H +#define __CUTILS_QTAGUID_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Set tags (and owning UIDs) for network sockets. +*/ +extern int qtaguid_tagSocket(int sockfd, int tag, uid_t uid); + +/* + * Untag a network socket before closing. +*/ +extern int qtaguid_untagSocket(int sockfd); + +/* + * For the given uid, switch counter sets. + * The kernel only keeps a limited number of sets. + * 2 for now. + */ +extern int qtaguid_setCounterSet(int counterSetNum, uid_t uid); + +/* + * Delete all tag info that relates to the given tag an uid. + * If the tag is 0, then ALL info about the uid is freeded. + * The delete data also affects active tagged socketd, which are + * then untagged. + * The calling process can only operate on its own tags. + * Unless it is part of the happy AID_NET_BW_ACCT group. + * In which case it can clobber everything. + */ +extern int qtaguid_deleteTagData(int tag, uid_t uid); + +/* + * Enable/disable qtaguid functionnality at a lower level. + * When pacified, the kernel will accept commands but do nothing. + */ +extern int qtaguid_setPacifier(int on); + +#ifdef __cplusplus +} +#endif + +#endif /* __CUTILS_QTAG_UID_H */ diff --git a/phonelibs/android_system_core/include/cutils/record_stream.h b/phonelibs/android_system_core/include/cutils/record_stream.h new file mode 100644 index 0000000000..bfac87a53c --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/record_stream.h @@ -0,0 +1,43 @@ +/* + * 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. + */ + +/* + * A simple utility for reading fixed records out of a stream fd + */ + +#ifndef _CUTILS_RECORD_STREAM_H +#define _CUTILS_RECORD_STREAM_H + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef struct RecordStream RecordStream; + +extern RecordStream *record_stream_new(int fd, size_t maxRecordLen); +extern void record_stream_free(RecordStream *p_rs); + +extern int record_stream_get_next (RecordStream *p_rs, void ** p_outRecord, + size_t *p_outRecordLen); + +#ifdef __cplusplus +} +#endif + + +#endif /*_CUTILS_RECORD_STREAM_H*/ + diff --git a/phonelibs/android_system_core/include/cutils/sched_policy.h b/phonelibs/android_system_core/include/cutils/sched_policy.h new file mode 100644 index 0000000000..6a8d570b2c --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/sched_policy.h @@ -0,0 +1,63 @@ +/* + * 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 __CUTILS_SCHED_POLICY_H +#define __CUTILS_SCHED_POLICY_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Keep in sync with THREAD_GROUP_* in frameworks/base/core/java/android/os/Process.java */ +typedef enum { + SP_DEFAULT = -1, + SP_BACKGROUND = 0, + SP_FOREGROUND = 1, + SP_SYSTEM = 2, // can't be used with set_sched_policy() + SP_AUDIO_APP = 3, + SP_AUDIO_SYS = 4, + SP_CNT, + SP_MAX = SP_CNT - 1, + SP_SYSTEM_DEFAULT = SP_FOREGROUND, +} SchedPolicy; + +extern int set_cpuset_policy(int tid, SchedPolicy policy); + +/* Assign thread tid to the cgroup associated with the specified policy. + * If the thread is a thread group leader, that is it's gettid() == getpid(), + * then the other threads in the same thread group are _not_ affected. + * On platforms which support gettid(), zero tid means current thread. + * Return value: 0 for success, or -errno for error. + */ +extern int set_sched_policy(int tid, SchedPolicy policy); + +/* Return the policy associated with the cgroup of thread tid via policy pointer. + * On platforms which support gettid(), zero tid means current thread. + * Return value: 0 for success, or -1 for error and set errno. + */ +extern int get_sched_policy(int tid, SchedPolicy *policy); + +/* Return a displayable string corresponding to policy. + * Return value: non-NULL NUL-terminated name of unspecified length; + * the caller is responsible for displaying the useful part of the string. + */ +extern const char *get_sched_policy_name(SchedPolicy policy); + +#ifdef __cplusplus +} +#endif + +#endif /* __CUTILS_SCHED_POLICY_H */ diff --git a/phonelibs/android_system_core/include/cutils/sockets.h b/phonelibs/android_system_core/include/cutils/sockets.h new file mode 100644 index 0000000000..f8076ca452 --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/sockets.h @@ -0,0 +1,104 @@ +/* + * 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 __CUTILS_SOCKETS_H +#define __CUTILS_SOCKETS_H + +#include +#include +#include +#include +#include + +#ifdef HAVE_WINSOCK +#include +typedef int socklen_t; +#else +#include +#endif + +#define ANDROID_SOCKET_ENV_PREFIX "ANDROID_SOCKET_" +#define ANDROID_SOCKET_DIR "/dev/socket" + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * android_get_control_socket - simple helper function to get the file + * descriptor of our init-managed Unix domain socket. `name' is the name of the + * socket, as given in init.rc. Returns -1 on error. + * + * This is inline and not in libcutils proper because we want to use this in + * third-party daemons with minimal modification. + */ +static inline int android_get_control_socket(const char *name) +{ + char key[64]; + snprintf(key, sizeof(key), ANDROID_SOCKET_ENV_PREFIX "%s", name); + + const char* val = getenv(key); + if (!val) { + return -1; + } + + errno = 0; + int fd = strtol(val, NULL, 10); + if (errno) { + return -1; + } + + return fd; +} + +/* + * See also android.os.LocalSocketAddress.Namespace + */ +// Linux "abstract" (non-filesystem) namespace +#define ANDROID_SOCKET_NAMESPACE_ABSTRACT 0 +// Android "reserved" (/dev/socket) namespace +#define ANDROID_SOCKET_NAMESPACE_RESERVED 1 +// Normal filesystem namespace +#define ANDROID_SOCKET_NAMESPACE_FILESYSTEM 2 + +extern int socket_loopback_client(int port, int type); +extern int socket_network_client(const char *host, int port, int type); +extern int socket_network_client_timeout(const char *host, int port, int type, + int timeout); +extern int socket_loopback_server(int port, int type); +extern int socket_local_server(const char *name, int namespaceId, int type); +extern int socket_local_server_bind(int s, const char *name, int namespaceId); +extern int socket_local_client_connect(int fd, + const char *name, int namespaceId, int type); +extern int socket_local_client(const char *name, int namespaceId, int type); +extern int socket_inaddr_any_server(int port, int type); + +/* + * socket_peer_is_trusted - Takes a socket which is presumed to be a + * connected local socket (e.g. AF_LOCAL) and returns whether the peer + * (the userid that owns the process on the other end of that socket) + * is one of the two trusted userids, root or shell. + * + * Note: This only works as advertised on the Android OS and always + * just returns true when called on other operating systems. + */ +extern bool socket_peer_is_trusted(int fd); + +#ifdef __cplusplus +} +#endif + +#endif /* __CUTILS_SOCKETS_H */ diff --git a/phonelibs/android_system_core/include/cutils/str_parms.h b/phonelibs/android_system_core/include/cutils/str_parms.h new file mode 100644 index 0000000000..aa1435a080 --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/str_parms.h @@ -0,0 +1,60 @@ +/* + * 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 __CUTILS_STR_PARMS_H +#define __CUTILS_STR_PARMS_H + +#include +#include + +__BEGIN_DECLS + +struct str_parms; + +struct str_parms *str_parms_create(void); +struct str_parms *str_parms_create_str(const char *_string); +void str_parms_destroy(struct str_parms *str_parms); + +void str_parms_del(struct str_parms *str_parms, const char *key); + +int str_parms_add_str(struct str_parms *str_parms, const char *key, + const char *value); +int str_parms_add_int(struct str_parms *str_parms, const char *key, int value); + +int str_parms_add_float(struct str_parms *str_parms, const char *key, + float value); + +// Returns non-zero if the str_parms contains the specified key. +int str_parms_has_key(struct str_parms *str_parms, const char *key); + +// Gets value associated with the specified key (if present), placing it in the buffer +// pointed to by the out_val parameter. Returns the length of the returned string value. +// If 'key' isn't in the parms, then return -ENOENT (-2) and leave 'out_val' untouched. +int str_parms_get_str(struct str_parms *str_parms, const char *key, + char *out_val, int len); +int str_parms_get_int(struct str_parms *str_parms, const char *key, + int *out_val); +int str_parms_get_float(struct str_parms *str_parms, const char *key, + float *out_val); + +char *str_parms_to_str(struct str_parms *str_parms); + +/* debug */ +void str_parms_dump(struct str_parms *str_parms); + +__END_DECLS + +#endif /* __CUTILS_STR_PARMS_H */ diff --git a/phonelibs/android_system_core/include/cutils/threads.h b/phonelibs/android_system_core/include/cutils/threads.h new file mode 100644 index 0000000000..5727494079 --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/threads.h @@ -0,0 +1,148 @@ +/* + * 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 _LIBS_CUTILS_THREADS_H +#define _LIBS_CUTILS_THREADS_H + +#include + +#if !defined(_WIN32) +#include +#else +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/***********************************************************************/ +/***********************************************************************/ +/***** *****/ +/***** local thread storage *****/ +/***** *****/ +/***********************************************************************/ +/***********************************************************************/ + +extern pid_t gettid(); + +#if !defined(_WIN32) + +typedef struct { + pthread_mutex_t lock; + int has_tls; + pthread_key_t tls; +} thread_store_t; + +#define THREAD_STORE_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0 } + +#else // !defined(_WIN32) + +typedef struct { + int lock_init; + int has_tls; + DWORD tls; + CRITICAL_SECTION lock; +} thread_store_t; + +#define THREAD_STORE_INITIALIZER { 0, 0, 0, {0, 0, 0, 0, 0, 0} } + +#endif // !defined(_WIN32) + +typedef void (*thread_store_destruct_t)(void* value); + +extern void* thread_store_get(thread_store_t* store); + +extern void thread_store_set(thread_store_t* store, + void* value, + thread_store_destruct_t destroy); + +/***********************************************************************/ +/***********************************************************************/ +/***** *****/ +/***** mutexes *****/ +/***** *****/ +/***********************************************************************/ +/***********************************************************************/ + +#if !defined(_WIN32) + +typedef pthread_mutex_t mutex_t; + +#define MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER + +static __inline__ void mutex_lock(mutex_t* lock) +{ + pthread_mutex_lock(lock); +} +static __inline__ void mutex_unlock(mutex_t* lock) +{ + pthread_mutex_unlock(lock); +} +static __inline__ int mutex_init(mutex_t* lock) +{ + return pthread_mutex_init(lock, NULL); +} +static __inline__ void mutex_destroy(mutex_t* lock) +{ + pthread_mutex_destroy(lock); +} + +#else // !defined(_WIN32) + +typedef struct { + int init; + CRITICAL_SECTION lock[1]; +} mutex_t; + +#define MUTEX_INITIALIZER { 0, {{ NULL, 0, 0, NULL, NULL, 0 }} } + +static __inline__ void mutex_lock(mutex_t* lock) +{ + if (!lock->init) { + lock->init = 1; + InitializeCriticalSection( lock->lock ); + lock->init = 2; + } else while (lock->init != 2) + Sleep(10); + + EnterCriticalSection(lock->lock); +} + +static __inline__ void mutex_unlock(mutex_t* lock) +{ + LeaveCriticalSection(lock->lock); +} +static __inline__ int mutex_init(mutex_t* lock) +{ + InitializeCriticalSection(lock->lock); + lock->init = 2; + return 0; +} +static __inline__ void mutex_destroy(mutex_t* lock) +{ + if (lock->init) { + lock->init = 0; + DeleteCriticalSection(lock->lock); + } +} +#endif // !defined(_WIN32) + +#ifdef __cplusplus +} +#endif + +#endif /* _LIBS_CUTILS_THREADS_H */ diff --git a/phonelibs/android_system_core/include/cutils/trace.h b/phonelibs/android_system_core/include/cutils/trace.h new file mode 100644 index 0000000000..e4ed17983d --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/trace.h @@ -0,0 +1,252 @@ +/* + * 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 _LIBS_CUTILS_TRACE_H +#define _LIBS_CUTILS_TRACE_H + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +__BEGIN_DECLS + +/** + * The ATRACE_TAG macro can be defined before including this header to trace + * using one of the tags defined below. It must be defined to one of the + * following ATRACE_TAG_* macros. The trace tag is used to filter tracing in + * userland to avoid some of the runtime cost of tracing when it is not desired. + * + * Defining ATRACE_TAG to be ATRACE_TAG_ALWAYS will result in the tracing always + * being enabled - this should ONLY be done for debug code, as userland tracing + * has a performance cost even when the trace is not being recorded. Defining + * ATRACE_TAG to be ATRACE_TAG_NEVER or leaving ATRACE_TAG undefined will result + * in the tracing always being disabled. + * + * ATRACE_TAG_HAL should be bitwise ORed with the relevant tags for tracing + * within a hardware module. For example a camera hardware module would set: + * #define ATRACE_TAG (ATRACE_TAG_CAMERA | ATRACE_TAG_HAL) + * + * Keep these in sync with frameworks/base/core/java/android/os/Trace.java. + */ +#define ATRACE_TAG_NEVER 0 // This tag is never enabled. +#define ATRACE_TAG_ALWAYS (1<<0) // This tag is always enabled. +#define ATRACE_TAG_GRAPHICS (1<<1) +#define ATRACE_TAG_INPUT (1<<2) +#define ATRACE_TAG_VIEW (1<<3) +#define ATRACE_TAG_WEBVIEW (1<<4) +#define ATRACE_TAG_WINDOW_MANAGER (1<<5) +#define ATRACE_TAG_ACTIVITY_MANAGER (1<<6) +#define ATRACE_TAG_SYNC_MANAGER (1<<7) +#define ATRACE_TAG_AUDIO (1<<8) +#define ATRACE_TAG_VIDEO (1<<9) +#define ATRACE_TAG_CAMERA (1<<10) +#define ATRACE_TAG_HAL (1<<11) +#define ATRACE_TAG_APP (1<<12) +#define ATRACE_TAG_RESOURCES (1<<13) +#define ATRACE_TAG_DALVIK (1<<14) +#define ATRACE_TAG_RS (1<<15) +#define ATRACE_TAG_BIONIC (1<<16) +#define ATRACE_TAG_POWER (1<<17) +#define ATRACE_TAG_LAST ATRACE_TAG_POWER + +// Reserved for initialization. +#define ATRACE_TAG_NOT_READY (1LL<<63) + +#define ATRACE_TAG_VALID_MASK ((ATRACE_TAG_LAST - 1) | ATRACE_TAG_LAST) + +#ifndef ATRACE_TAG +#define ATRACE_TAG ATRACE_TAG_NEVER +#elif ATRACE_TAG > ATRACE_TAG_VALID_MASK +#error ATRACE_TAG must be defined to be one of the tags defined in cutils/trace.h +#endif + +/** + * Opens the trace file for writing and reads the property for initial tags. + * The atrace.tags.enableflags property sets the tags to trace. + * This function should not be explicitly called, the first call to any normal + * trace function will cause it to be run safely. + */ +void atrace_setup(); + +/** + * If tracing is ready, set atrace_enabled_tags to the system property + * debug.atrace.tags.enableflags. Can be used as a sysprop change callback. + */ +void atrace_update_tags(); + +/** + * Set whether the process is debuggable. By default the process is not + * considered debuggable. If the process is not debuggable then application- + * level tracing is not allowed unless the ro.debuggable system property is + * set to '1'. + */ +void atrace_set_debuggable(bool debuggable); + +/** + * Set whether tracing is enabled for the current process. This is used to + * prevent tracing within the Zygote process. + */ +void atrace_set_tracing_enabled(bool enabled); + +/** + * Flag indicating whether setup has been completed, initialized to 0. + * Nonzero indicates setup has completed. + * Note: This does NOT indicate whether or not setup was successful. + */ +extern atomic_bool atrace_is_ready; + +/** + * Set of ATRACE_TAG flags to trace for, initialized to ATRACE_TAG_NOT_READY. + * A value of zero indicates setup has failed. + * Any other nonzero value indicates setup has succeeded, and tracing is on. + */ +extern uint64_t atrace_enabled_tags; + +/** + * Handle to the kernel's trace buffer, initialized to -1. + * Any other value indicates setup has succeeded, and is a valid fd for tracing. + */ +extern int atrace_marker_fd; + +/** + * atrace_init readies the process for tracing by opening the trace_marker file. + * Calling any trace function causes this to be run, so calling it is optional. + * This can be explicitly run to avoid setup delay on first trace function. + */ +#define ATRACE_INIT() atrace_init() +static inline void atrace_init() +{ + if (CC_UNLIKELY(!atomic_load_explicit(&atrace_is_ready, memory_order_acquire))) { + atrace_setup(); + } +} + +/** + * Get the mask of all tags currently enabled. + * It can be used as a guard condition around more expensive trace calculations. + * Every trace function calls this, which ensures atrace_init is run. + */ +#define ATRACE_GET_ENABLED_TAGS() atrace_get_enabled_tags() +static inline uint64_t atrace_get_enabled_tags() +{ + atrace_init(); + return atrace_enabled_tags; +} + +/** + * Test if a given tag is currently enabled. + * Returns nonzero if the tag is enabled, otherwise zero. + * It can be used as a guard condition around more expensive trace calculations. + */ +#define ATRACE_ENABLED() atrace_is_tag_enabled(ATRACE_TAG) +static inline uint64_t atrace_is_tag_enabled(uint64_t tag) +{ + return atrace_get_enabled_tags() & tag; +} + +/** + * Trace the beginning of a context. name is used to identify the context. + * This is often used to time function execution. + */ +#define ATRACE_BEGIN(name) atrace_begin(ATRACE_TAG, name) +static inline void atrace_begin(uint64_t tag, const char* name) +{ + if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) { + void atrace_begin_body(const char*); + atrace_begin_body(name); + } +} + +/** + * Trace the end of a context. + * This should match up (and occur after) a corresponding ATRACE_BEGIN. + */ +#define ATRACE_END() atrace_end(ATRACE_TAG) +static inline void atrace_end(uint64_t tag) +{ + if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) { + char c = 'E'; + write(atrace_marker_fd, &c, 1); + } +} + +/** + * Trace the beginning of an asynchronous event. Unlike ATRACE_BEGIN/ATRACE_END + * contexts, asynchronous events do not need to be nested. The name describes + * the event, and the cookie provides a unique identifier for distinguishing + * simultaneous events. The name and cookie used to begin an event must be + * used to end it. + */ +#define ATRACE_ASYNC_BEGIN(name, cookie) \ + atrace_async_begin(ATRACE_TAG, name, cookie) +static inline void atrace_async_begin(uint64_t tag, const char* name, + int32_t cookie) +{ + if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) { + void atrace_async_begin_body(const char*, int32_t); + atrace_async_begin_body(name, cookie); + } +} + +/** + * Trace the end of an asynchronous event. + * This should have a corresponding ATRACE_ASYNC_BEGIN. + */ +#define ATRACE_ASYNC_END(name, cookie) atrace_async_end(ATRACE_TAG, name, cookie) +static inline void atrace_async_end(uint64_t tag, const char* name, int32_t cookie) +{ + if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) { + void atrace_async_end_body(const char*, int32_t); + atrace_async_end_body(name, cookie); + } +} + +/** + * Traces an integer counter value. name is used to identify the counter. + * This can be used to track how a value changes over time. + */ +#define ATRACE_INT(name, value) atrace_int(ATRACE_TAG, name, value) +static inline void atrace_int(uint64_t tag, const char* name, int32_t value) +{ + if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) { + void atrace_int_body(const char*, int32_t); + atrace_int_body(name, value); + } +} + +/** + * Traces a 64-bit integer counter value. name is used to identify the + * counter. This can be used to track how a value changes over time. + */ +#define ATRACE_INT64(name, value) atrace_int64(ATRACE_TAG, name, value) +static inline void atrace_int64(uint64_t tag, const char* name, int64_t value) +{ + if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) { + void atrace_int64_body(const char*, int64_t); + atrace_int64_body(name, value); + } +} + +__END_DECLS + +#endif // _LIBS_CUTILS_TRACE_H diff --git a/phonelibs/android_system_core/include/cutils/uevent.h b/phonelibs/android_system_core/include/cutils/uevent.h new file mode 100644 index 0000000000..da1c2aae6b --- /dev/null +++ b/phonelibs/android_system_core/include/cutils/uevent.h @@ -0,0 +1,36 @@ +/* + * 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 __CUTILS_UEVENT_H +#define __CUTILS_UEVENT_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +int uevent_open_socket(int buf_sz, bool passcred); +ssize_t uevent_kernel_multicast_recv(int socket, void *buffer, size_t length); +ssize_t uevent_kernel_multicast_uid_recv(int socket, void *buffer, size_t length, uid_t *uid); +ssize_t uevent_kernel_recv(int socket, void *buffer, size_t length, bool require_group, uid_t *uid); + +#ifdef __cplusplus +} +#endif + +#endif /* __CUTILS_UEVENT_H */ diff --git a/phonelibs/android_system_core/include/log/event_tag_map.h b/phonelibs/android_system_core/include/log/event_tag_map.h new file mode 100644 index 0000000000..1653c61e9a --- /dev/null +++ b/phonelibs/android_system_core/include/log/event_tag_map.h @@ -0,0 +1,50 @@ +/* + * 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 _LIBS_CUTILS_EVENTTAGMAP_H +#define _LIBS_CUTILS_EVENTTAGMAP_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define EVENT_TAG_MAP_FILE "/system/etc/event-log-tags" + +struct EventTagMap; +typedef struct EventTagMap EventTagMap; + +/* + * Open the specified file as an event log tag map. + * + * Returns NULL on failure. + */ +EventTagMap* android_openEventTagMap(const char* fileName); + +/* + * Close the map. + */ +void android_closeEventTagMap(EventTagMap* map); + +/* + * Look up a tag by index. Returns the tag string, or NULL if not found. + */ +const char* android_lookupEventTag(const EventTagMap* map, int tag); + +#ifdef __cplusplus +} +#endif + +#endif /*_LIBS_CUTILS_EVENTTAGMAP_H*/ diff --git a/phonelibs/android_system_core/include/log/log.h b/phonelibs/android_system_core/include/log/log.h new file mode 100644 index 0000000000..63a441a689 --- /dev/null +++ b/phonelibs/android_system_core/include/log/log.h @@ -0,0 +1,642 @@ +/* + * Copyright (C) 2005-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. + */ + +// +// C/C++ logging functions. See the logging documentation for API details. +// +// We'd like these to be available from C code (in case we import some from +// somewhere), so this has a C interface. +// +// The output will be correct when the log file is shared between multiple +// threads and/or multiple processes so long as the operating system +// supports O_APPEND. These calls have mutex-protected data structures +// and so are NOT reentrant. Do not use LOG in a signal handler. +// +#ifndef _LIBS_LOG_LOG_H +#define _LIBS_LOG_LOG_H + +#include +#include +#include +#include +#include + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// --------------------------------------------------------------------- + +/* + * Normally we strip ALOGV (VERBOSE messages) from release builds. + * You can modify this (for example with "#define LOG_NDEBUG 0" + * at the top of your source file) to change that behavior. + */ +#ifndef LOG_NDEBUG +#ifdef NDEBUG +#define LOG_NDEBUG 1 +#else +#define LOG_NDEBUG 0 +#endif +#endif + +/* + * This is the local tag used for the following simplified + * logging macros. You can change this preprocessor definition + * before using the other macros to change the tag. + */ +#ifndef LOG_TAG +#define LOG_TAG NULL +#endif + +// --------------------------------------------------------------------- + +#ifndef __predict_false +#define __predict_false(exp) __builtin_expect((exp) != 0, 0) +#endif + +/* + * -DLINT_RLOG in sources that you want to enforce that all logging + * goes to the radio log buffer. If any logging goes to any of the other + * log buffers, there will be a compile or link error to highlight the + * problem. This is not a replacement for a full audit of the code since + * this only catches compiled code, not ifdef'd debug code. Options to + * defining this, either temporarily to do a spot check, or permanently + * to enforce, in all the communications trees; We have hopes to ensure + * that by supplying just the radio log buffer that the communications + * teams will have their one-stop shop for triaging issues. + */ +#ifndef LINT_RLOG + +/* + * Simplified macro to send a verbose log message using the current LOG_TAG. + */ +#ifndef ALOGV +#define __ALOGV(...) ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) +#if LOG_NDEBUG +#define ALOGV(...) do { if (0) { __ALOGV(__VA_ARGS__); } } while (0) +#else +#define ALOGV(...) __ALOGV(__VA_ARGS__) +#endif +#endif + +#ifndef ALOGV_IF +#if LOG_NDEBUG +#define ALOGV_IF(cond, ...) ((void)0) +#else +#define ALOGV_IF(cond, ...) \ + ( (__predict_false(cond)) \ + ? ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) \ + : (void)0 ) +#endif +#endif + +/* + * Simplified macro to send a debug log message using the current LOG_TAG. + */ +#ifndef ALOGD +#define ALOGD(...) ((void)ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)) +#endif + +#ifndef ALOGD_IF +#define ALOGD_IF(cond, ...) \ + ( (__predict_false(cond)) \ + ? ((void)ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)) \ + : (void)0 ) +#endif + +/* + * Simplified macro to send an info log message using the current LOG_TAG. + */ +#ifndef ALOGI +#define ALOGI(...) ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__)) +#endif + +#ifndef ALOGI_IF +#define ALOGI_IF(cond, ...) \ + ( (__predict_false(cond)) \ + ? ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__)) \ + : (void)0 ) +#endif + +/* + * Simplified macro to send a warning log message using the current LOG_TAG. + */ +#ifndef ALOGW +#define ALOGW(...) ((void)ALOG(LOG_WARN, LOG_TAG, __VA_ARGS__)) +#endif + +#ifndef ALOGW_IF +#define ALOGW_IF(cond, ...) \ + ( (__predict_false(cond)) \ + ? ((void)ALOG(LOG_WARN, LOG_TAG, __VA_ARGS__)) \ + : (void)0 ) +#endif + +/* + * Simplified macro to send an error log message using the current LOG_TAG. + */ +#ifndef ALOGE +#define ALOGE(...) ((void)ALOG(LOG_ERROR, LOG_TAG, __VA_ARGS__)) +#endif + +#ifndef ALOGE_IF +#define ALOGE_IF(cond, ...) \ + ( (__predict_false(cond)) \ + ? ((void)ALOG(LOG_ERROR, LOG_TAG, __VA_ARGS__)) \ + : (void)0 ) +#endif + +// --------------------------------------------------------------------- + +/* + * Conditional based on whether the current LOG_TAG is enabled at + * verbose priority. + */ +#ifndef IF_ALOGV +#if LOG_NDEBUG +#define IF_ALOGV() if (false) +#else +#define IF_ALOGV() IF_ALOG(LOG_VERBOSE, LOG_TAG) +#endif +#endif + +/* + * Conditional based on whether the current LOG_TAG is enabled at + * debug priority. + */ +#ifndef IF_ALOGD +#define IF_ALOGD() IF_ALOG(LOG_DEBUG, LOG_TAG) +#endif + +/* + * Conditional based on whether the current LOG_TAG is enabled at + * info priority. + */ +#ifndef IF_ALOGI +#define IF_ALOGI() IF_ALOG(LOG_INFO, LOG_TAG) +#endif + +/* + * Conditional based on whether the current LOG_TAG is enabled at + * warn priority. + */ +#ifndef IF_ALOGW +#define IF_ALOGW() IF_ALOG(LOG_WARN, LOG_TAG) +#endif + +/* + * Conditional based on whether the current LOG_TAG is enabled at + * error priority. + */ +#ifndef IF_ALOGE +#define IF_ALOGE() IF_ALOG(LOG_ERROR, LOG_TAG) +#endif + + +// --------------------------------------------------------------------- + +/* + * Simplified macro to send a verbose system log message using the current LOG_TAG. + */ +#ifndef SLOGV +#define __SLOGV(...) \ + ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) +#if LOG_NDEBUG +#define SLOGV(...) do { if (0) { __SLOGV(__VA_ARGS__); } } while (0) +#else +#define SLOGV(...) __SLOGV(__VA_ARGS__) +#endif +#endif + +#ifndef SLOGV_IF +#if LOG_NDEBUG +#define SLOGV_IF(cond, ...) ((void)0) +#else +#define SLOGV_IF(cond, ...) \ + ( (__predict_false(cond)) \ + ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) \ + : (void)0 ) +#endif +#endif + +/* + * Simplified macro to send a debug system log message using the current LOG_TAG. + */ +#ifndef SLOGD +#define SLOGD(...) \ + ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)) +#endif + +#ifndef SLOGD_IF +#define SLOGD_IF(cond, ...) \ + ( (__predict_false(cond)) \ + ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)) \ + : (void)0 ) +#endif + +/* + * Simplified macro to send an info system log message using the current LOG_TAG. + */ +#ifndef SLOGI +#define SLOGI(...) \ + ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)) +#endif + +#ifndef SLOGI_IF +#define SLOGI_IF(cond, ...) \ + ( (__predict_false(cond)) \ + ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)) \ + : (void)0 ) +#endif + +/* + * Simplified macro to send a warning system log message using the current LOG_TAG. + */ +#ifndef SLOGW +#define SLOGW(...) \ + ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)) +#endif + +#ifndef SLOGW_IF +#define SLOGW_IF(cond, ...) \ + ( (__predict_false(cond)) \ + ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)) \ + : (void)0 ) +#endif + +/* + * Simplified macro to send an error system log message using the current LOG_TAG. + */ +#ifndef SLOGE +#define SLOGE(...) \ + ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)) +#endif + +#ifndef SLOGE_IF +#define SLOGE_IF(cond, ...) \ + ( (__predict_false(cond)) \ + ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)) \ + : (void)0 ) +#endif + +#endif /* !LINT_RLOG */ + +// --------------------------------------------------------------------- + +/* + * Simplified macro to send a verbose radio log message using the current LOG_TAG. + */ +#ifndef RLOGV +#define __RLOGV(...) \ + ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) +#if LOG_NDEBUG +#define RLOGV(...) do { if (0) { __RLOGV(__VA_ARGS__); } } while (0) +#else +#define RLOGV(...) __RLOGV(__VA_ARGS__) +#endif +#endif + +#ifndef RLOGV_IF +#if LOG_NDEBUG +#define RLOGV_IF(cond, ...) ((void)0) +#else +#define RLOGV_IF(cond, ...) \ + ( (__predict_false(cond)) \ + ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) \ + : (void)0 ) +#endif +#endif + +/* + * Simplified macro to send a debug radio log message using the current LOG_TAG. + */ +#ifndef RLOGD +#define RLOGD(...) \ + ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)) +#endif + +#ifndef RLOGD_IF +#define RLOGD_IF(cond, ...) \ + ( (__predict_false(cond)) \ + ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)) \ + : (void)0 ) +#endif + +/* + * Simplified macro to send an info radio log message using the current LOG_TAG. + */ +#ifndef RLOGI +#define RLOGI(...) \ + ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)) +#endif + +#ifndef RLOGI_IF +#define RLOGI_IF(cond, ...) \ + ( (__predict_false(cond)) \ + ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)) \ + : (void)0 ) +#endif + +/* + * Simplified macro to send a warning radio log message using the current LOG_TAG. + */ +#ifndef RLOGW +#define RLOGW(...) \ + ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)) +#endif + +#ifndef RLOGW_IF +#define RLOGW_IF(cond, ...) \ + ( (__predict_false(cond)) \ + ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)) \ + : (void)0 ) +#endif + +/* + * Simplified macro to send an error radio log message using the current LOG_TAG. + */ +#ifndef RLOGE +#define RLOGE(...) \ + ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)) +#endif + +#ifndef RLOGE_IF +#define RLOGE_IF(cond, ...) \ + ( (__predict_false(cond)) \ + ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)) \ + : (void)0 ) +#endif + + +// --------------------------------------------------------------------- + +/* + * Log a fatal error. If the given condition fails, this stops program + * execution like a normal assertion, but also generating the given message. + * It is NOT stripped from release builds. Note that the condition test + * is -inverted- from the normal assert() semantics. + */ +#ifndef LOG_ALWAYS_FATAL_IF +#define LOG_ALWAYS_FATAL_IF(cond, ...) \ + ( (__predict_false(cond)) \ + ? ((void)android_printAssert(#cond, LOG_TAG, ## __VA_ARGS__)) \ + : (void)0 ) +#endif + +#ifndef LOG_ALWAYS_FATAL +#define LOG_ALWAYS_FATAL(...) \ + ( ((void)android_printAssert(NULL, LOG_TAG, ## __VA_ARGS__)) ) +#endif + +/* + * Versions of LOG_ALWAYS_FATAL_IF and LOG_ALWAYS_FATAL that + * are stripped out of release builds. + */ +#if LOG_NDEBUG + +#ifndef LOG_FATAL_IF +#define LOG_FATAL_IF(cond, ...) ((void)0) +#endif +#ifndef LOG_FATAL +#define LOG_FATAL(...) ((void)0) +#endif + +#else + +#ifndef LOG_FATAL_IF +#define LOG_FATAL_IF(cond, ...) LOG_ALWAYS_FATAL_IF(cond, ## __VA_ARGS__) +#endif +#ifndef LOG_FATAL +#define LOG_FATAL(...) LOG_ALWAYS_FATAL(__VA_ARGS__) +#endif + +#endif + +/* + * Assertion that generates a log message when the assertion fails. + * Stripped out of release builds. Uses the current LOG_TAG. + */ +#ifndef ALOG_ASSERT +#define ALOG_ASSERT(cond, ...) LOG_FATAL_IF(!(cond), ## __VA_ARGS__) +//#define ALOG_ASSERT(cond) LOG_FATAL_IF(!(cond), "Assertion failed: " #cond) +#endif + +// --------------------------------------------------------------------- + +/* + * Basic log message macro. + * + * Example: + * ALOG(LOG_WARN, NULL, "Failed with error %d", errno); + * + * The second argument may be NULL or "" to indicate the "global" tag. + */ +#ifndef ALOG +#define ALOG(priority, tag, ...) \ + LOG_PRI(ANDROID_##priority, tag, __VA_ARGS__) +#endif + +/* + * Log macro that allows you to specify a number for the priority. + */ +#ifndef LOG_PRI +#define LOG_PRI(priority, tag, ...) \ + android_printLog(priority, tag, __VA_ARGS__) +#endif + +/* + * Log macro that allows you to pass in a varargs ("args" is a va_list). + */ +#ifndef LOG_PRI_VA +#define LOG_PRI_VA(priority, tag, fmt, args) \ + android_vprintLog(priority, NULL, tag, fmt, args) +#endif + +/* + * Conditional given a desired logging priority and tag. + */ +#ifndef IF_ALOG +#define IF_ALOG(priority, tag) \ + if (android_testLog(ANDROID_##priority, tag)) +#endif + +// --------------------------------------------------------------------- + +/* + * Event logging. + */ + +/* + * Event log entry types. These must match up with the declarations in + * java/android/android/util/EventLog.java. + */ +typedef enum { + EVENT_TYPE_INT = 0, + EVENT_TYPE_LONG = 1, + EVENT_TYPE_STRING = 2, + EVENT_TYPE_LIST = 3, + EVENT_TYPE_FLOAT = 4, +} AndroidEventLogType; +#define sizeof_AndroidEventLogType sizeof(typeof_AndroidEventLogType) +#define typeof_AndroidEventLogType unsigned char + +#ifndef LOG_EVENT_INT +#define LOG_EVENT_INT(_tag, _value) { \ + int intBuf = _value; \ + (void) android_btWriteLog(_tag, EVENT_TYPE_INT, &intBuf, \ + sizeof(intBuf)); \ + } +#endif +#ifndef LOG_EVENT_LONG +#define LOG_EVENT_LONG(_tag, _value) { \ + long long longBuf = _value; \ + (void) android_btWriteLog(_tag, EVENT_TYPE_LONG, &longBuf, \ + sizeof(longBuf)); \ + } +#endif +#ifndef LOG_EVENT_FLOAT +#define LOG_EVENT_FLOAT(_tag, _value) { \ + float floatBuf = _value; \ + (void) android_btWriteLog(_tag, EVENT_TYPE_FLOAT, &floatBuf, \ + sizeof(floatBuf)); \ + } +#endif +#ifndef LOG_EVENT_STRING +#define LOG_EVENT_STRING(_tag, _value) \ + (void) __android_log_bswrite(_tag, _value); +#endif +/* TODO: something for LIST */ + +/* + * =========================================================================== + * + * The stuff in the rest of this file should not be used directly. + */ + +#define android_printLog(prio, tag, fmt...) \ + __android_log_print(prio, tag, fmt) + +#define android_vprintLog(prio, cond, tag, fmt...) \ + __android_log_vprint(prio, tag, fmt) + +/* XXX Macros to work around syntax errors in places where format string + * arg is not passed to ALOG_ASSERT, LOG_ALWAYS_FATAL or LOG_ALWAYS_FATAL_IF + * (happens only in debug builds). + */ + +/* Returns 2nd arg. Used to substitute default value if caller's vararg list + * is empty. + */ +#define __android_second(dummy, second, ...) second + +/* If passed multiple args, returns ',' followed by all but 1st arg, otherwise + * returns nothing. + */ +#define __android_rest(first, ...) , ## __VA_ARGS__ + +#define android_printAssert(cond, tag, fmt...) \ + __android_log_assert(cond, tag, \ + __android_second(0, ## fmt, NULL) __android_rest(fmt)) + +#define android_writeLog(prio, tag, text) \ + __android_log_write(prio, tag, text) + +#define android_bWriteLog(tag, payload, len) \ + __android_log_bwrite(tag, payload, len) +#define android_btWriteLog(tag, type, payload, len) \ + __android_log_btwrite(tag, type, payload, len) + +#define android_errorWriteLog(tag, subTag) \ + __android_log_error_write(tag, subTag, -1, NULL, 0) + +#define android_errorWriteWithInfoLog(tag, subTag, uid, data, dataLen) \ + __android_log_error_write(tag, subTag, uid, data, dataLen) + +/* + * IF_ALOG uses android_testLog, but IF_ALOG can be overridden. + * android_testLog will remain constant in its purpose as a wrapper + * for Android logging filter policy, and can be subject to + * change. It can be reused by the developers that override + * IF_ALOG as a convenient means to reimplement their policy + * over Android. + */ +#if LOG_NDEBUG /* Production */ +#define android_testLog(prio, tag) \ + (__android_log_is_loggable(prio, tag, ANDROID_LOG_DEBUG) != 0) +#else +#define android_testLog(prio, tag) \ + (__android_log_is_loggable(prio, tag, ANDROID_LOG_VERBOSE) != 0) +#endif + +// TODO: remove these prototypes and their users +#define android_writevLog(vec,num) do{}while(0) +#define android_write1Log(str,len) do{}while (0) +#define android_setMinPriority(tag, prio) do{}while(0) +//#define android_logToCallback(func) do{}while(0) +#define android_logToFile(tag, file) (0) +#define android_logToFd(tag, fd) (0) + +#ifndef log_id_t_defined +#define log_id_t_defined + +typedef enum log_id { + LOG_ID_MIN = 0, + +#ifndef LINT_RLOG + LOG_ID_MAIN = 0, +#endif + LOG_ID_RADIO = 1, +#ifndef LINT_RLOG + LOG_ID_EVENTS = 2, + LOG_ID_SYSTEM = 3, + LOG_ID_CRASH = 4, + LOG_ID_KERNEL = 5, +#endif + + LOG_ID_MAX +} log_id_t; +#endif +#define sizeof_log_id_t sizeof(typeof_log_id_t) +#define typeof_log_id_t unsigned char + +/* + * Use the per-tag properties "log.tag." to generate a runtime + * result of non-zero to expose a log. + */ +int __android_log_is_loggable(int prio, const char *tag, int def); + +int __android_log_error_write(int tag, const char *subTag, int32_t uid, const char *data, + uint32_t dataLen); + +/* + * Send a simple string to the log. + */ +int __android_log_buf_write(int bufID, int prio, const char *tag, const char *text); +int __android_log_buf_print(int bufID, int prio, const char *tag, const char *fmt, ...) +#if defined(__GNUC__) + __attribute__((__format__(printf, 4, 5))) +#endif + ; + +#ifdef __cplusplus +} +#endif + +#endif /* _LIBS_LOG_LOG_H */ diff --git a/phonelibs/android_system_core/include/log/log_read.h b/phonelibs/android_system_core/include/log/log_read.h new file mode 100644 index 0000000000..1b70affc35 --- /dev/null +++ b/phonelibs/android_system_core/include/log/log_read.h @@ -0,0 +1,170 @@ +/* + * Copyright (C) 2013-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 _LIBS_LOG_LOG_READ_H +#define _LIBS_LOG_LOG_READ_H + +#include +#include + +/* struct log_time is a wire-format variant of struct timespec */ +#define NS_PER_SEC 1000000000ULL + +#ifdef __cplusplus + +// NB: do NOT define a copy constructor. This will result in structure +// no longer being compatible with pass-by-value which is desired +// efficient behavior. Also, pass-by-reference breaks C/C++ ABI. +struct log_time { +public: + uint32_t tv_sec; // good to Feb 5 2106 + uint32_t tv_nsec; + + static const uint32_t tv_sec_max = 0xFFFFFFFFUL; + static const uint32_t tv_nsec_max = 999999999UL; + + log_time(const timespec &T) + { + tv_sec = T.tv_sec; + tv_nsec = T.tv_nsec; + } + log_time(uint32_t sec, uint32_t nsec) + { + tv_sec = sec; + tv_nsec = nsec; + } + static const timespec EPOCH; + log_time() + { + } + log_time(clockid_t id) + { + timespec T; + clock_gettime(id, &T); + tv_sec = T.tv_sec; + tv_nsec = T.tv_nsec; + } + log_time(const char *T) + { + const uint8_t *c = (const uint8_t *) T; + tv_sec = c[0] | (c[1] << 8) | (c[2] << 16) | (c[3] << 24); + tv_nsec = c[4] | (c[5] << 8) | (c[6] << 16) | (c[7] << 24); + } + + // timespec + bool operator== (const timespec &T) const + { + return (tv_sec == static_cast(T.tv_sec)) + && (tv_nsec == static_cast(T.tv_nsec)); + } + bool operator!= (const timespec &T) const + { + return !(*this == T); + } + bool operator< (const timespec &T) const + { + return (tv_sec < static_cast(T.tv_sec)) + || ((tv_sec == static_cast(T.tv_sec)) + && (tv_nsec < static_cast(T.tv_nsec))); + } + bool operator>= (const timespec &T) const + { + return !(*this < T); + } + bool operator> (const timespec &T) const + { + return (tv_sec > static_cast(T.tv_sec)) + || ((tv_sec == static_cast(T.tv_sec)) + && (tv_nsec > static_cast(T.tv_nsec))); + } + bool operator<= (const timespec &T) const + { + return !(*this > T); + } + log_time operator-= (const timespec &T); + log_time operator- (const timespec &T) const + { + log_time local(*this); + return local -= T; + } + log_time operator+= (const timespec &T); + log_time operator+ (const timespec &T) const + { + log_time local(*this); + return local += T; + } + + // log_time + bool operator== (const log_time &T) const + { + return (tv_sec == T.tv_sec) && (tv_nsec == T.tv_nsec); + } + bool operator!= (const log_time &T) const + { + return !(*this == T); + } + bool operator< (const log_time &T) const + { + return (tv_sec < T.tv_sec) + || ((tv_sec == T.tv_sec) && (tv_nsec < T.tv_nsec)); + } + bool operator>= (const log_time &T) const + { + return !(*this < T); + } + bool operator> (const log_time &T) const + { + return (tv_sec > T.tv_sec) + || ((tv_sec == T.tv_sec) && (tv_nsec > T.tv_nsec)); + } + bool operator<= (const log_time &T) const + { + return !(*this > T); + } + log_time operator-= (const log_time &T); + log_time operator- (const log_time &T) const + { + log_time local(*this); + return local -= T; + } + log_time operator+= (const log_time &T); + log_time operator+ (const log_time &T) const + { + log_time local(*this); + return local += T; + } + + uint64_t nsec() const + { + return static_cast(tv_sec) * NS_PER_SEC + tv_nsec; + } + + static const char default_format[]; + + // Add %#q for the fraction of a second to the standard library functions + char *strptime(const char *s, const char *format = default_format); +} __attribute__((__packed__)); + +#else + +typedef struct log_time { + uint32_t tv_sec; + uint32_t tv_nsec; +} __attribute__((__packed__)) log_time; + +#endif + +#endif /* define _LIBS_LOG_LOG_READ_H */ diff --git a/phonelibs/android_system_core/include/log/logd.h b/phonelibs/android_system_core/include/log/logd.h new file mode 100644 index 0000000000..0fe515f2ab --- /dev/null +++ b/phonelibs/android_system_core/include/log/logd.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _ANDROID_CUTILS_LOGD_H +#define _ANDROID_CUTILS_LOGD_H + +/* the stable/frozen log-related definitions have been + * moved to this header, which is exposed by the NDK + */ +#include + +/* the rest is only used internally by the system */ +#if !defined(_WIN32) +#include +#endif +#include +#include +#include +#include +#include +#include + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +int __android_log_bwrite(int32_t tag, const void *payload, size_t len); +int __android_log_btwrite(int32_t tag, char type, const void *payload, + size_t len); +int __android_log_bswrite(int32_t tag, const char *payload); + +#ifdef __cplusplus +} +#endif + +#endif /* _LOGD_H */ diff --git a/phonelibs/android_system_core/include/log/logger.h b/phonelibs/android_system_core/include/log/logger.h new file mode 100644 index 0000000000..f030dab5a9 --- /dev/null +++ b/phonelibs/android_system_core/include/log/logger.h @@ -0,0 +1,196 @@ +/* +** +** Copyright 2007-2014, The Android Open Source Project +** +** This file is dual licensed. It may be redistributed and/or modified +** under the terms of the Apache 2.0 License OR version 2 of the GNU +** General Public License. +*/ + +#ifndef _LIBS_LOG_LOGGER_H +#define _LIBS_LOG_LOGGER_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * The userspace structure for version 1 of the logger_entry ABI. + * This structure is returned to userspace by the kernel logger + * driver unless an upgrade to a newer ABI version is requested. + */ +struct logger_entry { + uint16_t len; /* length of the payload */ + uint16_t __pad; /* no matter what, we get 2 bytes of padding */ + int32_t pid; /* generating process's pid */ + int32_t tid; /* generating process's tid */ + int32_t sec; /* seconds since Epoch */ + int32_t nsec; /* nanoseconds */ + char msg[0]; /* the entry's payload */ +} __attribute__((__packed__)); + +/* + * The userspace structure for version 2 of the logger_entry ABI. + * This structure is returned to userspace if ioctl(LOGGER_SET_VERSION) + * is called with version==2; or used with the user space log daemon. + */ +struct logger_entry_v2 { + uint16_t len; /* length of the payload */ + uint16_t hdr_size; /* sizeof(struct logger_entry_v2) */ + int32_t pid; /* generating process's pid */ + int32_t tid; /* generating process's tid */ + int32_t sec; /* seconds since Epoch */ + int32_t nsec; /* nanoseconds */ + uint32_t euid; /* effective UID of logger */ + char msg[0]; /* the entry's payload */ +} __attribute__((__packed__)); + +struct logger_entry_v3 { + uint16_t len; /* length of the payload */ + uint16_t hdr_size; /* sizeof(struct logger_entry_v3) */ + int32_t pid; /* generating process's pid */ + int32_t tid; /* generating process's tid */ + int32_t sec; /* seconds since Epoch */ + int32_t nsec; /* nanoseconds */ + uint32_t lid; /* log id of the payload */ + char msg[0]; /* the entry's payload */ +} __attribute__((__packed__)); + +/* + * The maximum size of the log entry payload that can be + * written to the logger. An attempt to write more than + * this amount will result in a truncated log entry. + */ +#define LOGGER_ENTRY_MAX_PAYLOAD 4076 + +/* + * The maximum size of a log entry which can be read from the + * kernel logger driver. An attempt to read less than this amount + * may result in read() returning EINVAL. + */ +#define LOGGER_ENTRY_MAX_LEN (5*1024) + +#define NS_PER_SEC 1000000000ULL + +struct log_msg { + union { + unsigned char buf[LOGGER_ENTRY_MAX_LEN + 1]; + struct logger_entry_v3 entry; + struct logger_entry_v3 entry_v3; + struct logger_entry_v2 entry_v2; + struct logger_entry entry_v1; + } __attribute__((aligned(4))); +#ifdef __cplusplus + /* Matching log_time operators */ + bool operator== (const log_msg &T) const + { + return (entry.sec == T.entry.sec) && (entry.nsec == T.entry.nsec); + } + bool operator!= (const log_msg &T) const + { + return !(*this == T); + } + bool operator< (const log_msg &T) const + { + return (entry.sec < T.entry.sec) + || ((entry.sec == T.entry.sec) + && (entry.nsec < T.entry.nsec)); + } + bool operator>= (const log_msg &T) const + { + return !(*this < T); + } + bool operator> (const log_msg &T) const + { + return (entry.sec > T.entry.sec) + || ((entry.sec == T.entry.sec) + && (entry.nsec > T.entry.nsec)); + } + bool operator<= (const log_msg &T) const + { + return !(*this > T); + } + uint64_t nsec() const + { + return static_cast(entry.sec) * NS_PER_SEC + entry.nsec; + } + + /* packet methods */ + log_id_t id() + { + return (log_id_t) entry.lid; + } + char *msg() + { + return entry.hdr_size ? (char *) buf + entry.hdr_size : entry_v1.msg; + } + unsigned int len() + { + return (entry.hdr_size ? entry.hdr_size : sizeof(entry_v1)) + entry.len; + } +#endif +}; + +struct logger; + +log_id_t android_logger_get_id(struct logger *logger); + +int android_logger_clear(struct logger *logger); +long android_logger_get_log_size(struct logger *logger); +int android_logger_set_log_size(struct logger *logger, unsigned long size); +long android_logger_get_log_readable_size(struct logger *logger); +int android_logger_get_log_version(struct logger *logger); + +struct logger_list; + +ssize_t android_logger_get_statistics(struct logger_list *logger_list, + char *buf, size_t len); +ssize_t android_logger_get_prune_list(struct logger_list *logger_list, + char *buf, size_t len); +int android_logger_set_prune_list(struct logger_list *logger_list, + char *buf, size_t len); + +#define ANDROID_LOG_RDONLY O_RDONLY +#define ANDROID_LOG_WRONLY O_WRONLY +#define ANDROID_LOG_RDWR O_RDWR +#define ANDROID_LOG_ACCMODE O_ACCMODE +#define ANDROID_LOG_NONBLOCK O_NONBLOCK +#define ANDROID_LOG_PSTORE 0x80000000 + +struct logger_list *android_logger_list_alloc(int mode, + unsigned int tail, + pid_t pid); +struct logger_list *android_logger_list_alloc_time(int mode, + log_time start, + pid_t pid); +void android_logger_list_free(struct logger_list *logger_list); +/* In the purest sense, the following two are orthogonal interfaces */ +int android_logger_list_read(struct logger_list *logger_list, + struct log_msg *log_msg); + +/* Multiple log_id_t opens */ +struct logger *android_logger_open(struct logger_list *logger_list, + log_id_t id); +#define android_logger_close android_logger_free +/* Single log_id_t open */ +struct logger_list *android_logger_list_open(log_id_t id, + int mode, + unsigned int tail, + pid_t pid); +#define android_logger_list_close android_logger_list_free + +/* + * log_id_t helpers + */ +log_id_t android_name_to_log_id(const char *logName); +const char *android_log_id_to_name(log_id_t log_id); + +#ifdef __cplusplus +} +#endif + +#endif /* _LIBS_LOG_LOGGER_H */ diff --git a/phonelibs/android_system_core/include/log/logprint.h b/phonelibs/android_system_core/include/log/logprint.h new file mode 100644 index 0000000000..4b812cc941 --- /dev/null +++ b/phonelibs/android_system_core/include/log/logprint.h @@ -0,0 +1,161 @@ +/* + * 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 _LOGPRINT_H +#define _LOGPRINT_H + +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + FORMAT_OFF = 0, + FORMAT_BRIEF, + FORMAT_PROCESS, + FORMAT_TAG, + FORMAT_THREAD, + FORMAT_RAW, + FORMAT_TIME, + FORMAT_THREADTIME, + FORMAT_LONG, + /* The following three are modifiers to above formats */ + FORMAT_MODIFIER_COLOR, /* converts priority to color */ + FORMAT_MODIFIER_TIME_USEC, /* switches from msec to usec time precision */ + FORMAT_MODIFIER_PRINTABLE, /* converts non-printable to printable escapes */ +} AndroidLogPrintFormat; + +typedef struct AndroidLogFormat_t AndroidLogFormat; + +typedef struct AndroidLogEntry_t { + time_t tv_sec; + long tv_nsec; + android_LogPriority priority; + int32_t pid; + int32_t tid; + const char * tag; + size_t messageLen; + const char * message; +} AndroidLogEntry; + +AndroidLogFormat *android_log_format_new(); + +void android_log_format_free(AndroidLogFormat *p_format); + +/* currently returns 0 if format is a modifier, 1 if not */ +int android_log_setPrintFormat(AndroidLogFormat *p_format, + AndroidLogPrintFormat format); + +/** + * Returns FORMAT_OFF on invalid string + */ +AndroidLogPrintFormat android_log_formatFromString(const char *s); + +/** + * filterExpression: a single filter expression + * eg "AT:d" + * + * returns 0 on success and -1 on invalid expression + * + * Assumes single threaded execution + * + */ + +int android_log_addFilterRule(AndroidLogFormat *p_format, + const char *filterExpression); + + +/** + * filterString: a whitespace-separated set of filter expressions + * eg "AT:d *:i" + * + * returns 0 on success and -1 on invalid expression + * + * Assumes single threaded execution + * + */ + +int android_log_addFilterString(AndroidLogFormat *p_format, + const char *filterString); + + +/** + * returns 1 if this log line should be printed based on its priority + * and tag, and 0 if it should not + */ +int android_log_shouldPrintLine ( + AndroidLogFormat *p_format, const char *tag, android_LogPriority pri); + + +/** + * Splits a wire-format buffer into an AndroidLogEntry + * entry allocated by caller. Pointers will point directly into buf + * + * Returns 0 on success and -1 on invalid wire format (entry will be + * in unspecified state) + */ +int android_log_processLogBuffer(struct logger_entry *buf, + AndroidLogEntry *entry); + +/** + * Like android_log_processLogBuffer, but for binary logs. + * + * If "map" is non-NULL, it will be used to convert the log tag number + * into a string. + */ +int android_log_processBinaryLogBuffer(struct logger_entry *buf, + AndroidLogEntry *entry, const EventTagMap* map, char* messageBuf, + int messageBufLen); + + +/** + * Formats a log message into a buffer + * + * Uses defaultBuffer if it can, otherwise malloc()'s a new buffer + * If return value != defaultBuffer, caller must call free() + * Returns NULL on malloc error + */ + +char *android_log_formatLogLine ( + AndroidLogFormat *p_format, + char *defaultBuffer, + size_t defaultBufferSize, + const AndroidLogEntry *p_line, + size_t *p_outLength); + + +/** + * Either print or do not print log line, based on filter + * + * Assumes single threaded execution + * + */ +int android_log_printLogLine( + AndroidLogFormat *p_format, + int fd, + const AndroidLogEntry *entry); + + +#ifdef __cplusplus +} +#endif + + +#endif /*_LOGPRINT_H*/ diff --git a/phonelibs/android_system_core/include/log/uio.h b/phonelibs/android_system_core/include/log/uio.h new file mode 100644 index 0000000000..7059da5f76 --- /dev/null +++ b/phonelibs/android_system_core/include/log/uio.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2007-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 _LIBS_CUTILS_UIO_H +#define _LIBS_CUTILS_UIO_H + +#if !defined(_WIN32) + +#include + +#else + +#ifdef __cplusplus +extern "C" { +#endif + +// +// Implementation of sys/uio.h for Win32. +// + +#include + +struct iovec { + void* iov_base; + size_t iov_len; +}; + +extern int readv( int fd, struct iovec* vecs, int count ); +extern int writev( int fd, const struct iovec* vecs, int count ); + +#ifdef __cplusplus +} +#endif + +#endif + +#endif /* _LIBS_UTILS_UIO_H */ + diff --git a/phonelibs/android_system_core/include/system/camera.h b/phonelibs/android_system_core/include/system/camera.h new file mode 100644 index 0000000000..0570ca04c6 --- /dev/null +++ b/phonelibs/android_system_core/include/system/camera.h @@ -0,0 +1,365 @@ +/* + * 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 SYSTEM_CORE_INCLUDE_ANDROID_CAMERA_H +#define SYSTEM_CORE_INCLUDE_ANDROID_CAMERA_H + +#include +#include +#include +#include +#include +#include + +__BEGIN_DECLS + +/** + * A set of bit masks for specifying how the received preview frames are + * handled before the previewCallback() call. + * + * The least significant 3 bits of an "int" value are used for this purpose: + * + * ..... 0 0 0 + * ^ ^ ^ + * | | |---------> determine whether the callback is enabled or not + * | |-----------> determine whether the callback is one-shot or not + * |-------------> determine whether the frame is copied out or not + * + * WARNING: When a frame is sent directly without copying, it is the frame + * receiver's responsiblity to make sure that the frame data won't get + * corrupted by subsequent preview frames filled by the camera. This flag is + * recommended only when copying out data brings significant performance price + * and the handling/processing of the received frame data is always faster than + * the preview frame rate so that data corruption won't occur. + * + * For instance, + * 1. 0x00 disables the callback. In this case, copy out and one shot bits + * are ignored. + * 2. 0x01 enables a callback without copying out the received frames. A + * typical use case is the Camcorder application to avoid making costly + * frame copies. + * 3. 0x05 is enabling a callback with frame copied out repeatedly. A typical + * use case is the Camera application. + * 4. 0x07 is enabling a callback with frame copied out only once. A typical + * use case is the Barcode scanner application. + */ + +enum { + CAMERA_FRAME_CALLBACK_FLAG_ENABLE_MASK = 0x01, + CAMERA_FRAME_CALLBACK_FLAG_ONE_SHOT_MASK = 0x02, + CAMERA_FRAME_CALLBACK_FLAG_COPY_OUT_MASK = 0x04, + /** Typical use cases */ + CAMERA_FRAME_CALLBACK_FLAG_NOOP = 0x00, + CAMERA_FRAME_CALLBACK_FLAG_CAMCORDER = 0x01, + CAMERA_FRAME_CALLBACK_FLAG_CAMERA = 0x05, + CAMERA_FRAME_CALLBACK_FLAG_BARCODE_SCANNER = 0x07 +}; + +/** msgType in notifyCallback and dataCallback functions */ +enum { + CAMERA_MSG_ERROR = 0x0001, // notifyCallback + CAMERA_MSG_SHUTTER = 0x0002, // notifyCallback + CAMERA_MSG_FOCUS = 0x0004, // notifyCallback + CAMERA_MSG_ZOOM = 0x0008, // notifyCallback + CAMERA_MSG_PREVIEW_FRAME = 0x0010, // dataCallback + CAMERA_MSG_VIDEO_FRAME = 0x0020, // data_timestamp_callback + CAMERA_MSG_POSTVIEW_FRAME = 0x0040, // dataCallback + CAMERA_MSG_RAW_IMAGE = 0x0080, // dataCallback + CAMERA_MSG_COMPRESSED_IMAGE = 0x0100, // dataCallback + CAMERA_MSG_RAW_IMAGE_NOTIFY = 0x0200, // dataCallback + // Preview frame metadata. This can be combined with + // CAMERA_MSG_PREVIEW_FRAME in dataCallback. For example, the apps can + // request FRAME and METADATA. Or the apps can request only FRAME or only + // METADATA. + CAMERA_MSG_PREVIEW_METADATA = 0x0400, // dataCallback + // Notify on autofocus start and stop. This is useful in continuous + // autofocus - FOCUS_MODE_CONTINUOUS_VIDEO and FOCUS_MODE_CONTINUOUS_PICTURE. + CAMERA_MSG_FOCUS_MOVE = 0x0800, // notifyCallback + CAMERA_MSG_VENDOR_START = 0x1000, + CAMERA_MSG_STATS_DATA = CAMERA_MSG_VENDOR_START, + CAMERA_MSG_META_DATA = 0x2000, + CAMERA_MSG_VENDOR_END = 0x8000, + CAMERA_MSG_ALL_MSGS = 0xFFFF +}; + +/** meta data type in CameraMetaDataCallback */ +enum { + CAMERA_META_DATA_ASD = 0x001, //ASD data + CAMERA_META_DATA_FD = 0x002, //FD/FP data + CAMERA_META_DATA_HDR = 0x003, //Auto HDR data +}; + +/** cmdType in sendCommand functions */ +enum { + CAMERA_CMD_START_SMOOTH_ZOOM = 1, + CAMERA_CMD_STOP_SMOOTH_ZOOM = 2, + + /** + * Set the clockwise rotation of preview display (setPreviewDisplay) in + * degrees. This affects the preview frames and the picture displayed after + * snapshot. This method is useful for portrait mode applications. Note + * that preview display of front-facing cameras is flipped horizontally + * before the rotation, that is, the image is reflected along the central + * vertical axis of the camera sensor. So the users can see themselves as + * looking into a mirror. + * + * This does not affect the order of byte array of + * CAMERA_MSG_PREVIEW_FRAME, CAMERA_MSG_VIDEO_FRAME, + * CAMERA_MSG_POSTVIEW_FRAME, CAMERA_MSG_RAW_IMAGE, or + * CAMERA_MSG_COMPRESSED_IMAGE. This is allowed to be set during preview + * since API level 14. + */ + CAMERA_CMD_SET_DISPLAY_ORIENTATION = 3, + + /** + * cmdType to disable/enable shutter sound. In sendCommand passing arg1 = + * 0 will disable, while passing arg1 = 1 will enable the shutter sound. + */ + CAMERA_CMD_ENABLE_SHUTTER_SOUND = 4, + + /* cmdType to play recording sound */ + CAMERA_CMD_PLAY_RECORDING_SOUND = 5, + + /** + * Start the face detection. This should be called after preview is started. + * The camera will notify the listener of CAMERA_MSG_FACE and the detected + * faces in the preview frame. The detected faces may be the same as the + * previous ones. Apps should call CAMERA_CMD_STOP_FACE_DETECTION to stop + * the face detection. This method is supported if CameraParameters + * KEY_MAX_NUM_HW_DETECTED_FACES or KEY_MAX_NUM_SW_DETECTED_FACES is + * bigger than 0. Hardware and software face detection should not be running + * at the same time. If the face detection has started, apps should not send + * this again. + * + * In hardware face detection mode, CameraParameters KEY_WHITE_BALANCE, + * KEY_FOCUS_AREAS and KEY_METERING_AREAS have no effect. + * + * arg1 is the face detection type. It can be CAMERA_FACE_DETECTION_HW or + * CAMERA_FACE_DETECTION_SW. If the type of face detection requested is not + * supported, the HAL must return BAD_VALUE. + */ + CAMERA_CMD_START_FACE_DETECTION = 6, + + /** + * Stop the face detection. + */ + CAMERA_CMD_STOP_FACE_DETECTION = 7, + + /** + * Enable/disable focus move callback (CAMERA_MSG_FOCUS_MOVE). Passing + * arg1 = 0 will disable, while passing arg1 = 1 will enable the callback. + */ + CAMERA_CMD_ENABLE_FOCUS_MOVE_MSG = 8, + + /** + * Ping camera service to see if camera hardware is released. + * + * When any camera method returns error, the client can use ping command + * to see if the camera has been taken away by other clients. If the result + * is NO_ERROR, it means the camera hardware is not released. If the result + * is not NO_ERROR, the camera has been released and the existing client + * can silently finish itself or show a dialog. + */ + CAMERA_CMD_PING = 9, + + /** + * Configure the number of video buffers used for recording. The intended + * video buffer count for recording is passed as arg1, which must be + * greater than 0. This command must be sent before recording is started. + * This command returns INVALID_OPERATION error if it is sent after video + * recording is started, or the command is not supported at all. This + * command also returns a BAD_VALUE error if the intended video buffer + * count is non-positive or too big to be realized. + */ + CAMERA_CMD_SET_VIDEO_BUFFER_COUNT = 10, + + /** + * Configure an explicit format to use for video recording metadata mode. + * This can be used to switch the format from the + * default IMPLEMENTATION_DEFINED gralloc format to some other + * device-supported format, and the default dataspace from the BT_709 color + * space to some other device-supported dataspace. arg1 is the HAL pixel + * format, and arg2 is the HAL dataSpace. This command returns + * INVALID_OPERATION error if it is sent after video recording is started, + * or the command is not supported at all. + * + * If the gralloc format is set to a format other than + * IMPLEMENTATION_DEFINED, then HALv3 devices will use gralloc usage flags + * of SW_READ_OFTEN. + */ +#ifndef CAMERA_VENDOR_L_COMPAT + CAMERA_CMD_SET_VIDEO_FORMAT = 11, + + CAMERA_CMD_VENDOR_START = 20, + /** + * Commands to enable/disable preview histogram + * + * Based on user's input to enable/disable histogram from the camera + * UI, send the appropriate command to the HAL to turn on/off the histogram + * stats and start sending the data to the application. + */ + CAMERA_CMD_HISTOGRAM_ON = CAMERA_CMD_VENDOR_START, + CAMERA_CMD_HISTOGRAM_OFF = CAMERA_CMD_VENDOR_START + 1, + CAMERA_CMD_HISTOGRAM_SEND_DATA = CAMERA_CMD_VENDOR_START + 2, + CAMERA_CMD_LONGSHOT_ON = CAMERA_CMD_VENDOR_START + 3, + CAMERA_CMD_LONGSHOT_OFF = CAMERA_CMD_VENDOR_START + 4, + CAMERA_CMD_STOP_LONGSHOT = CAMERA_CMD_VENDOR_START + 5, + CAMERA_CMD_METADATA_ON = CAMERA_CMD_VENDOR_START + 6, + CAMERA_CMD_METADATA_OFF = CAMERA_CMD_VENDOR_START + 7, + CAMERA_CMD_VENDOR_END = 200, +#else + + /** + * Values used by older HALs, provided as an option for compatibility + */ + CAMERA_CMD_HISTOGRAM_ON = 11, + CAMERA_CMD_HISTOGRAM_OFF = 12, + CAMERA_CMD_HISTOGRAM_SEND_DATA = 13, + CAMERA_CMD_LONGSHOT_ON = 14, + CAMERA_CMD_LONGSHOT_OFF = 15, + CAMERA_CMD_STOP_LONGSHOT = 16, + CAMERA_CMD_METADATA_ON = 100, + CAMERA_CMD_METADATA_OFF = 101, + CAMERA_CMD_SET_VIDEO_FORMAT = 102, +#endif +}; + +/** camera fatal errors */ +enum { + CAMERA_ERROR_UNKNOWN = 1, + /** + * Camera was released because another client has connected to the camera. + * The original client should call Camera::disconnect immediately after + * getting this notification. Otherwise, the camera will be released by + * camera service in a short time. The client should not call any method + * (except disconnect and sending CAMERA_CMD_PING) after getting this. + */ + CAMERA_ERROR_RELEASED = 2, + CAMERA_ERROR_SERVER_DIED = 100 +}; + +enum { + /** The facing of the camera is opposite to that of the screen. */ + CAMERA_FACING_BACK = 0, + /** The facing of the camera is the same as that of the screen. */ + CAMERA_FACING_FRONT = 1, + /** + * The facing of the camera is not fixed relative to the screen. + * The cameras with this facing are external cameras, e.g. USB cameras. + */ + CAMERA_FACING_EXTERNAL = 2 +}; + +enum { + /** Hardware face detection. It does not use much CPU. */ + CAMERA_FACE_DETECTION_HW = 0, + /** + * Software face detection. It uses some CPU. Applications must use + * Camera.setPreviewTexture for preview in this mode. + */ + CAMERA_FACE_DETECTION_SW = 1 +}; + +/** + * The information of a face from camera face detection. + */ +typedef struct camera_face { + /** + * Bounds of the face [left, top, right, bottom]. (-1000, -1000) represents + * the top-left of the camera field of view, and (1000, 1000) represents the + * bottom-right of the field of view. The width and height cannot be 0 or + * negative. This is supported by both hardware and software face detection. + * + * The direction is relative to the sensor orientation, that is, what the + * sensor sees. The direction is not affected by the rotation or mirroring + * of CAMERA_CMD_SET_DISPLAY_ORIENTATION. + */ + int32_t rect[4]; + + /** + * The confidence level of the face. The range is 1 to 100. 100 is the + * highest confidence. This is supported by both hardware and software + * face detection. + */ + int32_t score; + + /** + * An unique id per face while the face is visible to the tracker. If + * the face leaves the field-of-view and comes back, it will get a new + * id. If the value is 0, id is not supported. + */ + int32_t id; + + /** + * The coordinates of the center of the left eye. The range is -1000 to + * 1000. -2000, -2000 if this is not supported. + */ + int32_t left_eye[2]; + + /** + * The coordinates of the center of the right eye. The range is -1000 to + * 1000. -2000, -2000 if this is not supported. + */ + int32_t right_eye[2]; + + /** + * The coordinates of the center of the mouth. The range is -1000 to 1000. + * -2000, -2000 if this is not supported. + */ + int32_t mouth[2]; + int32_t smile_degree; + int32_t smile_score; + int32_t blink_detected; + int32_t face_recognised; + int32_t gaze_angle; + int32_t updown_dir; + int32_t leftright_dir; + int32_t roll_dir; + int32_t left_right_gaze; + int32_t top_bottom_gaze; + int32_t leye_blink; + int32_t reye_blink; + +} camera_face_t; + +/** + * The information of a data type received in a camera frame. + */ +typedef enum { + /** Data buffer */ + CAMERA_FRAME_DATA_BUF = 0x000, + /** File descriptor */ + CAMERA_FRAME_DATA_FD = 0x100 +} camera_frame_data_type_t; + +/** + * The metadata of the frame data. + */ +typedef struct camera_frame_metadata { + /** + * The number of detected faces in the frame. + */ + int32_t number_of_faces; + + /** + * An array of the detected faces. The length is number_of_faces. + */ + camera_face_t *faces; +} camera_frame_metadata_t; + +__END_DECLS + +#endif /* SYSTEM_CORE_INCLUDE_ANDROID_CAMERA_H */ diff --git a/phonelibs/android_system_core/include/system/graphics.h b/phonelibs/android_system_core/include/system/graphics.h new file mode 100644 index 0000000000..afd9f7bdb3 --- /dev/null +++ b/phonelibs/android_system_core/include/system/graphics.h @@ -0,0 +1,763 @@ +/* + * 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 SYSTEM_CORE_INCLUDE_ANDROID_GRAPHICS_H +#define SYSTEM_CORE_INCLUDE_ANDROID_GRAPHICS_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * If the HAL needs to create service threads to handle graphics related + * tasks, these threads need to run at HAL_PRIORITY_URGENT_DISPLAY priority + * if they can block the main rendering thread in any way. + * + * the priority of the current thread can be set with: + * + * #include + * setpriority(PRIO_PROCESS, 0, HAL_PRIORITY_URGENT_DISPLAY); + * + */ + +#define HAL_PRIORITY_URGENT_DISPLAY (-8) + +/** + * pixel format definitions + */ + +enum { + /* + * "linear" color pixel formats: + * + * When used with ANativeWindow, the dataSpace field describes the color + * space of the buffer. + * + * The color space determines, for example, if the formats are linear or + * gamma-corrected; or whether any special operations are performed when + * reading or writing into a buffer in one of these formats. + */ + HAL_PIXEL_FORMAT_RGBA_8888 = 1, + HAL_PIXEL_FORMAT_RGBX_8888 = 2, + HAL_PIXEL_FORMAT_RGB_888 = 3, + HAL_PIXEL_FORMAT_RGB_565 = 4, + HAL_PIXEL_FORMAT_BGRA_8888 = 5, + + /* + * 0x100 - 0x1FF + * + * This range is reserved for pixel formats that are specific to the HAL + * implementation. Implementations can use any value in this range to + * communicate video pixel formats between their HAL modules. These formats + * must not have an alpha channel. Additionally, an EGLimage created from a + * gralloc buffer of one of these formats must be supported for use with the + * GL_OES_EGL_image_external OpenGL ES extension. + */ + + /* + * Android YUV format: + * + * This format is exposed outside of the HAL to software decoders and + * applications. EGLImageKHR must support it in conjunction with the + * OES_EGL_image_external extension. + * + * YV12 is a 4:2:0 YCrCb planar format comprised of a WxH Y plane followed + * by (W/2) x (H/2) Cr and Cb planes. + * + * This format assumes + * - an even width + * - an even height + * - a horizontal stride multiple of 16 pixels + * - a vertical stride equal to the height + * + * y_size = stride * height + * c_stride = ALIGN(stride/2, 16) + * c_size = c_stride * height/2 + * size = y_size + c_size * 2 + * cr_offset = y_size + * cb_offset = y_size + c_size + * + * When used with ANativeWindow, the dataSpace field describes the color + * space of the buffer. + */ + HAL_PIXEL_FORMAT_YV12 = 0x32315659, // YCrCb 4:2:0 Planar + + + /* + * Android Y8 format: + * + * This format is exposed outside of the HAL to the framework. + * The expected gralloc usage flags are SW_* and HW_CAMERA_*, + * and no other HW_ flags will be used. + * + * Y8 is a YUV planar format comprised of a WxH Y plane, + * with each pixel being represented by 8 bits. + * + * It is equivalent to just the Y plane from YV12. + * + * This format assumes + * - an even width + * - an even height + * - a horizontal stride multiple of 16 pixels + * - a vertical stride equal to the height + * + * size = stride * height + * + * When used with ANativeWindow, the dataSpace field describes the color + * space of the buffer. + */ + HAL_PIXEL_FORMAT_Y8 = 0x20203859, + + /* + * Android Y16 format: + * + * This format is exposed outside of the HAL to the framework. + * The expected gralloc usage flags are SW_* and HW_CAMERA_*, + * and no other HW_ flags will be used. + * + * Y16 is a YUV planar format comprised of a WxH Y plane, + * with each pixel being represented by 16 bits. + * + * It is just like Y8, but has double the bits per pixel (little endian). + * + * This format assumes + * - an even width + * - an even height + * - a horizontal stride multiple of 16 pixels + * - a vertical stride equal to the height + * - strides are specified in pixels, not in bytes + * + * size = stride * height * 2 + * + * When used with ANativeWindow, the dataSpace field describes the color + * space of the buffer, except that dataSpace field + * HAL_DATASPACE_DEPTH indicates that this buffer contains a depth + * image where each sample is a distance value measured by a depth camera, + * plus an associated confidence value. + */ + HAL_PIXEL_FORMAT_Y16 = 0x20363159, + + /* + * Android RAW sensor format: + * + * This format is exposed outside of the camera HAL to applications. + * + * RAW16 is a single-channel, 16-bit, little endian format, typically + * representing raw Bayer-pattern images from an image sensor, with minimal + * processing. + * + * The exact pixel layout of the data in the buffer is sensor-dependent, and + * needs to be queried from the camera device. + * + * Generally, not all 16 bits are used; more common values are 10 or 12 + * bits. If not all bits are used, the lower-order bits are filled first. + * All parameters to interpret the raw data (black and white points, + * color space, etc) must be queried from the camera device. + * + * This format assumes + * - an even width + * - an even height + * - a horizontal stride multiple of 16 pixels + * - a vertical stride equal to the height + * - strides are specified in pixels, not in bytes + * + * size = stride * height * 2 + * + * This format must be accepted by the gralloc module when used with the + * following usage flags: + * - GRALLOC_USAGE_HW_CAMERA_* + * - GRALLOC_USAGE_SW_* + * - GRALLOC_USAGE_RENDERSCRIPT + * + * When used with ANativeWindow, the dataSpace should be + * HAL_DATASPACE_ARBITRARY, as raw image sensor buffers require substantial + * extra metadata to define. + */ + HAL_PIXEL_FORMAT_RAW16 = 0x20, + + /* + * Android RAW10 format: + * + * This format is exposed outside of the camera HAL to applications. + * + * RAW10 is a single-channel, 10-bit per pixel, densely packed in each row, + * unprocessed format, usually representing raw Bayer-pattern images coming from + * an image sensor. + * + * In an image buffer with this format, starting from the first pixel of each + * row, each 4 consecutive pixels are packed into 5 bytes (40 bits). Each one + * of the first 4 bytes contains the top 8 bits of each pixel, The fifth byte + * contains the 2 least significant bits of the 4 pixels, the exact layout data + * for each 4 consecutive pixels is illustrated below (Pi[j] stands for the jth + * bit of the ith pixel): + * + * bit 7 bit 0 + * =====|=====|=====|=====|=====|=====|=====|=====| + * Byte 0: |P0[9]|P0[8]|P0[7]|P0[6]|P0[5]|P0[4]|P0[3]|P0[2]| + * |-----|-----|-----|-----|-----|-----|-----|-----| + * Byte 1: |P1[9]|P1[8]|P1[7]|P1[6]|P1[5]|P1[4]|P1[3]|P1[2]| + * |-----|-----|-----|-----|-----|-----|-----|-----| + * Byte 2: |P2[9]|P2[8]|P2[7]|P2[6]|P2[5]|P2[4]|P2[3]|P2[2]| + * |-----|-----|-----|-----|-----|-----|-----|-----| + * Byte 3: |P3[9]|P3[8]|P3[7]|P3[6]|P3[5]|P3[4]|P3[3]|P3[2]| + * |-----|-----|-----|-----|-----|-----|-----|-----| + * Byte 4: |P3[1]|P3[0]|P2[1]|P2[0]|P1[1]|P1[0]|P0[1]|P0[0]| + * =============================================== + * + * This format assumes + * - a width multiple of 4 pixels + * - an even height + * - a vertical stride equal to the height + * - strides are specified in bytes, not in pixels + * + * size = stride * height + * + * When stride is equal to width * (10 / 8), there will be no padding bytes at + * the end of each row, the entire image data is densely packed. When stride is + * larger than width * (10 / 8), padding bytes will be present at the end of each + * row (including the last row). + * + * This format must be accepted by the gralloc module when used with the + * following usage flags: + * - GRALLOC_USAGE_HW_CAMERA_* + * - GRALLOC_USAGE_SW_* + * - GRALLOC_USAGE_RENDERSCRIPT + * + * When used with ANativeWindow, the dataSpace field should be + * HAL_DATASPACE_ARBITRARY, as raw image sensor buffers require substantial + * extra metadata to define. + */ + HAL_PIXEL_FORMAT_RAW10 = 0x25, + + /* + * Android RAW12 format: + * + * This format is exposed outside of camera HAL to applications. + * + * RAW12 is a single-channel, 12-bit per pixel, densely packed in each row, + * unprocessed format, usually representing raw Bayer-pattern images coming from + * an image sensor. + * + * In an image buffer with this format, starting from the first pixel of each + * row, each two consecutive pixels are packed into 3 bytes (24 bits). The first + * and second byte contains the top 8 bits of first and second pixel. The third + * byte contains the 4 least significant bits of the two pixels, the exact layout + * data for each two consecutive pixels is illustrated below (Pi[j] stands for + * the jth bit of the ith pixel): + * + * bit 7 bit 0 + * ======|======|======|======|======|======|======|======| + * Byte 0: |P0[11]|P0[10]|P0[ 9]|P0[ 8]|P0[ 7]|P0[ 6]|P0[ 5]|P0[ 4]| + * |------|------|------|------|------|------|------|------| + * Byte 1: |P1[11]|P1[10]|P1[ 9]|P1[ 8]|P1[ 7]|P1[ 6]|P1[ 5]|P1[ 4]| + * |------|------|------|------|------|------|------|------| + * Byte 2: |P1[ 3]|P1[ 2]|P1[ 1]|P1[ 0]|P0[ 3]|P0[ 2]|P0[ 1]|P0[ 0]| + * ======================================================= + * + * This format assumes: + * - a width multiple of 4 pixels + * - an even height + * - a vertical stride equal to the height + * - strides are specified in bytes, not in pixels + * + * size = stride * height + * + * When stride is equal to width * (12 / 8), there will be no padding bytes at + * the end of each row, the entire image data is densely packed. When stride is + * larger than width * (12 / 8), padding bytes will be present at the end of + * each row (including the last row). + * + * This format must be accepted by the gralloc module when used with the + * following usage flags: + * - GRALLOC_USAGE_HW_CAMERA_* + * - GRALLOC_USAGE_SW_* + * - GRALLOC_USAGE_RENDERSCRIPT + * + * When used with ANativeWindow, the dataSpace field should be + * HAL_DATASPACE_ARBITRARY, as raw image sensor buffers require substantial + * extra metadata to define. + */ + HAL_PIXEL_FORMAT_RAW12 = 0x26, + + /* + * Android opaque RAW format: + * + * This format is exposed outside of the camera HAL to applications. + * + * RAW_OPAQUE is a format for unprocessed raw image buffers coming from an + * image sensor. The actual structure of buffers of this format is + * implementation-dependent. + * + * This format must be accepted by the gralloc module when used with the + * following usage flags: + * - GRALLOC_USAGE_HW_CAMERA_* + * - GRALLOC_USAGE_SW_* + * - GRALLOC_USAGE_RENDERSCRIPT + * + * When used with ANativeWindow, the dataSpace field should be + * HAL_DATASPACE_ARBITRARY, as raw image sensor buffers require substantial + * extra metadata to define. + */ + HAL_PIXEL_FORMAT_RAW_OPAQUE = 0x24, + + /* + * Android binary blob graphics buffer format: + * + * This format is used to carry task-specific data which does not have a + * standard image structure. The details of the format are left to the two + * endpoints. + * + * A typical use case is for transporting JPEG-compressed images from the + * Camera HAL to the framework or to applications. + * + * Buffers of this format must have a height of 1, and width equal to their + * size in bytes. + * + * When used with ANativeWindow, the mapping of the dataSpace field to + * buffer contents for BLOB is as follows: + * + * dataSpace value | Buffer contents + * -------------------------------+----------------------------------------- + * HAL_DATASPACE_JFIF | An encoded JPEG image + * HAL_DATASPACE_DEPTH | An android_depth_points buffer + * Other | Unsupported + * + */ + HAL_PIXEL_FORMAT_BLOB = 0x21, + + /* + * Android format indicating that the choice of format is entirely up to the + * device-specific Gralloc implementation. + * + * The Gralloc implementation should examine the usage bits passed in when + * allocating a buffer with this format, and it should derive the pixel + * format from those usage flags. This format will never be used with any + * of the GRALLOC_USAGE_SW_* usage flags. + * + * If a buffer of this format is to be used as an OpenGL ES texture, the + * framework will assume that sampling the texture will always return an + * alpha value of 1.0 (i.e. the buffer contains only opaque pixel values). + * + * When used with ANativeWindow, the dataSpace field describes the color + * space of the buffer. + */ + HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED = 0x22, + + /* + * Android flexible YCbCr 4:2:0 formats + * + * This format allows platforms to use an efficient YCbCr/YCrCb 4:2:0 + * buffer layout, while still describing the general format in a + * layout-independent manner. While called YCbCr, it can be + * used to describe formats with either chromatic ordering, as well as + * whole planar or semiplanar layouts. + * + * struct android_ycbcr (below) is the the struct used to describe it. + * + * This format must be accepted by the gralloc module when + * USAGE_SW_WRITE_* or USAGE_SW_READ_* are set. + * + * This format is locked for use by gralloc's (*lock_ycbcr) method, and + * locking with the (*lock) method will return an error. + * + * When used with ANativeWindow, the dataSpace field describes the color + * space of the buffer. + */ + HAL_PIXEL_FORMAT_YCbCr_420_888 = 0x23, + + /* + * Android flexible YCbCr 4:2:2 formats + * + * This format allows platforms to use an efficient YCbCr/YCrCb 4:2:2 + * buffer layout, while still describing the general format in a + * layout-independent manner. While called YCbCr, it can be + * used to describe formats with either chromatic ordering, as well as + * whole planar or semiplanar layouts. + * + * This format is currently only used by SW readable buffers + * produced by MediaCodecs, so the gralloc module can ignore this format. + */ + HAL_PIXEL_FORMAT_YCbCr_422_888 = 0x27, + + /* + * Android flexible YCbCr 4:4:4 formats + * + * This format allows platforms to use an efficient YCbCr/YCrCb 4:4:4 + * buffer layout, while still describing the general format in a + * layout-independent manner. While called YCbCr, it can be + * used to describe formats with either chromatic ordering, as well as + * whole planar or semiplanar layouts. + * + * This format is currently only used by SW readable buffers + * produced by MediaCodecs, so the gralloc module can ignore this format. + */ + HAL_PIXEL_FORMAT_YCbCr_444_888 = 0x28, + + /* + * Android flexible RGB 888 formats + * + * This format allows platforms to use an efficient RGB/BGR/RGBX/BGRX + * buffer layout, while still describing the general format in a + * layout-independent manner. While called RGB, it can be + * used to describe formats with either color ordering and optional + * padding, as well as whole planar layout. + * + * This format is currently only used by SW readable buffers + * produced by MediaCodecs, so the gralloc module can ignore this format. + */ + HAL_PIXEL_FORMAT_FLEX_RGB_888 = 0x29, + + /* + * Android flexible RGBA 8888 formats + * + * This format allows platforms to use an efficient RGBA/BGRA/ARGB/ABGR + * buffer layout, while still describing the general format in a + * layout-independent manner. While called RGBA, it can be + * used to describe formats with any of the component orderings, as + * well as whole planar layout. + * + * This format is currently only used by SW readable buffers + * produced by MediaCodecs, so the gralloc module can ignore this format. + */ + HAL_PIXEL_FORMAT_FLEX_RGBA_8888 = 0x2A, + + /* Legacy formats (deprecated), used by ImageFormat.java */ + HAL_PIXEL_FORMAT_YCbCr_422_SP = 0x10, // NV16 + HAL_PIXEL_FORMAT_YCrCb_420_SP = 0x11, // NV21 + HAL_PIXEL_FORMAT_YCbCr_422_I = 0x14, // YUY2 +}; + +/* + * Structure for describing YCbCr formats for consumption by applications. + * This is used with HAL_PIXEL_FORMAT_YCbCr_*_888. + * + * Buffer chroma subsampling is defined in the format. + * e.g. HAL_PIXEL_FORMAT_YCbCr_420_888 has subsampling 4:2:0. + * + * Buffers must have a 8 bit depth. + * + * @y, @cb, and @cr point to the first byte of their respective planes. + * + * Stride describes the distance in bytes from the first value of one row of + * the image to the first value of the next row. It includes the width of the + * image plus padding. + * @ystride is the stride of the luma plane. + * @cstride is the stride of the chroma planes. + * + * @chroma_step is the distance in bytes from one chroma pixel value to the + * next. This is 2 bytes for semiplanar (because chroma values are interleaved + * and each chroma value is one byte) and 1 for planar. + */ + +struct android_ycbcr { + void *y; + void *cb; + void *cr; + size_t ystride; + size_t cstride; + size_t chroma_step; + + /** reserved for future use, set to 0 by gralloc's (*lock_ycbcr)() */ + uint32_t reserved[8]; +}; + +/** + * Structure used to define depth point clouds for format HAL_PIXEL_FORMAT_BLOB + * with dataSpace value of HAL_DATASPACE_DEPTH. + * When locking a native buffer of the above format and dataSpace value, + * the vaddr pointer can be cast to this structure. + * + * A variable-length list of (x,y,z, confidence) 3D points, as floats. (x, y, + * z) represents a measured point's position, with the coordinate system defined + * by the data source. Confidence represents the estimated likelihood that this + * measurement is correct. It is between 0.f and 1.f, inclusive, with 1.f == + * 100% confidence. + * + * @num_points is the number of points in the list + * + * @xyz_points is the flexible array of floating-point values. + * It contains (num_points) * 4 floats. + * + * For example: + * android_depth_points d = get_depth_buffer(); + * struct { + * float x; float y; float z; float confidence; + * } firstPoint, lastPoint; + * + * firstPoint.x = d.xyzc_points[0]; + * firstPoint.y = d.xyzc_points[1]; + * firstPoint.z = d.xyzc_points[2]; + * firstPoint.confidence = d.xyzc_points[3]; + * lastPoint.x = d.xyzc_points[(d.num_points - 1) * 4 + 0]; + * lastPoint.y = d.xyzc_points[(d.num_points - 1) * 4 + 1]; + * lastPoint.z = d.xyzc_points[(d.num_points - 1) * 4 + 2]; + * lastPoint.confidence = d.xyzc_points[(d.num_points - 1) * 4 + 3]; + */ + +struct android_depth_points { + uint32_t num_points; + + /** reserved for future use, set to 0 by gralloc's (*lock)() */ + uint32_t reserved[8]; + + float xyzc_points[]; +}; + +/** + * Transformation definitions + * + * IMPORTANT NOTE: + * HAL_TRANSFORM_ROT_90 is applied CLOCKWISE and AFTER HAL_TRANSFORM_FLIP_{H|V}. + * + */ + +enum { + /* flip source image horizontally (around the vertical axis) */ + HAL_TRANSFORM_FLIP_H = 0x01, + /* flip source image vertically (around the horizontal axis)*/ + HAL_TRANSFORM_FLIP_V = 0x02, + /* rotate source image 90 degrees clockwise */ + HAL_TRANSFORM_ROT_90 = 0x04, + /* rotate source image 180 degrees */ + HAL_TRANSFORM_ROT_180 = 0x03, + /* rotate source image 270 degrees clockwise */ + HAL_TRANSFORM_ROT_270 = 0x07, + /* don't use. see system/window.h */ + HAL_TRANSFORM_RESERVED = 0x08, +}; + +/** + * Dataspace Definitions + * ====================== + * + * Dataspace is the definition of how pixel values should be interpreted. + * + * For many formats, this is the colorspace of the image data, which includes + * primaries (including white point) and the transfer characteristic function, + * which describes both gamma curve and numeric range (within the bit depth). + * + * Other dataspaces include depth measurement data from a depth camera. + */ + +typedef enum android_dataspace { + /* + * Default-assumption data space, when not explicitly specified. + * + * It is safest to assume the buffer is an image with sRGB primaries and + * encoding ranges, but the consumer and/or the producer of the data may + * simply be using defaults. No automatic gamma transform should be + * expected, except for a possible display gamma transform when drawn to a + * screen. + */ + HAL_DATASPACE_UNKNOWN = 0x0, + + /* + * Arbitrary dataspace with manually defined characteristics. Definition + * for colorspaces or other meaning must be communicated separately. + * + * This is used when specifying primaries, transfer characteristics, + * etc. separately. + * + * A typical use case is in video encoding parameters (e.g. for H.264), + * where a colorspace can have separately defined primaries, transfer + * characteristics, etc. + */ + HAL_DATASPACE_ARBITRARY = 0x1, + + /* + * RGB Colorspaces + * ----------------- + * + * Primaries are given using (x,y) coordinates in the CIE 1931 definition + * of x and y specified by ISO 11664-1. + * + * Transfer characteristics are the opto-electronic transfer characteristic + * at the source as a function of linear optical intensity (luminance). + */ + + /* + * sRGB linear encoding: + * + * The red, green, and blue components are stored in sRGB space, but + * are linear, not gamma-encoded. + * The RGB primaries and the white point are the same as BT.709. + * + * The values are encoded using the full range ([0,255] for 8-bit) for all + * components. + */ + HAL_DATASPACE_SRGB_LINEAR = 0x200, + + /* + * sRGB gamma encoding: + * + * The red, green and blue components are stored in sRGB space, and + * converted to linear space when read, using the standard sRGB to linear + * equation: + * + * Clinear = Csrgb / 12.92 for Csrgb <= 0.04045 + * = (Csrgb + 0.055 / 1.055)^2.4 for Csrgb > 0.04045 + * + * When written the inverse transformation is performed: + * + * Csrgb = 12.92 * Clinear for Clinear <= 0.0031308 + * = 1.055 * Clinear^(1/2.4) - 0.055 for Clinear > 0.0031308 + * + * + * The alpha component, if present, is always stored in linear space and + * is left unmodified when read or written. + * + * The RGB primaries and the white point are the same as BT.709. + * + * The values are encoded using the full range ([0,255] for 8-bit) for all + * components. + * + */ + HAL_DATASPACE_SRGB = 0x201, + + /* + * YCbCr Colorspaces + * ----------------- + * + * Primaries are given using (x,y) coordinates in the CIE 1931 definition + * of x and y specified by ISO 11664-1. + * + * Transfer characteristics are the opto-electronic transfer characteristic + * at the source as a function of linear optical intensity (luminance). + */ + + /* + * JPEG File Interchange Format (JFIF) + * + * Same model as BT.601-625, but all values (Y, Cb, Cr) range from 0 to 255 + * + * Transfer characteristic curve: + * E = 1.099 * L ^ 0.45 - 0.099, 1.00 >= L >= 0.018 + * E = 4.500 L, 0.018 > L >= 0 + * L - luminance of image 0 <= L <= 1 for conventional colorimetry + * E - corresponding electrical signal + * + * Primaries: x y + * green 0.290 0.600 + * blue 0.150 0.060 + * red 0.640 0.330 + * white (D65) 0.3127 0.3290 + */ + HAL_DATASPACE_JFIF = 0x101, + + /* + * ITU-R Recommendation 601 (BT.601) - 625-line + * + * Standard-definition television, 625 Lines (PAL) + * + * For 8-bit-depth formats: + * Luma (Y) samples should range from 16 to 235, inclusive + * Chroma (Cb, Cr) samples should range from 16 to 240, inclusive + * + * For 10-bit-depth formats: + * Luma (Y) samples should range from 64 to 940, inclusive + * Chroma (Cb, Cr) samples should range from 64 to 960, inclusive + * + * Transfer characteristic curve: + * E = 1.099 * L ^ 0.45 - 0.099, 1.00 >= L >= 0.018 + * E = 4.500 L, 0.018 > L >= 0 + * L - luminance of image 0 <= L <= 1 for conventional colorimetry + * E - corresponding electrical signal + * + * Primaries: x y + * green 0.290 0.600 + * blue 0.150 0.060 + * red 0.640 0.330 + * white (D65) 0.3127 0.3290 + */ + HAL_DATASPACE_BT601_625 = 0x102, + + /* + * ITU-R Recommendation 601 (BT.601) - 525-line + * + * Standard-definition television, 525 Lines (NTSC) + * + * For 8-bit-depth formats: + * Luma (Y) samples should range from 16 to 235, inclusive + * Chroma (Cb, Cr) samples should range from 16 to 240, inclusive + * + * For 10-bit-depth formats: + * Luma (Y) samples should range from 64 to 940, inclusive + * Chroma (Cb, Cr) samples should range from 64 to 960, inclusive + * + * Transfer characteristic curve: + * E = 1.099 * L ^ 0.45 - 0.099, 1.00 >= L >= 0.018 + * E = 4.500 L, 0.018 > L >= 0 + * L - luminance of image 0 <= L <= 1 for conventional colorimetry + * E - corresponding electrical signal + * + * Primaries: x y + * green 0.310 0.595 + * blue 0.155 0.070 + * red 0.630 0.340 + * white (D65) 0.3127 0.3290 + */ + HAL_DATASPACE_BT601_525 = 0x103, + + /* + * ITU-R Recommendation 709 (BT.709) + * + * High-definition television + * + * For 8-bit-depth formats: + * Luma (Y) samples should range from 16 to 235, inclusive + * Chroma (Cb, Cr) samples should range from 16 to 240, inclusive + * + * For 10-bit-depth formats: + * Luma (Y) samples should range from 64 to 940, inclusive + * Chroma (Cb, Cr) samples should range from 64 to 960, inclusive + * + * Primaries: x y + * green 0.300 0.600 + * blue 0.150 0.060 + * red 0.640 0.330 + * white (D65) 0.3127 0.3290 + */ + HAL_DATASPACE_BT709 = 0x104, + + /* + * The buffer contains depth ranging measurements from a depth camera. + * This value is valid with formats: + * HAL_PIXEL_FORMAT_Y16: 16-bit samples, consisting of a depth measurement + * and an associated confidence value. The 3 MSBs of the sample make + * up the confidence value, and the low 13 LSBs of the sample make up + * the depth measurement. + * For the confidence section, 0 means 100% confidence, 1 means 0% + * confidence. The mapping to a linear float confidence value between + * 0.f and 1.f can be obtained with + * float confidence = (((depthSample >> 13) - 1) & 0x7) / 7.0f; + * The depth measurement can be extracted simply with + * uint16_t range = (depthSample & 0x1FFF); + * HAL_PIXEL_FORMAT_BLOB: A depth point cloud, as + * a variable-length float (x,y,z, confidence) coordinate point list. + * The point cloud will be represented with the android_depth_points + * structure. + */ + HAL_DATASPACE_DEPTH = 0x1000 + +} android_dataspace_t; + +#ifdef __cplusplus +} +#endif + +#endif /* SYSTEM_CORE_INCLUDE_ANDROID_GRAPHICS_H */ diff --git a/phonelibs/android_system_core/include/system/radio.h b/phonelibs/android_system_core/include/system/radio.h new file mode 100644 index 0000000000..a088526046 --- /dev/null +++ b/phonelibs/android_system_core/include/system/radio.h @@ -0,0 +1,247 @@ +/* + * 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_RADIO_H +#define ANDROID_RADIO_H + +#include +#include +#include +#include +#include + + +#define RADIO_NUM_BANDS_MAX 16 +#define RADIO_NUM_SPACINGS_MAX 16 +#define RADIO_STRING_LEN_MAX 128 + +/* + * Radio hardware module class. A given radio hardware module HAL is of one class + * only. The platform can not have more than one hardware module of each class. + * Current version of the framework only supports RADIO_CLASS_AM_FM. + */ +typedef enum { + RADIO_CLASS_AM_FM = 0, /* FM (including HD radio) and AM */ + RADIO_CLASS_SAT = 1, /* Satellite Radio */ + RADIO_CLASS_DT = 2, /* Digital Radio (DAB) */ +} radio_class_t; + +/* value for field "type" of radio band described in struct radio_hal_band_config */ +typedef enum { + RADIO_BAND_AM = 0, /* Amplitude Modulation band: LW, MW, SW */ + RADIO_BAND_FM = 1, /* Frequency Modulation band: FM */ + RADIO_BAND_FM_HD = 2, /* FM HD Radio / DRM (IBOC) */ + RADIO_BAND_AM_HD = 3, /* AM HD Radio / DRM (IBOC) */ +} radio_band_t; + +/* RDS variant implemented. A struct radio_hal_fm_band_config can list none or several. */ +enum { + RADIO_RDS_NONE = 0x0, + RADIO_RDS_WORLD = 0x01, + RADIO_RDS_US = 0x02, +}; +typedef unsigned int radio_rds_t; + +/* FM deemphasis variant implemented. A struct radio_hal_fm_band_config can list one or more. */ +enum { + RADIO_DEEMPHASIS_50 = 0x1, + RADIO_DEEMPHASIS_75 = 0x2, +}; +typedef unsigned int radio_deemphasis_t; + +/* Region a particular radio band configuration corresponds to. Not used at the HAL. + * Derived by the framework when converting the band descriptors retrieved from the HAL to + * individual band descriptors for each supported region. */ +typedef enum { + RADIO_REGION_NONE = -1, + RADIO_REGION_ITU_1 = 0, + RADIO_REGION_ITU_2 = 1, + RADIO_REGION_OIRT = 2, + RADIO_REGION_JAPAN = 3, + RADIO_REGION_KOREA = 4, +} radio_region_t; + +/* scanning direction for scan() and step() tuner APIs */ +typedef enum { + RADIO_DIRECTION_UP, + RADIO_DIRECTION_DOWN +} radio_direction_t; + +/* unique handle allocated to a radio module */ +typedef unsigned int radio_handle_t; + +/* Opaque meta data structure used by radio meta data API (see system/radio_metadata.h) */ +typedef struct radio_medtadata radio_metadata_t; + + +/* Additional attributes for an FM band configuration */ +typedef struct radio_hal_fm_band_config { + radio_deemphasis_t deemphasis; /* deemphasis variant */ + bool stereo; /* stereo supported */ + radio_rds_t rds; /* RDS variants supported */ + bool ta; /* Traffic Announcement supported */ + bool af; /* Alternate Frequency supported */ +} radio_hal_fm_band_config_t; + +/* Additional attributes for an AM band configuration */ +typedef struct radio_hal_am_band_config { + bool stereo; /* stereo supported */ +} radio_hal_am_band_config_t; + +/* Radio band configuration. Describes a given band supported by the radio module. + * The HAL can expose only one band per type with the the maximum range supported and all options. + * THe framework will derive the actual regions were this module can operate and expose separate + * band configurations for applications to chose from. */ +typedef struct radio_hal_band_config { + radio_band_t type; + bool antenna_connected; + unsigned int lower_limit; + unsigned int upper_limit; + unsigned int num_spacings; + unsigned int spacings[RADIO_NUM_SPACINGS_MAX]; + union { + radio_hal_fm_band_config_t fm; + radio_hal_am_band_config_t am; + }; +} radio_hal_band_config_t; + +/* Used internally by the framework to represent a band for s specific region */ +typedef struct radio_band_config { + radio_region_t region; + radio_hal_band_config_t band; +} radio_band_config_t; + + +/* Exposes properties of a given hardware radio module. + * NOTE: current framework implementation supports only one audio source (num_audio_sources = 1). + * The source corresponds to AUDIO_DEVICE_IN_FM_TUNER. + * If more than one tuner is supported (num_tuners > 1), only one can be connected to the audio + * source. */ +typedef struct radio_hal_properties { + radio_class_t class_id; /* Class of this module. E.g RADIO_CLASS_AM_FM */ + char implementor[RADIO_STRING_LEN_MAX]; /* implementor name */ + char product[RADIO_STRING_LEN_MAX]; /* product name */ + char version[RADIO_STRING_LEN_MAX]; /* product version */ + char serial[RADIO_STRING_LEN_MAX]; /* serial number (for subscription services) */ + unsigned int num_tuners; /* number of tuners controllable independently */ + unsigned int num_audio_sources; /* number of audio sources driven simultaneously */ + bool supports_capture; /* the hardware supports capture of audio source audio HAL */ + unsigned int num_bands; /* number of band descriptors */ + radio_hal_band_config_t bands[RADIO_NUM_BANDS_MAX]; /* band descriptors */ +} radio_hal_properties_t; + +/* Used internally by the framework. Same information as in struct radio_hal_properties plus a + * unique handle and one band configuration per region. */ +typedef struct radio_properties { + radio_handle_t handle; + radio_class_t class_id; + char implementor[RADIO_STRING_LEN_MAX]; + char product[RADIO_STRING_LEN_MAX]; + char version[RADIO_STRING_LEN_MAX]; + char serial[RADIO_STRING_LEN_MAX]; + unsigned int num_tuners; + unsigned int num_audio_sources; + bool supports_capture; + unsigned int num_bands; + radio_band_config_t bands[RADIO_NUM_BANDS_MAX]; +} radio_properties_t; + +/* Radio program information. Returned by the HAL with event RADIO_EVENT_TUNED. + * Contains information on currently tuned channel. + */ +typedef struct radio_program_info { + unsigned int channel; /* current channel. (e.g kHz for band type RADIO_BAND_FM) */ + unsigned int sub_channel; /* current sub channel. (used for RADIO_BAND_FM_HD) */ + bool tuned; /* tuned to a program or not */ + bool stereo; /* program is stereo or not */ + bool digital; /* digital program or not (e.g HD Radio program) */ + unsigned int signal_strength; /* signal strength from 0 to 100 */ + radio_metadata_t *metadata; /* non null if meta data are present (e.g PTY, song title ...) */ +} radio_program_info_t; + + +/* Events sent to the framework via the HAL callback. An event can notify the completion of an + * asynchronous command (configuration, tune, scan ...) or a spontaneous change (antenna connection, + * failure, AF switching, meta data reception... */ +enum { + RADIO_EVENT_HW_FAILURE = 0, /* hardware module failure. Requires reopening the tuner */ + RADIO_EVENT_CONFIG = 1, /* configuration change completed */ + RADIO_EVENT_ANTENNA = 2, /* Antenna connected, disconnected */ + RADIO_EVENT_TUNED = 3, /* tune, step, scan completed */ + RADIO_EVENT_METADATA = 4, /* New meta data received */ + RADIO_EVENT_TA = 5, /* Traffic announcement start or stop */ + RADIO_EVENT_AF_SWITCH = 6, /* Switch to Alternate Frequency */ + // begin framework only events + RADIO_EVENT_CONTROL = 100, /* loss/gain of tuner control */ + RADIO_EVENT_SERVER_DIED = 101, /* radio service died */ +}; +typedef unsigned int radio_event_type_t; + +/* Event passed to the framework by the HAL callback */ +typedef struct radio_hal_event { + radio_event_type_t type; /* event type */ + int status; /* used by RADIO_EVENT_CONFIG, RADIO_EVENT_TUNED */ + union { + bool on; /* RADIO_EVENT_ANTENNA, RADIO_EVENT_TA */ + radio_hal_band_config_t config; /* RADIO_EVENT_CONFIG */ + radio_program_info_t info; /* RADIO_EVENT_TUNED, RADIO_EVENT_AF_SWITCH */ + radio_metadata_t *metadata; /* RADIO_EVENT_METADATA */ + }; +} radio_hal_event_t; + +/* Used internally by the framework. Same information as in struct radio_hal_event */ +typedef struct radio_event { + radio_event_type_t type; + int status; + union { + bool on; + radio_band_config_t config; + radio_program_info_t info; + radio_metadata_t *metadata; /* offset from start of struct when in shared memory */ + }; +} radio_event_t; + + +static radio_rds_t radio_rds_for_region(bool rds, radio_region_t region) { + if (!rds) + return RADIO_RDS_NONE; + switch(region) { + case RADIO_REGION_ITU_1: + case RADIO_REGION_OIRT: + case RADIO_REGION_JAPAN: + case RADIO_REGION_KOREA: + return RADIO_RDS_WORLD; + case RADIO_REGION_ITU_2: + return RADIO_RDS_US; + default: + return RADIO_REGION_NONE; + } +} + +static radio_deemphasis_t radio_demephasis_for_region(radio_region_t region) { + switch(region) { + case RADIO_REGION_KOREA: + case RADIO_REGION_ITU_2: + return RADIO_DEEMPHASIS_75; + case RADIO_REGION_ITU_1: + case RADIO_REGION_OIRT: + case RADIO_REGION_JAPAN: + default: + return RADIO_DEEMPHASIS_50; + } +} + +#endif // ANDROID_RADIO_H diff --git a/phonelibs/android_system_core/include/system/thread_defs.h b/phonelibs/android_system_core/include/system/thread_defs.h new file mode 100644 index 0000000000..377a48ce92 --- /dev/null +++ b/phonelibs/android_system_core/include/system/thread_defs.h @@ -0,0 +1,77 @@ +/* + * 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_THREAD_DEFS_H +#define ANDROID_THREAD_DEFS_H + +#include "graphics.h" + +#if defined(__cplusplus) +extern "C" { +#endif + +enum { + /* + * *********************************************** + * ** Keep in sync with android.os.Process.java ** + * *********************************************** + * + * This maps directly to the "nice" priorities we use in Android. + * A thread priority should be chosen inverse-proportionally to + * the amount of work the thread is expected to do. The more work + * a thread will do, the less favorable priority it should get so that + * it doesn't starve the system. Threads not behaving properly might + * be "punished" by the kernel. + * Use the levels below when appropriate. Intermediate values are + * acceptable, preferably use the {MORE|LESS}_FAVORABLE constants below. + */ + ANDROID_PRIORITY_LOWEST = 19, + + /* use for background tasks */ + ANDROID_PRIORITY_BACKGROUND = 10, + + /* most threads run at normal priority */ + ANDROID_PRIORITY_NORMAL = 0, + + /* threads currently running a UI that the user is interacting with */ + ANDROID_PRIORITY_FOREGROUND = -2, + + /* the main UI thread has a slightly more favorable priority */ + ANDROID_PRIORITY_DISPLAY = -4, + + /* ui service treads might want to run at a urgent display (uncommon) */ + ANDROID_PRIORITY_URGENT_DISPLAY = HAL_PRIORITY_URGENT_DISPLAY, + + /* all normal audio threads */ + ANDROID_PRIORITY_AUDIO = -16, + + /* service audio threads (uncommon) */ + ANDROID_PRIORITY_URGENT_AUDIO = -19, + + /* should never be used in practice. regular process might not + * be allowed to use this level */ + ANDROID_PRIORITY_HIGHEST = -20, + + ANDROID_PRIORITY_DEFAULT = ANDROID_PRIORITY_NORMAL, + ANDROID_PRIORITY_MORE_FAVORABLE = -1, + ANDROID_PRIORITY_LESS_FAVORABLE = +1, +}; + +#if defined(__cplusplus) +} +#endif + +#endif /* ANDROID_THREAD_DEFS_H */ diff --git a/phonelibs/android_system_core/include/system/window.h b/phonelibs/android_system_core/include/system/window.h new file mode 100644 index 0000000000..508ce00bac --- /dev/null +++ b/phonelibs/android_system_core/include/system/window.h @@ -0,0 +1,954 @@ +/* + * 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 SYSTEM_CORE_INCLUDE_ANDROID_WINDOW_H +#define SYSTEM_CORE_INCLUDE_ANDROID_WINDOW_H + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef __UNUSED +#define __UNUSED __attribute__((__unused__)) +#endif +#ifndef __deprecated +#define __deprecated __attribute__((__deprecated__)) +#endif + +__BEGIN_DECLS + +/*****************************************************************************/ + +#define ANDROID_NATIVE_MAKE_CONSTANT(a,b,c,d) \ + (((unsigned)(a)<<24)|((unsigned)(b)<<16)|((unsigned)(c)<<8)|(unsigned)(d)) + +#define ANDROID_NATIVE_WINDOW_MAGIC \ + ANDROID_NATIVE_MAKE_CONSTANT('_','w','n','d') + +#define ANDROID_NATIVE_BUFFER_MAGIC \ + ANDROID_NATIVE_MAKE_CONSTANT('_','b','f','r') + +// --------------------------------------------------------------------------- + +// This #define may be used to conditionally compile device-specific code to +// support either the prior ANativeWindow interface, which did not pass libsync +// fences around, or the new interface that does. This #define is only present +// when the ANativeWindow interface does include libsync support. +#define ANDROID_NATIVE_WINDOW_HAS_SYNC 1 + +// --------------------------------------------------------------------------- + +typedef const native_handle_t* buffer_handle_t; + +// --------------------------------------------------------------------------- + +typedef struct android_native_rect_t +{ + int32_t left; + int32_t top; + int32_t right; + int32_t bottom; +} android_native_rect_t; + +// --------------------------------------------------------------------------- + +typedef struct android_native_base_t +{ + /* a magic value defined by the actual EGL native type */ + int magic; + + /* the sizeof() of the actual EGL native type */ + int version; + + void* reserved[4]; + + /* reference-counting interface */ + void (*incRef)(struct android_native_base_t* base); + void (*decRef)(struct android_native_base_t* base); +} android_native_base_t; + +typedef struct ANativeWindowBuffer +{ +#ifdef __cplusplus + ANativeWindowBuffer() { + common.magic = ANDROID_NATIVE_BUFFER_MAGIC; + common.version = sizeof(ANativeWindowBuffer); + memset(common.reserved, 0, sizeof(common.reserved)); + } + + // Implement the methods that sp expects so that it + // can be used to automatically refcount ANativeWindowBuffer's. + void incStrong(const void* /*id*/) const { + common.incRef(const_cast(&common)); + } + void decStrong(const void* /*id*/) const { + common.decRef(const_cast(&common)); + } +#endif + + struct android_native_base_t common; + + int width; + int height; + int stride; + int format; + int usage; + + void* reserved[2]; + + buffer_handle_t handle; + + void* reserved_proc[8]; +} ANativeWindowBuffer_t; + +// Old typedef for backwards compatibility. +typedef ANativeWindowBuffer_t android_native_buffer_t; + +// --------------------------------------------------------------------------- + +/* attributes queriable with query() */ +enum { + NATIVE_WINDOW_WIDTH = 0, + NATIVE_WINDOW_HEIGHT = 1, + NATIVE_WINDOW_FORMAT = 2, + + /* The minimum number of buffers that must remain un-dequeued after a buffer + * has been queued. This value applies only if set_buffer_count was used to + * override the number of buffers and if a buffer has since been queued. + * Users of the set_buffer_count ANativeWindow method should query this + * value before calling set_buffer_count. If it is necessary to have N + * buffers simultaneously dequeued as part of the steady-state operation, + * and this query returns M then N+M buffers should be requested via + * native_window_set_buffer_count. + * + * Note that this value does NOT apply until a single buffer has been + * queued. In particular this means that it is possible to: + * + * 1. Query M = min undequeued buffers + * 2. Set the buffer count to N + M + * 3. Dequeue all N + M buffers + * 4. Cancel M buffers + * 5. Queue, dequeue, queue, dequeue, ad infinitum + */ + NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS = 3, + + /* Check whether queueBuffer operations on the ANativeWindow send the buffer + * to the window compositor. The query sets the returned 'value' argument + * to 1 if the ANativeWindow DOES send queued buffers directly to the window + * compositor and 0 if the buffers do not go directly to the window + * compositor. + * + * This can be used to determine whether protected buffer content should be + * sent to the ANativeWindow. Note, however, that a result of 1 does NOT + * indicate that queued buffers will be protected from applications or users + * capturing their contents. If that behavior is desired then some other + * mechanism (e.g. the GRALLOC_USAGE_PROTECTED flag) should be used in + * conjunction with this query. + */ + NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER = 4, + + /* Get the concrete type of a ANativeWindow. See below for the list of + * possible return values. + * + * This query should not be used outside the Android framework and will + * likely be removed in the near future. + */ + NATIVE_WINDOW_CONCRETE_TYPE = 5, + + + /* + * Default width and height of ANativeWindow buffers, these are the + * dimensions of the window buffers irrespective of the + * NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS call and match the native window + * size unless overridden by NATIVE_WINDOW_SET_BUFFERS_USER_DIMENSIONS. + */ + NATIVE_WINDOW_DEFAULT_WIDTH = 6, + NATIVE_WINDOW_DEFAULT_HEIGHT = 7, + + /* + * transformation that will most-likely be applied to buffers. This is only + * a hint, the actual transformation applied might be different. + * + * INTENDED USE: + * + * The transform hint can be used by a producer, for instance the GLES + * driver, to pre-rotate the rendering such that the final transformation + * in the composer is identity. This can be very useful when used in + * conjunction with the h/w composer HAL, in situations where it + * cannot handle arbitrary rotations. + * + * 1. Before dequeuing a buffer, the GL driver (or any other ANW client) + * queries the ANW for NATIVE_WINDOW_TRANSFORM_HINT. + * + * 2. The GL driver overrides the width and height of the ANW to + * account for NATIVE_WINDOW_TRANSFORM_HINT. This is done by querying + * NATIVE_WINDOW_DEFAULT_{WIDTH | HEIGHT}, swapping the dimensions + * according to NATIVE_WINDOW_TRANSFORM_HINT and calling + * native_window_set_buffers_dimensions(). + * + * 3. The GL driver dequeues a buffer of the new pre-rotated size. + * + * 4. The GL driver renders to the buffer such that the image is + * already transformed, that is applying NATIVE_WINDOW_TRANSFORM_HINT + * to the rendering. + * + * 5. The GL driver calls native_window_set_transform to apply + * inverse transformation to the buffer it just rendered. + * In order to do this, the GL driver needs + * to calculate the inverse of NATIVE_WINDOW_TRANSFORM_HINT, this is + * done easily: + * + * int hintTransform, inverseTransform; + * query(..., NATIVE_WINDOW_TRANSFORM_HINT, &hintTransform); + * inverseTransform = hintTransform; + * if (hintTransform & HAL_TRANSFORM_ROT_90) + * inverseTransform ^= HAL_TRANSFORM_ROT_180; + * + * + * 6. The GL driver queues the pre-transformed buffer. + * + * 7. The composer combines the buffer transform with the display + * transform. If the buffer transform happens to cancel out the + * display transform then no rotation is needed. + * + */ + NATIVE_WINDOW_TRANSFORM_HINT = 8, + + /* + * Boolean that indicates whether the consumer is running more than + * one buffer behind the producer. + */ + NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND = 9, + + /* + * The consumer gralloc usage bits currently set by the consumer. + * The values are defined in hardware/libhardware/include/gralloc.h. + */ + NATIVE_WINDOW_CONSUMER_USAGE_BITS = 10, + + /** + * Transformation that will by applied to buffers by the hwcomposer. + * This must not be set or checked by producer endpoints, and will + * disable the transform hint set in SurfaceFlinger (see + * NATIVE_WINDOW_TRANSFORM_HINT). + * + * INTENDED USE: + * Temporary - Please do not use this. This is intended only to be used + * by the camera's LEGACY mode. + * + * In situations where a SurfaceFlinger client wishes to set a transform + * that is not visible to the producer, and will always be applied in the + * hardware composer, the client can set this flag with + * native_window_set_buffers_sticky_transform. This can be used to rotate + * and flip buffers consumed by hardware composer without actually changing + * the aspect ratio of the buffers produced. + */ + NATIVE_WINDOW_STICKY_TRANSFORM = 11, + + /** + * The default data space for the buffers as set by the consumer. + * The values are defined in graphics.h. + */ + NATIVE_WINDOW_DEFAULT_DATASPACE = 12, + + /* + * Returns the age of the contents of the most recently dequeued buffer as + * the number of frames that have elapsed since it was last queued. For + * example, if the window is double-buffered, the age of any given buffer in + * steady state will be 2. If the dequeued buffer has never been queued, its + * age will be 0. + */ + NATIVE_WINDOW_BUFFER_AGE = 13, +}; + +/* Valid operations for the (*perform)() hook. + * + * Values marked as 'deprecated' are supported, but have been superceded by + * other functionality. + * + * Values marked as 'private' should be considered private to the framework. + * HAL implementation code with access to an ANativeWindow should not use these, + * as it may not interact properly with the framework's use of the + * ANativeWindow. + */ +enum { + NATIVE_WINDOW_SET_USAGE = 0, + NATIVE_WINDOW_CONNECT = 1, /* deprecated */ + NATIVE_WINDOW_DISCONNECT = 2, /* deprecated */ + NATIVE_WINDOW_SET_CROP = 3, /* private */ + NATIVE_WINDOW_SET_BUFFER_COUNT = 4, + NATIVE_WINDOW_SET_BUFFERS_GEOMETRY = 5, /* deprecated */ + NATIVE_WINDOW_SET_BUFFERS_TRANSFORM = 6, + NATIVE_WINDOW_SET_BUFFERS_TIMESTAMP = 7, + NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS = 8, + NATIVE_WINDOW_SET_BUFFERS_FORMAT = 9, + NATIVE_WINDOW_SET_SCALING_MODE = 10, /* private */ + NATIVE_WINDOW_LOCK = 11, /* private */ + NATIVE_WINDOW_UNLOCK_AND_POST = 12, /* private */ + NATIVE_WINDOW_API_CONNECT = 13, /* private */ + NATIVE_WINDOW_API_DISCONNECT = 14, /* private */ + NATIVE_WINDOW_SET_BUFFERS_USER_DIMENSIONS = 15, /* private */ + NATIVE_WINDOW_SET_POST_TRANSFORM_CROP = 16, /* private */ + NATIVE_WINDOW_SET_BUFFERS_STICKY_TRANSFORM = 17,/* private */ + NATIVE_WINDOW_SET_SIDEBAND_STREAM = 18, + NATIVE_WINDOW_SET_BUFFERS_DATASPACE = 19, + NATIVE_WINDOW_SET_SURFACE_DAMAGE = 20, /* private */ +}; + +/* parameter for NATIVE_WINDOW_[API_][DIS]CONNECT */ +enum { + /* Buffers will be queued by EGL via eglSwapBuffers after being filled using + * OpenGL ES. + */ + NATIVE_WINDOW_API_EGL = 1, + + /* Buffers will be queued after being filled using the CPU + */ + NATIVE_WINDOW_API_CPU = 2, + + /* Buffers will be queued by Stagefright after being filled by a video + * decoder. The video decoder can either be a software or hardware decoder. + */ + NATIVE_WINDOW_API_MEDIA = 3, + + /* Buffers will be queued by the the camera HAL. + */ + NATIVE_WINDOW_API_CAMERA = 4, +}; + +/* parameter for NATIVE_WINDOW_SET_BUFFERS_TRANSFORM */ +enum { + /* flip source image horizontally */ + NATIVE_WINDOW_TRANSFORM_FLIP_H = HAL_TRANSFORM_FLIP_H , + /* flip source image vertically */ + NATIVE_WINDOW_TRANSFORM_FLIP_V = HAL_TRANSFORM_FLIP_V, + /* rotate source image 90 degrees clock-wise, and is applied after TRANSFORM_FLIP_{H|V} */ + NATIVE_WINDOW_TRANSFORM_ROT_90 = HAL_TRANSFORM_ROT_90, + /* rotate source image 180 degrees */ + NATIVE_WINDOW_TRANSFORM_ROT_180 = HAL_TRANSFORM_ROT_180, + /* rotate source image 270 degrees clock-wise */ + NATIVE_WINDOW_TRANSFORM_ROT_270 = HAL_TRANSFORM_ROT_270, + /* transforms source by the inverse transform of the screen it is displayed onto. This + * transform is applied last */ + NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY = 0x08 +}; + +/* parameter for NATIVE_WINDOW_SET_SCALING_MODE */ +enum { + /* the window content is not updated (frozen) until a buffer of + * the window size is received (enqueued) + */ + NATIVE_WINDOW_SCALING_MODE_FREEZE = 0, + /* the buffer is scaled in both dimensions to match the window size */ + NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW = 1, + /* the buffer is scaled uniformly such that the smaller dimension + * of the buffer matches the window size (cropping in the process) + */ + NATIVE_WINDOW_SCALING_MODE_SCALE_CROP = 2, + /* the window is clipped to the size of the buffer's crop rectangle; pixels + * outside the crop rectangle are treated as if they are completely + * transparent. + */ + NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP = 3, +}; + +/* values returned by the NATIVE_WINDOW_CONCRETE_TYPE query */ +enum { + NATIVE_WINDOW_FRAMEBUFFER = 0, /* FramebufferNativeWindow */ + NATIVE_WINDOW_SURFACE = 1, /* Surface */ +}; + +/* parameter for NATIVE_WINDOW_SET_BUFFERS_TIMESTAMP + * + * Special timestamp value to indicate that timestamps should be auto-generated + * by the native window when queueBuffer is called. This is equal to INT64_MIN, + * defined directly to avoid problems with C99/C++ inclusion of stdint.h. + */ +static const int64_t NATIVE_WINDOW_TIMESTAMP_AUTO = (-9223372036854775807LL-1); + +struct ANativeWindow +{ +#ifdef __cplusplus + ANativeWindow() + : flags(0), minSwapInterval(0), maxSwapInterval(0), xdpi(0), ydpi(0) + { + common.magic = ANDROID_NATIVE_WINDOW_MAGIC; + common.version = sizeof(ANativeWindow); + memset(common.reserved, 0, sizeof(common.reserved)); + } + + /* Implement the methods that sp expects so that it + can be used to automatically refcount ANativeWindow's. */ + void incStrong(const void* /*id*/) const { + common.incRef(const_cast(&common)); + } + void decStrong(const void* /*id*/) const { + common.decRef(const_cast(&common)); + } +#endif + + struct android_native_base_t common; + + /* flags describing some attributes of this surface or its updater */ + const uint32_t flags; + + /* min swap interval supported by this updated */ + const int minSwapInterval; + + /* max swap interval supported by this updated */ + const int maxSwapInterval; + + /* horizontal and vertical resolution in DPI */ + const float xdpi; + const float ydpi; + + /* Some storage reserved for the OEM's driver. */ + intptr_t oem[4]; + + /* + * Set the swap interval for this surface. + * + * Returns 0 on success or -errno on error. + */ + int (*setSwapInterval)(struct ANativeWindow* window, + int interval); + + /* + * Hook called by EGL to acquire a buffer. After this call, the buffer + * is not locked, so its content cannot be modified. This call may block if + * no buffers are available. + * + * The window holds a reference to the buffer between dequeueBuffer and + * either queueBuffer or cancelBuffer, so clients only need their own + * reference if they might use the buffer after queueing or canceling it. + * Holding a reference to a buffer after queueing or canceling it is only + * allowed if a specific buffer count has been set. + * + * Returns 0 on success or -errno on error. + * + * XXX: This function is deprecated. It will continue to work for some + * time for binary compatibility, but the new dequeueBuffer function that + * outputs a fence file descriptor should be used in its place. + */ + int (*dequeueBuffer_DEPRECATED)(struct ANativeWindow* window, + struct ANativeWindowBuffer** buffer); + + /* + * hook called by EGL to lock a buffer. This MUST be called before modifying + * the content of a buffer. The buffer must have been acquired with + * dequeueBuffer first. + * + * Returns 0 on success or -errno on error. + * + * XXX: This function is deprecated. It will continue to work for some + * time for binary compatibility, but it is essentially a no-op, and calls + * to it should be removed. + */ + int (*lockBuffer_DEPRECATED)(struct ANativeWindow* window, + struct ANativeWindowBuffer* buffer); + + /* + * Hook called by EGL when modifications to the render buffer are done. + * This unlocks and post the buffer. + * + * The window holds a reference to the buffer between dequeueBuffer and + * either queueBuffer or cancelBuffer, so clients only need their own + * reference if they might use the buffer after queueing or canceling it. + * Holding a reference to a buffer after queueing or canceling it is only + * allowed if a specific buffer count has been set. + * + * Buffers MUST be queued in the same order than they were dequeued. + * + * Returns 0 on success or -errno on error. + * + * XXX: This function is deprecated. It will continue to work for some + * time for binary compatibility, but the new queueBuffer function that + * takes a fence file descriptor should be used in its place (pass a value + * of -1 for the fence file descriptor if there is no valid one to pass). + */ + int (*queueBuffer_DEPRECATED)(struct ANativeWindow* window, + struct ANativeWindowBuffer* buffer); + + /* + * hook used to retrieve information about the native window. + * + * Returns 0 on success or -errno on error. + */ + int (*query)(const struct ANativeWindow* window, + int what, int* value); + + /* + * hook used to perform various operations on the surface. + * (*perform)() is a generic mechanism to add functionality to + * ANativeWindow while keeping backward binary compatibility. + * + * DO NOT CALL THIS HOOK DIRECTLY. Instead, use the helper functions + * defined below. + * + * (*perform)() returns -ENOENT if the 'what' parameter is not supported + * by the surface's implementation. + * + * See above for a list of valid operations, such as + * NATIVE_WINDOW_SET_USAGE or NATIVE_WINDOW_CONNECT + */ + int (*perform)(struct ANativeWindow* window, + int operation, ... ); + + /* + * Hook used to cancel a buffer that has been dequeued. + * No synchronization is performed between dequeue() and cancel(), so + * either external synchronization is needed, or these functions must be + * called from the same thread. + * + * The window holds a reference to the buffer between dequeueBuffer and + * either queueBuffer or cancelBuffer, so clients only need their own + * reference if they might use the buffer after queueing or canceling it. + * Holding a reference to a buffer after queueing or canceling it is only + * allowed if a specific buffer count has been set. + * + * XXX: This function is deprecated. It will continue to work for some + * time for binary compatibility, but the new cancelBuffer function that + * takes a fence file descriptor should be used in its place (pass a value + * of -1 for the fence file descriptor if there is no valid one to pass). + */ + int (*cancelBuffer_DEPRECATED)(struct ANativeWindow* window, + struct ANativeWindowBuffer* buffer); + + /* + * Hook called by EGL to acquire a buffer. This call may block if no + * buffers are available. + * + * The window holds a reference to the buffer between dequeueBuffer and + * either queueBuffer or cancelBuffer, so clients only need their own + * reference if they might use the buffer after queueing or canceling it. + * Holding a reference to a buffer after queueing or canceling it is only + * allowed if a specific buffer count has been set. + * + * The libsync fence file descriptor returned in the int pointed to by the + * fenceFd argument will refer to the fence that must signal before the + * dequeued buffer may be written to. A value of -1 indicates that the + * caller may access the buffer immediately without waiting on a fence. If + * a valid file descriptor is returned (i.e. any value except -1) then the + * caller is responsible for closing the file descriptor. + * + * Returns 0 on success or -errno on error. + */ + int (*dequeueBuffer)(struct ANativeWindow* window, + struct ANativeWindowBuffer** buffer, int* fenceFd); + + /* + * Hook called by EGL when modifications to the render buffer are done. + * This unlocks and post the buffer. + * + * The window holds a reference to the buffer between dequeueBuffer and + * either queueBuffer or cancelBuffer, so clients only need their own + * reference if they might use the buffer after queueing or canceling it. + * Holding a reference to a buffer after queueing or canceling it is only + * allowed if a specific buffer count has been set. + * + * The fenceFd argument specifies a libsync fence file descriptor for a + * fence that must signal before the buffer can be accessed. If the buffer + * can be accessed immediately then a value of -1 should be used. The + * caller must not use the file descriptor after it is passed to + * queueBuffer, and the ANativeWindow implementation is responsible for + * closing it. + * + * Returns 0 on success or -errno on error. + */ + int (*queueBuffer)(struct ANativeWindow* window, + struct ANativeWindowBuffer* buffer, int fenceFd); + + /* + * Hook used to cancel a buffer that has been dequeued. + * No synchronization is performed between dequeue() and cancel(), so + * either external synchronization is needed, or these functions must be + * called from the same thread. + * + * The window holds a reference to the buffer between dequeueBuffer and + * either queueBuffer or cancelBuffer, so clients only need their own + * reference if they might use the buffer after queueing or canceling it. + * Holding a reference to a buffer after queueing or canceling it is only + * allowed if a specific buffer count has been set. + * + * The fenceFd argument specifies a libsync fence file decsriptor for a + * fence that must signal before the buffer can be accessed. If the buffer + * can be accessed immediately then a value of -1 should be used. + * + * Note that if the client has not waited on the fence that was returned + * from dequeueBuffer, that same fence should be passed to cancelBuffer to + * ensure that future uses of the buffer are preceded by a wait on that + * fence. The caller must not use the file descriptor after it is passed + * to cancelBuffer, and the ANativeWindow implementation is responsible for + * closing it. + * + * Returns 0 on success or -errno on error. + */ + int (*cancelBuffer)(struct ANativeWindow* window, + struct ANativeWindowBuffer* buffer, int fenceFd); +}; + + /* Backwards compatibility: use ANativeWindow (struct ANativeWindow in C). + * android_native_window_t is deprecated. + */ +typedef struct ANativeWindow ANativeWindow; +typedef struct ANativeWindow android_native_window_t __deprecated; + +/* + * native_window_set_usage(..., usage) + * Sets the intended usage flags for the next buffers + * acquired with (*lockBuffer)() and on. + * By default (if this function is never called), a usage of + * GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE + * is assumed. + * Calling this function will usually cause following buffers to be + * reallocated. + */ + +static inline int native_window_set_usage( + struct ANativeWindow* window, int usage) +{ + return window->perform(window, NATIVE_WINDOW_SET_USAGE, usage); +} + +/* deprecated. Always returns 0. Don't call. */ +static inline int native_window_connect( + struct ANativeWindow* window __UNUSED, int api __UNUSED) __deprecated; + +static inline int native_window_connect( + struct ANativeWindow* window __UNUSED, int api __UNUSED) { + return 0; +} + +/* deprecated. Always returns 0. Don't call. */ +static inline int native_window_disconnect( + struct ANativeWindow* window __UNUSED, int api __UNUSED) __deprecated; + +static inline int native_window_disconnect( + struct ANativeWindow* window __UNUSED, int api __UNUSED) { + return 0; +} + +/* + * native_window_set_crop(..., crop) + * Sets which region of the next queued buffers needs to be considered. + * Depending on the scaling mode, a buffer's crop region is scaled and/or + * cropped to match the surface's size. This function sets the crop in + * pre-transformed buffer pixel coordinates. + * + * The specified crop region applies to all buffers queued after it is called. + * + * If 'crop' is NULL, subsequently queued buffers won't be cropped. + * + * An error is returned if for instance the crop region is invalid, out of the + * buffer's bound or if the window is invalid. + */ +static inline int native_window_set_crop( + struct ANativeWindow* window, + android_native_rect_t const * crop) +{ + return window->perform(window, NATIVE_WINDOW_SET_CROP, crop); +} + +/* + * native_window_set_post_transform_crop(..., crop) + * Sets which region of the next queued buffers needs to be considered. + * Depending on the scaling mode, a buffer's crop region is scaled and/or + * cropped to match the surface's size. This function sets the crop in + * post-transformed pixel coordinates. + * + * The specified crop region applies to all buffers queued after it is called. + * + * If 'crop' is NULL, subsequently queued buffers won't be cropped. + * + * An error is returned if for instance the crop region is invalid, out of the + * buffer's bound or if the window is invalid. + */ +static inline int native_window_set_post_transform_crop( + struct ANativeWindow* window, + android_native_rect_t const * crop) +{ + return window->perform(window, NATIVE_WINDOW_SET_POST_TRANSFORM_CROP, crop); +} + +/* + * native_window_set_active_rect(..., active_rect) + * + * This function is deprecated and will be removed soon. For now it simply + * sets the post-transform crop for compatibility while multi-project commits + * get checked. + */ +static inline int native_window_set_active_rect( + struct ANativeWindow* window, + android_native_rect_t const * active_rect) __deprecated; + +static inline int native_window_set_active_rect( + struct ANativeWindow* window, + android_native_rect_t const * active_rect) +{ + return native_window_set_post_transform_crop(window, active_rect); +} + +/* + * native_window_set_buffer_count(..., count) + * Sets the number of buffers associated with this native window. + */ +static inline int native_window_set_buffer_count( + struct ANativeWindow* window, + size_t bufferCount) +{ + return window->perform(window, NATIVE_WINDOW_SET_BUFFER_COUNT, bufferCount); +} + +/* + * native_window_set_buffers_geometry(..., int w, int h, int format) + * All buffers dequeued after this call will have the dimensions and format + * specified. A successful call to this function has the same effect as calling + * native_window_set_buffers_size and native_window_set_buffers_format. + * + * XXX: This function is deprecated. The native_window_set_buffers_dimensions + * and native_window_set_buffers_format functions should be used instead. + */ +static inline int native_window_set_buffers_geometry( + struct ANativeWindow* window, + int w, int h, int format) __deprecated; + +static inline int native_window_set_buffers_geometry( + struct ANativeWindow* window, + int w, int h, int format) +{ + return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_GEOMETRY, + w, h, format); +} + +/* + * native_window_set_buffers_dimensions(..., int w, int h) + * All buffers dequeued after this call will have the dimensions specified. + * In particular, all buffers will have a fixed-size, independent from the + * native-window size. They will be scaled according to the scaling mode + * (see native_window_set_scaling_mode) upon window composition. + * + * If w and h are 0, the normal behavior is restored. That is, dequeued buffers + * following this call will be sized to match the window's size. + * + * Calling this function will reset the window crop to a NULL value, which + * disables cropping of the buffers. + */ +static inline int native_window_set_buffers_dimensions( + struct ANativeWindow* window, + int w, int h) +{ + return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS, + w, h); +} + +/* + * native_window_set_buffers_user_dimensions(..., int w, int h) + * + * Sets the user buffer size for the window, which overrides the + * window's size. All buffers dequeued after this call will have the + * dimensions specified unless overridden by + * native_window_set_buffers_dimensions. All buffers will have a + * fixed-size, independent from the native-window size. They will be + * scaled according to the scaling mode (see + * native_window_set_scaling_mode) upon window composition. + * + * If w and h are 0, the normal behavior is restored. That is, the + * default buffer size will match the windows's size. + * + * Calling this function will reset the window crop to a NULL value, which + * disables cropping of the buffers. + */ +static inline int native_window_set_buffers_user_dimensions( + struct ANativeWindow* window, + int w, int h) +{ + return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_USER_DIMENSIONS, + w, h); +} + +/* + * native_window_set_buffers_format(..., int format) + * All buffers dequeued after this call will have the format specified. + * + * If the specified format is 0, the default buffer format will be used. + */ +static inline int native_window_set_buffers_format( + struct ANativeWindow* window, + int format) +{ + return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_FORMAT, format); +} + +/* + * native_window_set_buffers_data_space(..., int dataSpace) + * All buffers queued after this call will be associated with the dataSpace + * parameter specified. + * + * dataSpace specifies additional information about the buffer that's dependent + * on the buffer format and the endpoints. For example, it can be used to convey + * the color space of the image data in the buffer, or it can be used to + * indicate that the buffers contain depth measurement data instead of color + * images. The default dataSpace is 0, HAL_DATASPACE_UNKNOWN, unless it has been + * overridden by the consumer. + */ +static inline int native_window_set_buffers_data_space( + struct ANativeWindow* window, + android_dataspace_t dataSpace) +{ + return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_DATASPACE, + dataSpace); +} + +/* + * native_window_set_buffers_transform(..., int transform) + * All buffers queued after this call will be displayed transformed according + * to the transform parameter specified. + */ +static inline int native_window_set_buffers_transform( + struct ANativeWindow* window, + int transform) +{ + return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_TRANSFORM, + transform); +} + +/* + * native_window_set_buffers_sticky_transform(..., int transform) + * All buffers queued after this call will be displayed transformed according + * to the transform parameter specified applied on top of the regular buffer + * transform. Setting this transform will disable the transform hint. + * + * Temporary - This is only intended to be used by the LEGACY camera mode, do + * not use this for anything else. + */ +static inline int native_window_set_buffers_sticky_transform( + struct ANativeWindow* window, + int transform) +{ + return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_STICKY_TRANSFORM, + transform); +} + +/* + * native_window_set_buffers_timestamp(..., int64_t timestamp) + * All buffers queued after this call will be associated with the timestamp + * parameter specified. If the timestamp is set to NATIVE_WINDOW_TIMESTAMP_AUTO + * (the default), timestamps will be generated automatically when queueBuffer is + * called. The timestamp is measured in nanoseconds, and is normally monotonically + * increasing. The timestamp should be unaffected by time-of-day adjustments, + * and for a camera should be strictly monotonic but for a media player may be + * reset when the position is set. + */ +static inline int native_window_set_buffers_timestamp( + struct ANativeWindow* window, + int64_t timestamp) +{ + return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_TIMESTAMP, + timestamp); +} + +/* + * native_window_set_scaling_mode(..., int mode) + * All buffers queued after this call will be associated with the scaling mode + * specified. + */ +static inline int native_window_set_scaling_mode( + struct ANativeWindow* window, + int mode) +{ + return window->perform(window, NATIVE_WINDOW_SET_SCALING_MODE, + mode); +} + +/* + * native_window_api_connect(..., int api) + * connects an API to this window. only one API can be connected at a time. + * Returns -EINVAL if for some reason the window cannot be connected, which + * can happen if it's connected to some other API. + */ +static inline int native_window_api_connect( + struct ANativeWindow* window, int api) +{ + return window->perform(window, NATIVE_WINDOW_API_CONNECT, api); +} + +/* + * native_window_api_disconnect(..., int api) + * disconnect the API from this window. + * An error is returned if for instance the window wasn't connected in the + * first place. + */ +static inline int native_window_api_disconnect( + struct ANativeWindow* window, int api) +{ + return window->perform(window, NATIVE_WINDOW_API_DISCONNECT, api); +} + +/* + * native_window_dequeue_buffer_and_wait(...) + * Dequeue a buffer and wait on the fence associated with that buffer. The + * buffer may safely be accessed immediately upon this function returning. An + * error is returned if either of the dequeue or the wait operations fail. + */ +static inline int native_window_dequeue_buffer_and_wait(ANativeWindow *anw, + struct ANativeWindowBuffer** anb) { + return anw->dequeueBuffer_DEPRECATED(anw, anb); +} + +/* + * native_window_set_sideband_stream(..., native_handle_t*) + * Attach a sideband buffer stream to a native window. + */ +static inline int native_window_set_sideband_stream( + struct ANativeWindow* window, + native_handle_t* sidebandHandle) +{ + return window->perform(window, NATIVE_WINDOW_SET_SIDEBAND_STREAM, + sidebandHandle); +} + +/* + * native_window_set_surface_damage(..., android_native_rect_t* rects, int numRects) + * Set the surface damage (i.e., the region of the surface that has changed + * since the previous frame). The damage set by this call will be reset (to the + * default of full-surface damage) after calling queue, so this must be called + * prior to every frame with damage that does not cover the whole surface if the + * caller desires downstream consumers to use this optimization. + * + * The damage region is specified as an array of rectangles, with the important + * caveat that the origin of the surface is considered to be the bottom-left + * corner, as in OpenGL ES. + * + * If numRects is set to 0, rects may be NULL, and the surface damage will be + * set to the full surface (the same as if this function had not been called for + * this frame). + */ +static inline int native_window_set_surface_damage( + struct ANativeWindow* window, + const android_native_rect_t* rects, size_t numRects) +{ + return window->perform(window, NATIVE_WINDOW_SET_SURFACE_DAMAGE, + rects, numRects); +} + +__END_DECLS + +#endif /* SYSTEM_CORE_INCLUDE_ANDROID_WINDOW_H */ diff --git a/phonelibs/android_system_core/include/utils/AndroidThreads.h b/phonelibs/android_system_core/include/utils/AndroidThreads.h new file mode 100644 index 0000000000..aad1e82cb7 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/AndroidThreads.h @@ -0,0 +1,125 @@ +/* + * 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 _LIBS_UTILS_ANDROID_THREADS_H +#define _LIBS_UTILS_ANDROID_THREADS_H + +#include +#include + +#if !defined(_WIN32) +# include +#endif + +#include + +// --------------------------------------------------------------------------- +// C API + +#ifdef __cplusplus +extern "C" { +#endif + +// Create and run a new thread. +extern int androidCreateThread(android_thread_func_t, void *); + +// Create thread with lots of parameters +extern int androidCreateThreadEtc(android_thread_func_t entryFunction, + void *userData, + const char* threadName, + int32_t threadPriority, + size_t threadStackSize, + android_thread_id_t *threadId); + +// Get some sort of unique identifier for the current thread. +extern android_thread_id_t androidGetThreadId(); + +// Low-level thread creation -- never creates threads that can +// interact with the Java VM. +extern int androidCreateRawThreadEtc(android_thread_func_t entryFunction, + void *userData, + const char* threadName, + int32_t threadPriority, + size_t threadStackSize, + android_thread_id_t *threadId); + +// set the same of the running thread +extern void androidSetThreadName(const char* name); + +// Used by the Java Runtime to control how threads are created, so that +// they can be proper and lovely Java threads. +typedef int (*android_create_thread_fn)(android_thread_func_t entryFunction, + void *userData, + const char* threadName, + int32_t threadPriority, + size_t threadStackSize, + android_thread_id_t *threadId); + +extern void androidSetCreateThreadFunc(android_create_thread_fn func); + +// ------------------------------------------------------------------ +// Extra functions working with raw pids. + +#ifdef HAVE_ANDROID_OS +// Change the priority AND scheduling group of a particular thread. The priority +// should be one of the ANDROID_PRIORITY constants. Returns INVALID_OPERATION +// if the priority set failed, else another value if just the group set failed; +// in either case errno is set. Thread ID zero means current thread. +extern int androidSetThreadPriority(pid_t tid, int prio); + +// Get the current priority of a particular thread. Returns one of the +// ANDROID_PRIORITY constants or a negative result in case of error. +extern int androidGetThreadPriority(pid_t tid); +#endif + +#ifdef __cplusplus +} // extern "C" +#endif + +// ---------------------------------------------------------------------------- +// C++ API +#ifdef __cplusplus +namespace android { +// ---------------------------------------------------------------------------- + +// Create and run a new thread. +inline bool createThread(thread_func_t f, void *a) { + return androidCreateThread(f, a) ? true : false; +} + +// Create thread with lots of parameters +inline bool createThreadEtc(thread_func_t entryFunction, + void *userData, + const char* threadName = "android:unnamed_thread", + int32_t threadPriority = PRIORITY_DEFAULT, + size_t threadStackSize = 0, + thread_id_t *threadId = 0) +{ + return androidCreateThreadEtc(entryFunction, userData, threadName, + threadPriority, threadStackSize, threadId) ? true : false; +} + +// Get some sort of unique identifier for the current thread. +inline thread_id_t getThreadId() { + return androidGetThreadId(); +} + +// ---------------------------------------------------------------------------- +}; // namespace android +#endif // __cplusplus +// ---------------------------------------------------------------------------- + +#endif // _LIBS_UTILS_ANDROID_THREADS_H diff --git a/phonelibs/android_system_core/include/utils/Atomic.h b/phonelibs/android_system_core/include/utils/Atomic.h new file mode 100644 index 0000000000..7eb476c94e --- /dev/null +++ b/phonelibs/android_system_core/include/utils/Atomic.h @@ -0,0 +1,22 @@ +/* + * 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_UTILS_ATOMIC_H +#define ANDROID_UTILS_ATOMIC_H + +#include + +#endif // ANDROID_UTILS_ATOMIC_H diff --git a/phonelibs/android_system_core/include/utils/BasicHashtable.h b/phonelibs/android_system_core/include/utils/BasicHashtable.h new file mode 100644 index 0000000000..c235d62526 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/BasicHashtable.h @@ -0,0 +1,402 @@ +/* + * 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_BASIC_HASHTABLE_H +#define ANDROID_BASIC_HASHTABLE_H + +#include +#include +#include +#include + +namespace android { + +/* Implementation type. Nothing to see here. */ +class BasicHashtableImpl { +protected: + struct Bucket { + // The collision flag indicates that the bucket is part of a collision chain + // such that at least two entries both hash to this bucket. When true, we + // may need to seek further along the chain to find the entry. + static const uint32_t COLLISION = 0x80000000UL; + + // The present flag indicates that the bucket contains an initialized entry value. + static const uint32_t PRESENT = 0x40000000UL; + + // Mask for 30 bits worth of the hash code that are stored within the bucket to + // speed up lookups and rehashing by eliminating the need to recalculate the + // hash code of the entry's key. + static const uint32_t HASH_MASK = 0x3fffffffUL; + + // Combined value that stores the collision and present flags as well as + // a 30 bit hash code. + uint32_t cookie; + + // Storage for the entry begins here. + char entry[0]; + }; + + BasicHashtableImpl(size_t entrySize, bool hasTrivialDestructor, + size_t minimumInitialCapacity, float loadFactor); + BasicHashtableImpl(const BasicHashtableImpl& other); + virtual ~BasicHashtableImpl(); + + void dispose(); + + inline void edit() { + if (mBuckets && !SharedBuffer::bufferFromData(mBuckets)->onlyOwner()) { + clone(); + } + } + + void setTo(const BasicHashtableImpl& other); + void clear(); + + ssize_t next(ssize_t index) const; + ssize_t find(ssize_t index, hash_t hash, const void* __restrict__ key) const; + size_t add(hash_t hash, const void* __restrict__ entry); + void removeAt(size_t index); + void rehash(size_t minimumCapacity, float loadFactor); + + const size_t mBucketSize; // number of bytes per bucket including the entry + const bool mHasTrivialDestructor; // true if the entry type does not require destruction + size_t mCapacity; // number of buckets that can be filled before exceeding load factor + float mLoadFactor; // load factor + size_t mSize; // number of elements actually in the table + size_t mFilledBuckets; // number of buckets for which collision or present is true + size_t mBucketCount; // number of slots in the mBuckets array + void* mBuckets; // array of buckets, as a SharedBuffer + + inline const Bucket& bucketAt(const void* __restrict__ buckets, size_t index) const { + return *reinterpret_cast( + static_cast(buckets) + index * mBucketSize); + } + + inline Bucket& bucketAt(void* __restrict__ buckets, size_t index) const { + return *reinterpret_cast(static_cast(buckets) + index * mBucketSize); + } + + virtual bool compareBucketKey(const Bucket& bucket, const void* __restrict__ key) const = 0; + virtual void initializeBucketEntry(Bucket& bucket, const void* __restrict__ entry) const = 0; + virtual void destroyBucketEntry(Bucket& bucket) const = 0; + +private: + void clone(); + + // Allocates a bucket array as a SharedBuffer. + void* allocateBuckets(size_t count) const; + + // Releases a bucket array's associated SharedBuffer. + void releaseBuckets(void* __restrict__ buckets, size_t count) const; + + // Destroys the contents of buckets (invokes destroyBucketEntry for each + // populated bucket if needed). + void destroyBuckets(void* __restrict__ buckets, size_t count) const; + + // Copies the content of buckets (copies the cookie and invokes copyBucketEntry + // for each populated bucket if needed). + void copyBuckets(const void* __restrict__ fromBuckets, + void* __restrict__ toBuckets, size_t count) const; + + // Determines the appropriate size of a bucket array to store a certain minimum + // number of entries and returns its effective capacity. + static void determineCapacity(size_t minimumCapacity, float loadFactor, + size_t* __restrict__ outBucketCount, size_t* __restrict__ outCapacity); + + // Trim a hash code to 30 bits to match what we store in the bucket's cookie. + inline static hash_t trimHash(hash_t hash) { + return (hash & Bucket::HASH_MASK) ^ (hash >> 30); + } + + // Returns the index of the first bucket that is in the collision chain + // for the specified hash code, given the total number of buckets. + // (Primary hash) + inline static size_t chainStart(hash_t hash, size_t count) { + return hash % count; + } + + // Returns the increment to add to a bucket index to seek to the next bucket + // in the collision chain for the specified hash code, given the total number of buckets. + // (Secondary hash) + inline static size_t chainIncrement(hash_t hash, size_t count) { + return ((hash >> 7) | (hash << 25)) % (count - 1) + 1; + } + + // Returns the index of the next bucket that is in the collision chain + // that is defined by the specified increment, given the total number of buckets. + inline static size_t chainSeek(size_t index, size_t increment, size_t count) { + return (index + increment) % count; + } +}; + +/* + * A BasicHashtable stores entries that are indexed by hash code in place + * within an array. The basic operations are finding entries by key, + * adding new entries and removing existing entries. + * + * This class provides a very limited set of operations with simple semantics. + * It is intended to be used as a building block to construct more complex + * and interesting data structures such as HashMap. Think very hard before + * adding anything extra to BasicHashtable, it probably belongs at a + * higher level of abstraction. + * + * TKey: The key type. + * TEntry: The entry type which is what is actually stored in the array. + * + * TKey must support the following contract: + * bool operator==(const TKey& other) const; // return true if equal + * bool operator!=(const TKey& other) const; // return true if unequal + * + * TEntry must support the following contract: + * const TKey& getKey() const; // get the key from the entry + * + * This class supports storing entries with duplicate keys. Of course, it can't + * tell them apart during removal so only the first entry will be removed. + * We do this because it means that operations like add() can't fail. + */ +template +class BasicHashtable : private BasicHashtableImpl { +public: + /* Creates a hashtable with the specified minimum initial capacity. + * The underlying array will be created when the first entry is added. + * + * minimumInitialCapacity: The minimum initial capacity for the hashtable. + * Default is 0. + * loadFactor: The desired load factor for the hashtable, between 0 and 1. + * Default is 0.75. + */ + BasicHashtable(size_t minimumInitialCapacity = 0, float loadFactor = 0.75f); + + /* Copies a hashtable. + * The underlying storage is shared copy-on-write. + */ + BasicHashtable(const BasicHashtable& other); + + /* Clears and destroys the hashtable. + */ + virtual ~BasicHashtable(); + + /* Making this hashtable a copy of the other hashtable. + * The underlying storage is shared copy-on-write. + * + * other: The hashtable to copy. + */ + inline BasicHashtable& operator =(const BasicHashtable & other) { + setTo(other); + return *this; + } + + /* Returns the number of entries in the hashtable. + */ + inline size_t size() const { + return mSize; + } + + /* Returns the capacity of the hashtable, which is the number of elements that can + * added to the hashtable without requiring it to be grown. + */ + inline size_t capacity() const { + return mCapacity; + } + + /* Returns the number of buckets that the hashtable has, which is the size of its + * underlying array. + */ + inline size_t bucketCount() const { + return mBucketCount; + } + + /* Returns the load factor of the hashtable. */ + inline float loadFactor() const { + return mLoadFactor; + }; + + /* Returns a const reference to the entry at the specified index. + * + * index: The index of the entry to retrieve. Must be a valid index within + * the bounds of the hashtable. + */ + inline const TEntry& entryAt(size_t index) const { + return entryFor(bucketAt(mBuckets, index)); + } + + /* Returns a non-const reference to the entry at the specified index. + * + * index: The index of the entry to edit. Must be a valid index within + * the bounds of the hashtable. + */ + inline TEntry& editEntryAt(size_t index) { + edit(); + return entryFor(bucketAt(mBuckets, index)); + } + + /* Clears the hashtable. + * All entries in the hashtable are destroyed immediately. + * If you need to do something special with the entries in the hashtable then iterate + * over them and do what you need before clearing the hashtable. + */ + inline void clear() { + BasicHashtableImpl::clear(); + } + + /* Returns the index of the next entry in the hashtable given the index of a previous entry. + * If the given index is -1, then returns the index of the first entry in the hashtable, + * if there is one, or -1 otherwise. + * If the given index is not -1, then returns the index of the next entry in the hashtable, + * in strictly increasing order, or -1 if there are none left. + * + * index: The index of the previous entry that was iterated, or -1 to begin + * iteration at the beginning of the hashtable. + */ + inline ssize_t next(ssize_t index) const { + return BasicHashtableImpl::next(index); + } + + /* Finds the index of an entry with the specified key. + * If the given index is -1, then returns the index of the first matching entry, + * otherwise returns the index of the next matching entry. + * If the hashtable contains multiple entries with keys that match the requested + * key, then the sequence of entries returned is arbitrary. + * Returns -1 if no entry was found. + * + * index: The index of the previous entry with the specified key, or -1 to + * find the first matching entry. + * hash: The hashcode of the key. + * key: The key. + */ + inline ssize_t find(ssize_t index, hash_t hash, const TKey& key) const { + return BasicHashtableImpl::find(index, hash, &key); + } + + /* Adds the entry to the hashtable. + * Returns the index of the newly added entry. + * If an entry with the same key already exists, then a duplicate entry is added. + * If the entry will not fit, then the hashtable's capacity is increased and + * its contents are rehashed. See rehash(). + * + * hash: The hashcode of the key. + * entry: The entry to add. + */ + inline size_t add(hash_t hash, const TEntry& entry) { + return BasicHashtableImpl::add(hash, &entry); + } + + /* Removes the entry with the specified index from the hashtable. + * The entry is destroyed immediately. + * The index must be valid. + * + * The hashtable is not compacted after an item is removed, so it is legal + * to continue iterating over the hashtable using next() or find(). + * + * index: The index of the entry to remove. Must be a valid index within the + * bounds of the hashtable, and it must refer to an existing entry. + */ + inline void removeAt(size_t index) { + BasicHashtableImpl::removeAt(index); + } + + /* Rehashes the contents of the hashtable. + * Grows the hashtable to at least the specified minimum capacity or the + * current number of elements, whichever is larger. + * + * Rehashing causes all entries to be copied and the entry indices may change. + * Although the hash codes are cached by the hashtable, rehashing can be an + * expensive operation and should be avoided unless the hashtable's size + * needs to be changed. + * + * Rehashing is the only way to change the capacity or load factor of the + * hashtable once it has been created. It can be used to compact the + * hashtable by choosing a minimum capacity that is smaller than the current + * capacity (such as 0). + * + * minimumCapacity: The desired minimum capacity after rehashing. + * loadFactor: The desired load factor after rehashing. + */ + inline void rehash(size_t minimumCapacity, float loadFactor) { + BasicHashtableImpl::rehash(minimumCapacity, loadFactor); + } + + /* Determines whether there is room to add another entry without rehashing. + * When this returns true, a subsequent add() operation is guaranteed to + * complete without performing a rehash. + */ + inline bool hasMoreRoom() const { + return mCapacity > mFilledBuckets; + } + +protected: + static inline const TEntry& entryFor(const Bucket& bucket) { + return reinterpret_cast(bucket.entry); + } + + static inline TEntry& entryFor(Bucket& bucket) { + return reinterpret_cast(bucket.entry); + } + + virtual bool compareBucketKey(const Bucket& bucket, const void* __restrict__ key) const; + virtual void initializeBucketEntry(Bucket& bucket, const void* __restrict__ entry) const; + virtual void destroyBucketEntry(Bucket& bucket) const; + +private: + // For dumping the raw contents of a hashtable during testing. + friend class BasicHashtableTest; + inline uint32_t cookieAt(size_t index) const { + return bucketAt(mBuckets, index).cookie; + } +}; + +template +BasicHashtable::BasicHashtable(size_t minimumInitialCapacity, float loadFactor) : + BasicHashtableImpl(sizeof(TEntry), traits::has_trivial_dtor, + minimumInitialCapacity, loadFactor) { +} + +template +BasicHashtable::BasicHashtable(const BasicHashtable& other) : + BasicHashtableImpl(other) { +} + +template +BasicHashtable::~BasicHashtable() { + dispose(); +} + +template +bool BasicHashtable::compareBucketKey(const Bucket& bucket, + const void* __restrict__ key) const { + return entryFor(bucket).getKey() == *static_cast(key); +} + +template +void BasicHashtable::initializeBucketEntry(Bucket& bucket, + const void* __restrict__ entry) const { + if (!traits::has_trivial_copy) { + new (&entryFor(bucket)) TEntry(*(static_cast(entry))); + } else { + memcpy(&entryFor(bucket), entry, sizeof(TEntry)); + } +} + +template +void BasicHashtable::destroyBucketEntry(Bucket& bucket) const { + if (!traits::has_trivial_dtor) { + entryFor(bucket).~TEntry(); + } +} + +}; // namespace android + +#endif // ANDROID_BASIC_HASHTABLE_H diff --git a/phonelibs/android_system_core/include/utils/BitSet.h b/phonelibs/android_system_core/include/utils/BitSet.h new file mode 100644 index 0000000000..8c612931de --- /dev/null +++ b/phonelibs/android_system_core/include/utils/BitSet.h @@ -0,0 +1,294 @@ +/* + * 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 UTILS_BITSET_H +#define UTILS_BITSET_H + +#include +#include + +/* + * Contains some bit manipulation helpers. + */ + +namespace android { + +// A simple set of 32 bits that can be individually marked or cleared. +struct BitSet32 { + uint32_t value; + + inline BitSet32() : value(0UL) { } + explicit inline BitSet32(uint32_t value) : value(value) { } + + // Gets the value associated with a particular bit index. + static inline uint32_t valueForBit(uint32_t n) { return 0x80000000UL >> n; } + + // Clears the bit set. + inline void clear() { clear(value); } + + static inline void clear(uint32_t& value) { value = 0UL; } + + // Returns the number of marked bits in the set. + inline uint32_t count() const { return count(value); } + + static inline uint32_t count(uint32_t value) { return __builtin_popcountl(value); } + + // Returns true if the bit set does not contain any marked bits. + inline bool isEmpty() const { return isEmpty(value); } + + static inline bool isEmpty(uint32_t value) { return ! value; } + + // Returns true if the bit set does not contain any unmarked bits. + inline bool isFull() const { return isFull(value); } + + static inline bool isFull(uint32_t value) { return value == 0xffffffffUL; } + + // Returns true if the specified bit is marked. + inline bool hasBit(uint32_t n) const { return hasBit(value, n); } + + static inline bool hasBit(uint32_t value, uint32_t n) { return value & valueForBit(n); } + + // Marks the specified bit. + inline void markBit(uint32_t n) { markBit(value, n); } + + static inline void markBit (uint32_t& value, uint32_t n) { value |= valueForBit(n); } + + // Clears the specified bit. + inline void clearBit(uint32_t n) { clearBit(value, n); } + + static inline void clearBit(uint32_t& value, uint32_t n) { value &= ~ valueForBit(n); } + + // Finds the first marked bit in the set. + // Result is undefined if all bits are unmarked. + inline uint32_t firstMarkedBit() const { return firstMarkedBit(value); } + + static uint32_t firstMarkedBit(uint32_t value) { return clz_checked(value); } + + // Finds the first unmarked bit in the set. + // Result is undefined if all bits are marked. + inline uint32_t firstUnmarkedBit() const { return firstUnmarkedBit(value); } + + static inline uint32_t firstUnmarkedBit(uint32_t value) { return clz_checked(~ value); } + + // Finds the last marked bit in the set. + // Result is undefined if all bits are unmarked. + inline uint32_t lastMarkedBit() const { return lastMarkedBit(value); } + + static inline uint32_t lastMarkedBit(uint32_t value) { return 31 - ctz_checked(value); } + + // Finds the first marked bit in the set and clears it. Returns the bit index. + // Result is undefined if all bits are unmarked. + inline uint32_t clearFirstMarkedBit() { return clearFirstMarkedBit(value); } + + static inline uint32_t clearFirstMarkedBit(uint32_t& value) { + uint32_t n = firstMarkedBit(value); + clearBit(value, n); + return n; + } + + // Finds the first unmarked bit in the set and marks it. Returns the bit index. + // Result is undefined if all bits are marked. + inline uint32_t markFirstUnmarkedBit() { return markFirstUnmarkedBit(value); } + + static inline uint32_t markFirstUnmarkedBit(uint32_t& value) { + uint32_t n = firstUnmarkedBit(value); + markBit(value, n); + return n; + } + + // Finds the last marked bit in the set and clears it. Returns the bit index. + // Result is undefined if all bits are unmarked. + inline uint32_t clearLastMarkedBit() { return clearLastMarkedBit(value); } + + static inline uint32_t clearLastMarkedBit(uint32_t& value) { + uint32_t n = lastMarkedBit(value); + clearBit(value, n); + return n; + } + + // Gets the index of the specified bit in the set, which is the number of + // marked bits that appear before the specified bit. + inline uint32_t getIndexOfBit(uint32_t n) const { + return getIndexOfBit(value, n); + } + + static inline uint32_t getIndexOfBit(uint32_t value, uint32_t n) { + return __builtin_popcountl(value & ~(0xffffffffUL >> n)); + } + + inline bool operator== (const BitSet32& other) const { return value == other.value; } + inline bool operator!= (const BitSet32& other) const { return value != other.value; } + inline BitSet32 operator& (const BitSet32& other) const { + return BitSet32(value & other.value); + } + inline BitSet32& operator&= (const BitSet32& other) { + value &= other.value; + return *this; + } + inline BitSet32 operator| (const BitSet32& other) const { + return BitSet32(value | other.value); + } + inline BitSet32& operator|= (const BitSet32& other) { + value |= other.value; + return *this; + } + +private: + // We use these helpers as the signature of __builtin_c{l,t}z has "unsigned int" for the + // input, which is only guaranteed to be 16b, not 32. The compiler should optimize this away. + static inline uint32_t clz_checked(uint32_t value) { + if (sizeof(unsigned int) == sizeof(uint32_t)) { + return __builtin_clz(value); + } else { + return __builtin_clzl(value); + } + } + + static inline uint32_t ctz_checked(uint32_t value) { + if (sizeof(unsigned int) == sizeof(uint32_t)) { + return __builtin_ctz(value); + } else { + return __builtin_ctzl(value); + } + } +}; + +ANDROID_BASIC_TYPES_TRAITS(BitSet32) + +// A simple set of 64 bits that can be individually marked or cleared. +struct BitSet64 { + uint64_t value; + + inline BitSet64() : value(0ULL) { } + explicit inline BitSet64(uint64_t value) : value(value) { } + + // Gets the value associated with a particular bit index. + static inline uint64_t valueForBit(uint32_t n) { return 0x8000000000000000ULL >> n; } + + // Clears the bit set. + inline void clear() { clear(value); } + + static inline void clear(uint64_t& value) { value = 0ULL; } + + // Returns the number of marked bits in the set. + inline uint32_t count() const { return count(value); } + + static inline uint32_t count(uint64_t value) { return __builtin_popcountll(value); } + + // Returns true if the bit set does not contain any marked bits. + inline bool isEmpty() const { return isEmpty(value); } + + static inline bool isEmpty(uint64_t value) { return ! value; } + + // Returns true if the bit set does not contain any unmarked bits. + inline bool isFull() const { return isFull(value); } + + static inline bool isFull(uint64_t value) { return value == 0xffffffffffffffffULL; } + + // Returns true if the specified bit is marked. + inline bool hasBit(uint32_t n) const { return hasBit(value, n); } + + static inline bool hasBit(uint64_t value, uint32_t n) { return value & valueForBit(n); } + + // Marks the specified bit. + inline void markBit(uint32_t n) { markBit(value, n); } + + static inline void markBit(uint64_t& value, uint32_t n) { value |= valueForBit(n); } + + // Clears the specified bit. + inline void clearBit(uint32_t n) { clearBit(value, n); } + + static inline void clearBit(uint64_t& value, uint32_t n) { value &= ~ valueForBit(n); } + + // Finds the first marked bit in the set. + // Result is undefined if all bits are unmarked. + inline uint32_t firstMarkedBit() const { return firstMarkedBit(value); } + + static inline uint32_t firstMarkedBit(uint64_t value) { return __builtin_clzll(value); } + + // Finds the first unmarked bit in the set. + // Result is undefined if all bits are marked. + inline uint32_t firstUnmarkedBit() const { return firstUnmarkedBit(value); } + + static inline uint32_t firstUnmarkedBit(uint64_t value) { return __builtin_clzll(~ value); } + + // Finds the last marked bit in the set. + // Result is undefined if all bits are unmarked. + inline uint32_t lastMarkedBit() const { return lastMarkedBit(value); } + + static inline uint32_t lastMarkedBit(uint64_t value) { return 63 - __builtin_ctzll(value); } + + // Finds the first marked bit in the set and clears it. Returns the bit index. + // Result is undefined if all bits are unmarked. + inline uint32_t clearFirstMarkedBit() { return clearFirstMarkedBit(value); } + + static inline uint32_t clearFirstMarkedBit(uint64_t& value) { + uint64_t n = firstMarkedBit(value); + clearBit(value, n); + return n; + } + + // Finds the first unmarked bit in the set and marks it. Returns the bit index. + // Result is undefined if all bits are marked. + inline uint32_t markFirstUnmarkedBit() { return markFirstUnmarkedBit(value); } + + static inline uint32_t markFirstUnmarkedBit(uint64_t& value) { + uint64_t n = firstUnmarkedBit(value); + markBit(value, n); + return n; + } + + // Finds the last marked bit in the set and clears it. Returns the bit index. + // Result is undefined if all bits are unmarked. + inline uint32_t clearLastMarkedBit() { return clearLastMarkedBit(value); } + + static inline uint32_t clearLastMarkedBit(uint64_t& value) { + uint64_t n = lastMarkedBit(value); + clearBit(value, n); + return n; + } + + // Gets the index of the specified bit in the set, which is the number of + // marked bits that appear before the specified bit. + inline uint32_t getIndexOfBit(uint32_t n) const { return getIndexOfBit(value, n); } + + static inline uint32_t getIndexOfBit(uint64_t value, uint32_t n) { + return __builtin_popcountll(value & ~(0xffffffffffffffffULL >> n)); + } + + inline bool operator== (const BitSet64& other) const { return value == other.value; } + inline bool operator!= (const BitSet64& other) const { return value != other.value; } + inline BitSet64 operator& (const BitSet64& other) const { + return BitSet64(value & other.value); + } + inline BitSet64& operator&= (const BitSet64& other) { + value &= other.value; + return *this; + } + inline BitSet64 operator| (const BitSet64& other) const { + return BitSet64(value | other.value); + } + inline BitSet64& operator|= (const BitSet64& other) { + value |= other.value; + return *this; + } +}; + +ANDROID_BASIC_TYPES_TRAITS(BitSet64) + +} // namespace android + +#endif // UTILS_BITSET_H diff --git a/phonelibs/android_system_core/include/utils/BlobCache.h b/phonelibs/android_system_core/include/utils/BlobCache.h new file mode 100644 index 0000000000..65dca9fb45 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/BlobCache.h @@ -0,0 +1,249 @@ +/* + ** Copyright 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_BLOB_CACHE_H +#define ANDROID_BLOB_CACHE_H + +#include + +#include +#include +#include +#include + +namespace android { + +// A BlobCache is an in-memory cache for binary key/value pairs. A BlobCache +// does NOT provide any thread-safety guarantees. +// +// The cache contents can be serialized to an in-memory buffer or mmap'd file +// and then reloaded in a subsequent execution of the program. This +// serialization is non-portable and the data should only be used by the device +// that generated it. +class BlobCache : public RefBase { + +public: + + // Create an empty blob cache. The blob cache will cache key/value pairs + // with key and value sizes less than or equal to maxKeySize and + // maxValueSize, respectively. The total combined size of ALL cache entries + // (key sizes plus value sizes) will not exceed maxTotalSize. + BlobCache(size_t maxKeySize, size_t maxValueSize, size_t maxTotalSize); + + // set inserts a new binary value into the cache and associates it with the + // given binary key. If the key or value are too large for the cache then + // the cache remains unchanged. This includes the case where a different + // value was previously associated with the given key - the old value will + // remain in the cache. If the given key and value are small enough to be + // put in the cache (based on the maxKeySize, maxValueSize, and maxTotalSize + // values specified to the BlobCache constructor), then the key/value pair + // will be in the cache after set returns. Note, however, that a subsequent + // call to set may evict old key/value pairs from the cache. + // + // Preconditions: + // key != NULL + // 0 < keySize + // value != NULL + // 0 < valueSize + void set(const void* key, size_t keySize, const void* value, + size_t valueSize); + + // get retrieves from the cache the binary value associated with a given + // binary key. If the key is present in the cache then the length of the + // binary value associated with that key is returned. If the value argument + // is non-NULL and the size of the cached value is less than valueSize bytes + // then the cached value is copied into the buffer pointed to by the value + // argument. If the key is not present in the cache then 0 is returned and + // the buffer pointed to by the value argument is not modified. + // + // Note that when calling get multiple times with the same key, the later + // calls may fail, returning 0, even if earlier calls succeeded. The return + // value must be checked for each call. + // + // Preconditions: + // key != NULL + // 0 < keySize + // 0 <= valueSize + size_t get(const void* key, size_t keySize, void* value, size_t valueSize); + + + // getFlattenedSize returns the number of bytes needed to store the entire + // serialized cache. + size_t getFlattenedSize() const; + + // flatten serializes the current contents of the cache into the memory + // pointed to by 'buffer'. The serialized cache contents can later be + // loaded into a BlobCache object using the unflatten method. The contents + // of the BlobCache object will not be modified. + // + // Preconditions: + // size >= this.getFlattenedSize() + status_t flatten(void* buffer, size_t size) const; + + // unflatten replaces the contents of the cache with the serialized cache + // contents in the memory pointed to by 'buffer'. The previous contents of + // the BlobCache will be evicted from the cache. If an error occurs while + // unflattening the serialized cache contents then the BlobCache will be + // left in an empty state. + // + status_t unflatten(void const* buffer, size_t size); + +private: + // Copying is disallowed. + BlobCache(const BlobCache&); + void operator=(const BlobCache&); + + // A random function helper to get around MinGW not having nrand48() + long int blob_random(); + + // clean evicts a randomly chosen set of entries from the cache such that + // the total size of all remaining entries is less than mMaxTotalSize/2. + void clean(); + + // isCleanable returns true if the cache is full enough for the clean method + // to have some effect, and false otherwise. + bool isCleanable() const; + + // A Blob is an immutable sized unstructured data blob. + class Blob : public RefBase { + public: + Blob(const void* data, size_t size, bool copyData); + ~Blob(); + + bool operator<(const Blob& rhs) const; + + const void* getData() const; + size_t getSize() const; + + private: + // Copying is not allowed. + Blob(const Blob&); + void operator=(const Blob&); + + // mData points to the buffer containing the blob data. + const void* mData; + + // mSize is the size of the blob data in bytes. + size_t mSize; + + // mOwnsData indicates whether or not this Blob object should free the + // memory pointed to by mData when the Blob gets destructed. + bool mOwnsData; + }; + + // A CacheEntry is a single key/value pair in the cache. + class CacheEntry { + public: + CacheEntry(); + CacheEntry(const sp& key, const sp& value); + CacheEntry(const CacheEntry& ce); + + bool operator<(const CacheEntry& rhs) const; + const CacheEntry& operator=(const CacheEntry&); + + sp getKey() const; + sp getValue() const; + + void setValue(const sp& value); + + private: + + // mKey is the key that identifies the cache entry. + sp mKey; + + // mValue is the cached data associated with the key. + sp mValue; + }; + + // A Header is the header for the entire BlobCache serialization format. No + // need to make this portable, so we simply write the struct out. + struct Header { + // mMagicNumber is the magic number that identifies the data as + // serialized BlobCache contents. It must always contain 'Blb$'. + uint32_t mMagicNumber; + + // mBlobCacheVersion is the serialization format version. + uint32_t mBlobCacheVersion; + + // mDeviceVersion is the device-specific version of the cache. This can + // be used to invalidate the cache. + uint32_t mDeviceVersion; + + // mNumEntries is number of cache entries following the header in the + // data. + size_t mNumEntries; + + // mBuildId is the build id of the device when the cache was created. + // When an update to the build happens (via an OTA or other update) this + // is used to invalidate the cache. + int mBuildIdLength; + char mBuildId[]; + }; + + // An EntryHeader is the header for a serialized cache entry. No need to + // make this portable, so we simply write the struct out. Each EntryHeader + // is followed imediately by the key data and then the value data. + // + // The beginning of each serialized EntryHeader is 4-byte aligned, so the + // number of bytes that a serialized cache entry will occupy is: + // + // ((sizeof(EntryHeader) + keySize + valueSize) + 3) & ~3 + // + struct EntryHeader { + // mKeySize is the size of the entry key in bytes. + size_t mKeySize; + + // mValueSize is the size of the entry value in bytes. + size_t mValueSize; + + // mData contains both the key and value data for the cache entry. The + // key comes first followed immediately by the value. + uint8_t mData[]; + }; + + // mMaxKeySize is the maximum key size that will be cached. Calls to + // BlobCache::set with a keySize parameter larger than mMaxKeySize will + // simply not add the key/value pair to the cache. + const size_t mMaxKeySize; + + // mMaxValueSize is the maximum value size that will be cached. Calls to + // BlobCache::set with a valueSize parameter larger than mMaxValueSize will + // simply not add the key/value pair to the cache. + const size_t mMaxValueSize; + + // mMaxTotalSize is the maximum size that all cache entries can occupy. This + // includes space for both keys and values. When a call to BlobCache::set + // would otherwise cause this limit to be exceeded, either the key/value + // pair passed to BlobCache::set will not be cached or other cache entries + // will be evicted from the cache to make room for the new entry. + const size_t mMaxTotalSize; + + // mTotalSize is the total combined size of all keys and values currently in + // the cache. + size_t mTotalSize; + + // mRandState is the pseudo-random number generator state. It is passed to + // nrand48 to generate random numbers when needed. + unsigned short mRandState[3]; + + // mCacheEntries stores all the cache entries that are resident in memory. + // Cache entries are added to it by the 'set' method. + SortedVector mCacheEntries; +}; + +} + +#endif // ANDROID_BLOB_CACHE_H diff --git a/phonelibs/android_system_core/include/utils/ByteOrder.h b/phonelibs/android_system_core/include/utils/ByteOrder.h new file mode 100644 index 0000000000..baa3a83ddd --- /dev/null +++ b/phonelibs/android_system_core/include/utils/ByteOrder.h @@ -0,0 +1,81 @@ +/* + * 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 _LIBS_UTILS_BYTE_ORDER_H +#define _LIBS_UTILS_BYTE_ORDER_H + +#include +#include +#ifdef HAVE_WINSOCK +#include +#else +#include +#endif + +/* + * These macros are like the hton/ntoh byte swapping macros, + * except they allow you to swap to and from the "device" byte + * order. The device byte order is the endianness of the target + * device -- for the ARM CPUs we use today, this is little endian. + * + * Note that the byte swapping functions have not been optimized + * much; performance is currently not an issue for them since the + * intent is to allow us to avoid byte swapping on the device. + */ + +static inline uint32_t android_swap_long(uint32_t v) +{ + return (v<<24) | ((v<<8)&0x00FF0000) | ((v>>8)&0x0000FF00) | (v>>24); +} + +static inline uint16_t android_swap_short(uint16_t v) +{ + return (v<<8) | (v>>8); +} + +#define DEVICE_BYTE_ORDER LITTLE_ENDIAN + +#if BYTE_ORDER == DEVICE_BYTE_ORDER + +#define dtohl(x) (x) +#define dtohs(x) (x) +#define htodl(x) (x) +#define htods(x) (x) + +#else + +#define dtohl(x) (android_swap_long(x)) +#define dtohs(x) (android_swap_short(x)) +#define htodl(x) (android_swap_long(x)) +#define htods(x) (android_swap_short(x)) + +#endif + +#if BYTE_ORDER == LITTLE_ENDIAN +#define fromlel(x) (x) +#define fromles(x) (x) +#define tolel(x) (x) +#define toles(x) (x) +#else +#define fromlel(x) (android_swap_long(x)) +#define fromles(x) (android_swap_short(x)) +#define tolel(x) (android_swap_long(x)) +#define toles(x) (android_swap_short(x)) +#endif + +#endif // _LIBS_UTILS_BYTE_ORDER_H diff --git a/phonelibs/android_system_core/include/utils/CallStack.h b/phonelibs/android_system_core/include/utils/CallStack.h new file mode 100644 index 0000000000..27e89f4622 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/CallStack.h @@ -0,0 +1,72 @@ +/* + * 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_CALLSTACK_H +#define ANDROID_CALLSTACK_H + +#include +#include +#include +#include + +#include +#include + +namespace android { + +class Printer; + +// Collect/print the call stack (function, file, line) traces for a single thread. +class CallStack { +public: + // Create an empty call stack. No-op. + CallStack(); + // Create a callstack with the current thread's stack trace. + // Immediately dump it to logcat using the given logtag. + CallStack(const char* logtag, int32_t ignoreDepth=1); + ~CallStack(); + + // Reset the stack frames (same as creating an empty call stack). + void clear() { mFrameLines.clear(); } + + // Immediately collect the stack traces for the specified thread. + // The default is to dump the stack of the current call. + void update(int32_t ignoreDepth=1, pid_t tid=BACKTRACE_CURRENT_THREAD); + + // Dump a stack trace to the log using the supplied logtag. + void log(const char* logtag, + android_LogPriority priority = ANDROID_LOG_DEBUG, + const char* prefix = 0) const; + + // Dump a stack trace to the specified file descriptor. + void dump(int fd, int indent = 0, const char* prefix = 0) const; + + // Return a string (possibly very long) containing the complete stack trace. + String8 toString(const char* prefix = 0) const; + + // Dump a serialized representation of the stack trace to the specified printer. + void print(Printer& printer) const; + + // Get the count of stack frames that are in this call stack. + size_t size() const { return mFrameLines.size(); } + +private: + Vector mFrameLines; +}; + +}; // namespace android + +#endif // ANDROID_CALLSTACK_H diff --git a/phonelibs/android_system_core/include/utils/Compat.h b/phonelibs/android_system_core/include/utils/Compat.h new file mode 100644 index 0000000000..7d96310272 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/Compat.h @@ -0,0 +1,78 @@ +/* + * 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 __LIB_UTILS_COMPAT_H +#define __LIB_UTILS_COMPAT_H + +#include + +#if defined(__APPLE__) + +/* Mac OS has always had a 64-bit off_t, so it doesn't have off64_t. */ + +typedef off_t off64_t; + +static inline off64_t lseek64(int fd, off64_t offset, int whence) { + return lseek(fd, offset, whence); +} + +static inline ssize_t pread64(int fd, void* buf, size_t nbytes, off64_t offset) { + return pread(fd, buf, nbytes, offset); +} + +#endif /* __APPLE__ */ + +#if defined(_WIN32) +#define O_CLOEXEC O_NOINHERIT +#define O_NOFOLLOW 0 +#define DEFFILEMODE 0666 +#endif /* _WIN32 */ + +#if defined(_WIN32) +#define ZD "%ld" +#define ZD_TYPE long +#else +#define ZD "%zd" +#define ZD_TYPE ssize_t +#endif + +/* + * Needed for cases where something should be constexpr if possible, but not + * being constexpr is fine if in pre-C++11 code (such as a const static float + * member variable). + */ +#if __cplusplus >= 201103L +#define CONSTEXPR constexpr +#else +#define CONSTEXPR +#endif + +/* + * TEMP_FAILURE_RETRY is defined by some, but not all, versions of + * . (Alas, it is not as standard as we'd hoped!) So, if it's + * not already defined, then define it here. + */ +#ifndef TEMP_FAILURE_RETRY +/* Used to retry syscalls that can return EINTR. */ +#define TEMP_FAILURE_RETRY(exp) ({ \ + typeof (exp) _rc; \ + do { \ + _rc = (exp); \ + } while (_rc == -1 && errno == EINTR); \ + _rc; }) +#endif + +#endif /* __LIB_UTILS_COMPAT_H */ diff --git a/phonelibs/android_system_core/include/utils/Condition.h b/phonelibs/android_system_core/include/utils/Condition.h new file mode 100644 index 0000000000..5a7251982a --- /dev/null +++ b/phonelibs/android_system_core/include/utils/Condition.h @@ -0,0 +1,158 @@ +/* + * 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 _LIBS_UTILS_CONDITION_H +#define _LIBS_UTILS_CONDITION_H + +#include +#include +#include + +#if !defined(_WIN32) +# include +#endif + +#include +#include +#include + +// --------------------------------------------------------------------------- +namespace android { +// --------------------------------------------------------------------------- + +/* + * Condition variable class. The implementation is system-dependent. + * + * Condition variables are paired up with mutexes. Lock the mutex, + * call wait(), then either re-wait() if things aren't quite what you want, + * or unlock the mutex and continue. All threads calling wait() must + * use the same mutex for a given Condition. + */ +class Condition { +public: + enum { + PRIVATE = 0, + SHARED = 1 + }; + + enum WakeUpType { + WAKE_UP_ONE = 0, + WAKE_UP_ALL = 1 + }; + + Condition(); + Condition(int type); + ~Condition(); + // Wait on the condition variable. Lock the mutex before calling. + status_t wait(Mutex& mutex); + // same with relative timeout + status_t waitRelative(Mutex& mutex, nsecs_t reltime); + // Signal the condition variable, allowing exactly one thread to continue. + void signal(); + // Signal the condition variable, allowing one or all threads to continue. + void signal(WakeUpType type) { + if (type == WAKE_UP_ONE) { + signal(); + } else { + broadcast(); + } + } + // Signal the condition variable, allowing all threads to continue. + void broadcast(); + +private: +#if !defined(_WIN32) + pthread_cond_t mCond; +#else + void* mState; +#endif +}; + +// --------------------------------------------------------------------------- + +#if !defined(_WIN32) + +inline Condition::Condition() { + pthread_cond_init(&mCond, NULL); +} +inline Condition::Condition(int type) { + if (type == SHARED) { + pthread_condattr_t attr; + pthread_condattr_init(&attr); + pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); + pthread_cond_init(&mCond, &attr); + pthread_condattr_destroy(&attr); + } else { + pthread_cond_init(&mCond, NULL); + } +} +inline Condition::~Condition() { + pthread_cond_destroy(&mCond); +} +inline status_t Condition::wait(Mutex& mutex) { + return -pthread_cond_wait(&mCond, &mutex.mMutex); +} +inline status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime) { +#if defined(HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE) + struct timespec ts; + ts.tv_sec = reltime/1000000000; + ts.tv_nsec = reltime%1000000000; + return -pthread_cond_timedwait_relative_np(&mCond, &mutex.mMutex, &ts); +#else // HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE + struct timespec ts; +#if defined(__linux__) + clock_gettime(CLOCK_REALTIME, &ts); +#else // __APPLE__ + // we don't support the clocks here. + struct timeval t; + gettimeofday(&t, NULL); + ts.tv_sec = t.tv_sec; + ts.tv_nsec= t.tv_usec*1000; +#endif + ts.tv_sec += reltime/1000000000; + ts.tv_nsec+= reltime%1000000000; + if (ts.tv_nsec >= 1000000000) { + ts.tv_nsec -= 1000000000; + ts.tv_sec += 1; + } + return -pthread_cond_timedwait(&mCond, &mutex.mMutex, &ts); +#endif // HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE +} +inline void Condition::signal() { + /* + * POSIX says pthread_cond_signal wakes up "one or more" waiting threads. + * However bionic follows the glibc guarantee which wakes up "exactly one" + * waiting thread. + * + * man 3 pthread_cond_signal + * pthread_cond_signal restarts one of the threads that are waiting on + * the condition variable cond. If no threads are waiting on cond, + * nothing happens. If several threads are waiting on cond, exactly one + * is restarted, but it is not specified which. + */ + pthread_cond_signal(&mCond); +} +inline void Condition::broadcast() { + pthread_cond_broadcast(&mCond); +} + +#endif // !defined(_WIN32) + +// --------------------------------------------------------------------------- +}; // namespace android +// --------------------------------------------------------------------------- + +#endif // _LIBS_UTILS_CONDITON_H diff --git a/phonelibs/android_system_core/include/utils/Debug.h b/phonelibs/android_system_core/include/utils/Debug.h new file mode 100644 index 0000000000..08893bdaaf --- /dev/null +++ b/phonelibs/android_system_core/include/utils/Debug.h @@ -0,0 +1,48 @@ +/* + * 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_UTILS_DEBUG_H +#define ANDROID_UTILS_DEBUG_H + +#include +#include + +namespace android { +// --------------------------------------------------------------------------- + +#ifdef __cplusplus +template struct CompileTimeAssert; +template<> struct CompileTimeAssert {}; +#define COMPILE_TIME_ASSERT(_exp) \ + template class CompileTimeAssert< (_exp) >; +#endif +#define COMPILE_TIME_ASSERT_FUNCTION_SCOPE(_exp) \ + CompileTimeAssert<( _exp )>(); + +// --------------------------------------------------------------------------- + +#ifdef __cplusplus +template struct CompileTimeIfElse; +template +struct CompileTimeIfElse { typedef LHS TYPE; }; +template +struct CompileTimeIfElse { typedef RHS TYPE; }; +#endif + +// --------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_UTILS_DEBUG_H diff --git a/phonelibs/android_system_core/include/utils/Endian.h b/phonelibs/android_system_core/include/utils/Endian.h new file mode 100644 index 0000000000..591cae0d34 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/Endian.h @@ -0,0 +1,35 @@ +/* + * 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. + */ + +// +// Android endian-ness defines. +// +#ifndef _LIBS_UTILS_ENDIAN_H +#define _LIBS_UTILS_ENDIAN_H + +#if defined(__APPLE__) || defined(_WIN32) + +#define __BIG_ENDIAN 0x1000 +#define __LITTLE_ENDIAN 0x0001 +#define __BYTE_ORDER __LITTLE_ENDIAN + +#else + +#include + +#endif + +#endif /*_LIBS_UTILS_ENDIAN_H*/ diff --git a/phonelibs/android_system_core/include/utils/Errors.h b/phonelibs/android_system_core/include/utils/Errors.h new file mode 100644 index 0000000000..46173db4a3 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/Errors.h @@ -0,0 +1,88 @@ +/* + * 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_ERRORS_H +#define ANDROID_ERRORS_H + +#include +#include + +namespace android { + +// use this type to return error codes +#ifdef HAVE_MS_C_RUNTIME +typedef int status_t; +#else +typedef int32_t status_t; +#endif + +/* the MS C runtime lacks a few error codes */ + +/* + * Error codes. + * All error codes are negative values. + */ + +// Win32 #defines NO_ERROR as well. It has the same value, so there's no +// real conflict, though it's a bit awkward. +#ifdef _WIN32 +# undef NO_ERROR +#endif + +enum { + OK = 0, // Everything's swell. + NO_ERROR = 0, // No errors. + + UNKNOWN_ERROR = (-2147483647-1), // INT32_MIN value + + NO_MEMORY = -ENOMEM, + INVALID_OPERATION = -ENOSYS, + BAD_VALUE = -EINVAL, + BAD_TYPE = (UNKNOWN_ERROR + 1), + NAME_NOT_FOUND = -ENOENT, + PERMISSION_DENIED = -EPERM, + NO_INIT = -ENODEV, + ALREADY_EXISTS = -EEXIST, + DEAD_OBJECT = -EPIPE, + FAILED_TRANSACTION = (UNKNOWN_ERROR + 2), + JPARKS_BROKE_IT = -EPIPE, +#if !defined(HAVE_MS_C_RUNTIME) + BAD_INDEX = -EOVERFLOW, + NOT_ENOUGH_DATA = -ENODATA, + WOULD_BLOCK = -EWOULDBLOCK, + TIMED_OUT = -ETIMEDOUT, + UNKNOWN_TRANSACTION = -EBADMSG, +#else + BAD_INDEX = -E2BIG, + NOT_ENOUGH_DATA = (UNKNOWN_ERROR + 3), + WOULD_BLOCK = (UNKNOWN_ERROR + 4), + TIMED_OUT = (UNKNOWN_ERROR + 5), + UNKNOWN_TRANSACTION = (UNKNOWN_ERROR + 6), +#endif + FDS_NOT_ALLOWED = (UNKNOWN_ERROR + 7), +}; + +// Restore define; enumeration is in "android" namespace, so the value defined +// there won't work for Win32 code in a different namespace. +#ifdef _WIN32 +# define NO_ERROR 0L +#endif + +}; // namespace android + +// --------------------------------------------------------------------------- + +#endif // ANDROID_ERRORS_H diff --git a/phonelibs/android_system_core/include/utils/FileMap.h b/phonelibs/android_system_core/include/utils/FileMap.h new file mode 100644 index 0000000000..f70fc927e4 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/FileMap.h @@ -0,0 +1,126 @@ +/* + * 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. + */ + +// +// Encapsulate a shared file mapping. +// +#ifndef __LIBS_FILE_MAP_H +#define __LIBS_FILE_MAP_H + +#include + +#include + +#if defined(__MINGW32__) +// Ensure that we always pull in winsock2.h before windows.h +#ifdef HAVE_WINSOCK +#include +#endif +#include +#endif + +namespace android { + +/* + * This represents a memory-mapped file. It might be the entire file or + * only part of it. This requires a little bookkeeping because the mapping + * needs to be aligned on page boundaries, and in some cases we'd like to + * have multiple references to the mapped area without creating additional + * maps. + * + * This always uses MAP_SHARED. + * + * TODO: we should be able to create a new FileMap that is a subset of + * an existing FileMap and shares the underlying mapped pages. Requires + * completing the refcounting stuff and possibly introducing the notion + * of a FileMap hierarchy. + */ +class FileMap { +public: + FileMap(void); + + /* + * Create a new mapping on an open file. + * + * Closing the file descriptor does not unmap the pages, so we don't + * claim ownership of the fd. + * + * Returns "false" on failure. + */ + bool create(const char* origFileName, int fd, + off64_t offset, size_t length, bool readOnly); + + ~FileMap(void); + + /* + * Return the name of the file this map came from, if known. + */ + const char* getFileName(void) const { return mFileName; } + + /* + * Get a pointer to the piece of the file we requested. + */ + void* getDataPtr(void) const { return mDataPtr; } + + /* + * Get the length we requested. + */ + size_t getDataLength(void) const { return mDataLength; } + + /* + * Get the data offset used to create this map. + */ + off64_t getDataOffset(void) const { return mDataOffset; } + + /* + * This maps directly to madvise() values, but allows us to avoid + * including everywhere. + */ + enum MapAdvice { + NORMAL, RANDOM, SEQUENTIAL, WILLNEED, DONTNEED + }; + + /* + * Apply an madvise() call to the entire file. + * + * Returns 0 on success, -1 on failure. + */ + int advise(MapAdvice advice); + +protected: + +private: + // these are not implemented + FileMap(const FileMap& src); + const FileMap& operator=(const FileMap& src); + + char* mFileName; // original file name, if known + void* mBasePtr; // base of mmap area; page aligned + size_t mBaseLength; // length, measured from "mBasePtr" + off64_t mDataOffset; // offset used when map was created + void* mDataPtr; // start of requested data, offset from base + size_t mDataLength; // length, measured from "mDataPtr" +#if defined(__MINGW32__) + HANDLE mFileHandle; // Win32 file handle + HANDLE mFileMapping; // Win32 file mapping handle +#endif + + static long mPageSize; +}; + +}; // namespace android + +#endif // __LIBS_FILE_MAP_H diff --git a/phonelibs/android_system_core/include/utils/Flattenable.h b/phonelibs/android_system_core/include/utils/Flattenable.h new file mode 100644 index 0000000000..882a8b2499 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/Flattenable.h @@ -0,0 +1,198 @@ +/* + * 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_UTILS_FLATTENABLE_H +#define ANDROID_UTILS_FLATTENABLE_H + + +#include +#include +#include +#include + +namespace android { + + +class FlattenableUtils { +public: + template + static size_t align(size_t size) { + COMPILE_TIME_ASSERT_FUNCTION_SCOPE( !(N & (N-1)) ); + return (size + (N-1)) & ~(N-1); + } + + template + static size_t align(void const*& buffer) { + COMPILE_TIME_ASSERT_FUNCTION_SCOPE( !(N & (N-1)) ); + intptr_t b = intptr_t(buffer); + buffer = (void*)((intptr_t(buffer) + (N-1)) & ~(N-1)); + return size_t(intptr_t(buffer) - b); + } + + template + static size_t align(void*& buffer) { + return align( const_cast(buffer) ); + } + + static void advance(void*& buffer, size_t& size, size_t offset) { + buffer = reinterpret_cast( intptr_t(buffer) + offset ); + size -= offset; + } + + static void advance(void const*& buffer, size_t& size, size_t offset) { + buffer = reinterpret_cast( intptr_t(buffer) + offset ); + size -= offset; + } + + // write a POD structure + template + static void write(void*& buffer, size_t& size, const T& value) { + *static_cast(buffer) = value; + advance(buffer, size, sizeof(T)); + } + + // read a POD structure + template + static void read(void const*& buffer, size_t& size, T& value) { + value = *static_cast(buffer); + advance(buffer, size, sizeof(T)); + } +}; + + +/* + * The Flattenable protocol allows an object to serialize itself out + * to a byte-buffer and an array of file descriptors. + * Flattenable objects must implement this protocol. + */ + +template +class Flattenable { +public: + // size in bytes of the flattened object + inline size_t getFlattenedSize() const; + + // number of file descriptors to flatten + inline size_t getFdCount() const; + + // flattens the object into buffer. + // size should be at least of getFlattenedSize() + // file descriptors are written in the fds[] array but ownership is + // not transfered (ie: they must be dupped by the caller of + // flatten() if needed). + inline status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const; + + // unflattens the object from buffer. + // size should be equal to the value of getFlattenedSize() when the + // object was flattened. + // unflattened file descriptors are found in the fds[] array and + // don't need to be dupped(). ie: the caller of unflatten doesn't + // keep ownership. If a fd is not retained by unflatten() it must be + // explicitly closed. + inline status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count); +}; + +template +inline size_t Flattenable::getFlattenedSize() const { + return static_cast(this)->T::getFlattenedSize(); +} +template +inline size_t Flattenable::getFdCount() const { + return static_cast(this)->T::getFdCount(); +} +template +inline status_t Flattenable::flatten( + void*& buffer, size_t& size, int*& fds, size_t& count) const { + return static_cast(this)->T::flatten(buffer, size, fds, count); +} +template +inline status_t Flattenable::unflatten( + void const*& buffer, size_t& size, int const*& fds, size_t& count) { + return static_cast(this)->T::unflatten(buffer, size, fds, count); +} + +/* + * LightFlattenable is a protocol allowing object to serialize themselves out + * to a byte-buffer. Because it doesn't handle file-descriptors, + * LightFlattenable is usually more size efficient than Flattenable. + * LightFlattenable objects must implement this protocol. + */ +template +class LightFlattenable { +public: + // returns whether this object always flatten into the same size. + // for efficiency, this should always be inline. + inline bool isFixedSize() const; + + // returns size in bytes of the flattened object. must be a constant. + inline size_t getFlattenedSize() const; + + // flattens the object into buffer. + inline status_t flatten(void* buffer, size_t size) const; + + // unflattens the object from buffer of given size. + inline status_t unflatten(void const* buffer, size_t size); +}; + +template +inline bool LightFlattenable::isFixedSize() const { + return static_cast(this)->T::isFixedSize(); +} +template +inline size_t LightFlattenable::getFlattenedSize() const { + return static_cast(this)->T::getFlattenedSize(); +} +template +inline status_t LightFlattenable::flatten(void* buffer, size_t size) const { + return static_cast(this)->T::flatten(buffer, size); +} +template +inline status_t LightFlattenable::unflatten(void const* buffer, size_t size) { + return static_cast(this)->T::unflatten(buffer, size); +} + +/* + * LightFlattenablePod is an implementation of the LightFlattenable protocol + * for POD (plain-old-data) objects. + * Simply derive from LightFlattenablePod to make Foo flattenable; no + * need to implement any methods; obviously Foo must be a POD structure. + */ +template +class LightFlattenablePod : public LightFlattenable { +public: + inline bool isFixedSize() const { + return true; + } + + inline size_t getFlattenedSize() const { + return sizeof(T); + } + inline status_t flatten(void* buffer, size_t size) const { + if (size < sizeof(T)) return NO_MEMORY; + *reinterpret_cast(buffer) = *static_cast(this); + return NO_ERROR; + } + inline status_t unflatten(void const* buffer, size_t) { + *static_cast(this) = *reinterpret_cast(buffer); + return NO_ERROR; + } +}; + + +}; // namespace android + + +#endif /* ANDROID_UTILS_FLATTENABLE_H */ diff --git a/phonelibs/android_system_core/include/utils/Functor.h b/phonelibs/android_system_core/include/utils/Functor.h new file mode 100644 index 0000000000..09ea614b61 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/Functor.h @@ -0,0 +1,33 @@ +/* + * 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_FUNCTOR_H +#define ANDROID_FUNCTOR_H + +#include + +namespace android { + +class Functor { +public: + Functor() {} + virtual ~Functor() {} + virtual status_t operator ()(int /*what*/, void* /*data*/) { return NO_ERROR; } +}; + +}; // namespace android + +#endif // ANDROID_FUNCTOR_H diff --git a/phonelibs/android_system_core/include/utils/JenkinsHash.h b/phonelibs/android_system_core/include/utils/JenkinsHash.h new file mode 100644 index 0000000000..7da5dbd6a9 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/JenkinsHash.h @@ -0,0 +1,48 @@ +/* + * 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. + */ + +/* Implementation of Jenkins one-at-a-time hash function. These choices are + * optimized for code size and portability, rather than raw speed. But speed + * should still be quite good. + **/ + +#ifndef ANDROID_JENKINS_HASH_H +#define ANDROID_JENKINS_HASH_H + +#include + +namespace android { + +/* The Jenkins hash of a sequence of 32 bit words A, B, C is: + * Whiten(Mix(Mix(Mix(0, A), B), C)) */ + +inline uint32_t JenkinsHashMix(uint32_t hash, uint32_t data) { + hash += data; + hash += (hash << 10); + hash ^= (hash >> 6); + return hash; +} + +hash_t JenkinsHashWhiten(uint32_t hash); + +/* Helpful utility functions for hashing data in 32 bit chunks */ +uint32_t JenkinsHashMixBytes(uint32_t hash, const uint8_t* bytes, size_t size); + +uint32_t JenkinsHashMixShorts(uint32_t hash, const uint16_t* shorts, size_t size); + +} + +#endif // ANDROID_JENKINS_HASH_H diff --git a/phonelibs/android_system_core/include/utils/KeyedVector.h b/phonelibs/android_system_core/include/utils/KeyedVector.h new file mode 100644 index 0000000000..c4faae0b76 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/KeyedVector.h @@ -0,0 +1,224 @@ +/* + * 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_KEYED_VECTOR_H +#define ANDROID_KEYED_VECTOR_H + +#include +#include +#include + +#include + +#include +#include +#include + +// --------------------------------------------------------------------------- + +namespace android { + +template +class KeyedVector +{ +public: + typedef KEY key_type; + typedef VALUE value_type; + + inline KeyedVector(); + + /* + * empty the vector + */ + + inline void clear() { mVector.clear(); } + + /*! + * vector stats + */ + + //! returns number of items in the vector + inline size_t size() const { return mVector.size(); } + //! returns whether or not the vector is empty + inline bool isEmpty() const { return mVector.isEmpty(); } + //! returns how many items can be stored without reallocating the backing store + inline size_t capacity() const { return mVector.capacity(); } + //! sets the capacity. capacity can never be reduced less than size() + inline ssize_t setCapacity(size_t size) { return mVector.setCapacity(size); } + + // returns true if the arguments is known to be identical to this vector + inline bool isIdenticalTo(const KeyedVector& rhs) const; + + /*! + * accessors + */ + const VALUE& valueFor(const KEY& key) const; + const VALUE& valueAt(size_t index) const; + const KEY& keyAt(size_t index) const; + ssize_t indexOfKey(const KEY& key) const; + const VALUE& operator[] (size_t index) const; + + /*! + * modifying the array + */ + + VALUE& editValueFor(const KEY& key); + VALUE& editValueAt(size_t index); + + /*! + * add/insert/replace items + */ + + ssize_t add(const KEY& key, const VALUE& item); + ssize_t replaceValueFor(const KEY& key, const VALUE& item); + ssize_t replaceValueAt(size_t index, const VALUE& item); + + /*! + * remove items + */ + + ssize_t removeItem(const KEY& key); + ssize_t removeItemsAt(size_t index, size_t count = 1); + +private: + SortedVector< key_value_pair_t > mVector; +}; + +// KeyedVector can be trivially moved using memcpy() because its +// underlying SortedVector can be trivially moved. +template struct trait_trivial_move > { + enum { value = trait_trivial_move > >::value }; +}; + + +// --------------------------------------------------------------------------- + +/** + * Variation of KeyedVector that holds a default value to return when + * valueFor() is called with a key that doesn't exist. + */ +template +class DefaultKeyedVector : public KeyedVector +{ +public: + inline DefaultKeyedVector(const VALUE& defValue = VALUE()); + const VALUE& valueFor(const KEY& key) const; + +private: + VALUE mDefault; +}; + +// --------------------------------------------------------------------------- + +template inline +KeyedVector::KeyedVector() +{ +} + +template inline +bool KeyedVector::isIdenticalTo(const KeyedVector& rhs) const { + return mVector.array() == rhs.mVector.array(); +} + +template inline +ssize_t KeyedVector::indexOfKey(const KEY& key) const { + return mVector.indexOf( key_value_pair_t(key) ); +} + +template inline +const VALUE& KeyedVector::valueFor(const KEY& key) const { + ssize_t i = this->indexOfKey(key); + LOG_ALWAYS_FATAL_IF(i<0, "%s: key not found", __PRETTY_FUNCTION__); + return mVector.itemAt(i).value; +} + +template inline +const VALUE& KeyedVector::valueAt(size_t index) const { + return mVector.itemAt(index).value; +} + +template inline +const VALUE& KeyedVector::operator[] (size_t index) const { + return valueAt(index); +} + +template inline +const KEY& KeyedVector::keyAt(size_t index) const { + return mVector.itemAt(index).key; +} + +template inline +VALUE& KeyedVector::editValueFor(const KEY& key) { + ssize_t i = this->indexOfKey(key); + LOG_ALWAYS_FATAL_IF(i<0, "%s: key not found", __PRETTY_FUNCTION__); + return mVector.editItemAt(i).value; +} + +template inline +VALUE& KeyedVector::editValueAt(size_t index) { + return mVector.editItemAt(index).value; +} + +template inline +ssize_t KeyedVector::add(const KEY& key, const VALUE& value) { + return mVector.add( key_value_pair_t(key, value) ); +} + +template inline +ssize_t KeyedVector::replaceValueFor(const KEY& key, const VALUE& value) { + key_value_pair_t pair(key, value); + mVector.remove(pair); + return mVector.add(pair); +} + +template inline +ssize_t KeyedVector::replaceValueAt(size_t index, const VALUE& item) { + if (index inline +ssize_t KeyedVector::removeItem(const KEY& key) { + return mVector.remove(key_value_pair_t(key)); +} + +template inline +ssize_t KeyedVector::removeItemsAt(size_t index, size_t count) { + return mVector.removeItemsAt(index, count); +} + +// --------------------------------------------------------------------------- + +template inline +DefaultKeyedVector::DefaultKeyedVector(const VALUE& defValue) + : mDefault(defValue) +{ +} + +template inline +const VALUE& DefaultKeyedVector::valueFor(const KEY& key) const { + ssize_t i = this->indexOfKey(key); + return i >= 0 ? KeyedVector::valueAt(i) : mDefault; +} + +}; // namespace android + +// --------------------------------------------------------------------------- + +#endif // ANDROID_KEYED_VECTOR_H diff --git a/phonelibs/android_system_core/include/utils/LinearTransform.h b/phonelibs/android_system_core/include/utils/LinearTransform.h new file mode 100644 index 0000000000..04cb355c7f --- /dev/null +++ b/phonelibs/android_system_core/include/utils/LinearTransform.h @@ -0,0 +1,64 @@ +/* + * 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 _LIBS_UTILS_LINEAR_TRANSFORM_H +#define _LIBS_UTILS_LINEAR_TRANSFORM_H + +#include + +namespace android { + +// LinearTransform defines a structure which hold the definition of a +// transformation from single dimensional coordinate system A into coordinate +// system B (and back again). Values in A and in B are 64 bit, the linear +// scale factor is expressed as a rational number using two 32 bit values. +// +// Specifically, let +// f(a) = b +// F(b) = f^-1(b) = a +// then +// +// f(a) = (((a - a_zero) * a_to_b_numer) / a_to_b_denom) + b_zero; +// +// and +// +// F(b) = (((b - b_zero) * a_to_b_denom) / a_to_b_numer) + a_zero; +// +struct LinearTransform { + int64_t a_zero; + int64_t b_zero; + int32_t a_to_b_numer; + uint32_t a_to_b_denom; + + // Transform from A->B + // Returns true on success, or false in the case of a singularity or an + // overflow. + bool doForwardTransform(int64_t a_in, int64_t* b_out) const; + + // Transform from B->A + // Returns true on success, or false in the case of a singularity or an + // overflow. + bool doReverseTransform(int64_t b_in, int64_t* a_out) const; + + // Helpers which will reduce the fraction N/D using Euclid's method. + template static void reduce(T* N, T* D); + static void reduce(int32_t* N, uint32_t* D); +}; + + +} + +#endif // _LIBS_UTILS_LINEAR_TRANSFORM_H diff --git a/phonelibs/android_system_core/include/utils/List.h b/phonelibs/android_system_core/include/utils/List.h new file mode 100644 index 0000000000..403cd7f1e5 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/List.h @@ -0,0 +1,332 @@ +/* + * 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. + */ + +// +// Templated list class. Normally we'd use STL, but we don't have that. +// This class mimics STL's interfaces. +// +// Objects are copied into the list with the '=' operator or with copy- +// construction, so if the compiler's auto-generated versions won't work for +// you, define your own. +// +// The only class you want to use from here is "List". +// +#ifndef _LIBS_UTILS_LIST_H +#define _LIBS_UTILS_LIST_H + +#include +#include + +namespace android { + +/* + * Doubly-linked list. Instantiate with "List myList". + * + * Objects added to the list are copied using the assignment operator, + * so this must be defined. + */ +template +class List +{ +protected: + /* + * One element in the list. + */ + class _Node { + public: + explicit _Node(const T& val) : mVal(val) {} + ~_Node() {} + inline T& getRef() { return mVal; } + inline const T& getRef() const { return mVal; } + inline _Node* getPrev() const { return mpPrev; } + inline _Node* getNext() const { return mpNext; } + inline void setVal(const T& val) { mVal = val; } + inline void setPrev(_Node* ptr) { mpPrev = ptr; } + inline void setNext(_Node* ptr) { mpNext = ptr; } + private: + friend class List; + friend class _ListIterator; + T mVal; + _Node* mpPrev; + _Node* mpNext; + }; + + /* + * Iterator for walking through the list. + */ + + template + struct CONST_ITERATOR { + typedef _Node const * NodePtr; + typedef const TYPE Type; + }; + + template + struct NON_CONST_ITERATOR { + typedef _Node* NodePtr; + typedef TYPE Type; + }; + + template< + typename U, + template class Constness + > + class _ListIterator { + typedef _ListIterator _Iter; + typedef typename Constness::NodePtr _NodePtr; + typedef typename Constness::Type _Type; + + explicit _ListIterator(_NodePtr ptr) : mpNode(ptr) {} + + public: + _ListIterator() {} + _ListIterator(const _Iter& rhs) : mpNode(rhs.mpNode) {} + ~_ListIterator() {} + + // this will handle conversions from iterator to const_iterator + // (and also all convertible iterators) + // Here, in this implementation, the iterators can be converted + // if the nodes can be converted + template explicit + _ListIterator(const V& rhs) : mpNode(rhs.mpNode) {} + + + /* + * Dereference operator. Used to get at the juicy insides. + */ + _Type& operator*() const { return mpNode->getRef(); } + _Type* operator->() const { return &(mpNode->getRef()); } + + /* + * Iterator comparison. + */ + inline bool operator==(const _Iter& right) const { + return mpNode == right.mpNode; } + + inline bool operator!=(const _Iter& right) const { + return mpNode != right.mpNode; } + + /* + * handle comparisons between iterator and const_iterator + */ + template + inline bool operator==(const OTHER& right) const { + return mpNode == right.mpNode; } + + template + inline bool operator!=(const OTHER& right) const { + return mpNode != right.mpNode; } + + /* + * Incr/decr, used to move through the list. + */ + inline _Iter& operator++() { // pre-increment + mpNode = mpNode->getNext(); + return *this; + } + const _Iter operator++(int) { // post-increment + _Iter tmp(*this); + mpNode = mpNode->getNext(); + return tmp; + } + inline _Iter& operator--() { // pre-increment + mpNode = mpNode->getPrev(); + return *this; + } + const _Iter operator--(int) { // post-increment + _Iter tmp(*this); + mpNode = mpNode->getPrev(); + return tmp; + } + + inline _NodePtr getNode() const { return mpNode; } + + _NodePtr mpNode; /* should be private, but older gcc fails */ + private: + friend class List; + }; + +public: + List() { + prep(); + } + List(const List& src) { // copy-constructor + prep(); + insert(begin(), src.begin(), src.end()); + } + virtual ~List() { + clear(); + delete[] (unsigned char*) mpMiddle; + } + + typedef _ListIterator iterator; + typedef _ListIterator const_iterator; + + List& operator=(const List& right); + + /* returns true if the list is empty */ + inline bool empty() const { return mpMiddle->getNext() == mpMiddle; } + + /* return #of elements in list */ + size_t size() const { + return size_t(distance(begin(), end())); + } + + /* + * Return the first element or one past the last element. The + * _Node* we're returning is converted to an "iterator" by a + * constructor in _ListIterator. + */ + inline iterator begin() { + return iterator(mpMiddle->getNext()); + } + inline const_iterator begin() const { + return const_iterator(const_cast<_Node const*>(mpMiddle->getNext())); + } + inline iterator end() { + return iterator(mpMiddle); + } + inline const_iterator end() const { + return const_iterator(const_cast<_Node const*>(mpMiddle)); + } + + /* add the object to the head or tail of the list */ + void push_front(const T& val) { insert(begin(), val); } + void push_back(const T& val) { insert(end(), val); } + + /* insert before the current node; returns iterator at new node */ + iterator insert(iterator posn, const T& val) + { + _Node* newNode = new _Node(val); // alloc & copy-construct + newNode->setNext(posn.getNode()); + newNode->setPrev(posn.getNode()->getPrev()); + posn.getNode()->getPrev()->setNext(newNode); + posn.getNode()->setPrev(newNode); + return iterator(newNode); + } + + /* insert a range of elements before the current node */ + void insert(iterator posn, const_iterator first, const_iterator last) { + for ( ; first != last; ++first) + insert(posn, *first); + } + + /* remove one entry; returns iterator at next node */ + iterator erase(iterator posn) { + _Node* pNext = posn.getNode()->getNext(); + _Node* pPrev = posn.getNode()->getPrev(); + pPrev->setNext(pNext); + pNext->setPrev(pPrev); + delete posn.getNode(); + return iterator(pNext); + } + + /* remove a range of elements */ + iterator erase(iterator first, iterator last) { + while (first != last) + erase(first++); // don't erase than incr later! + return iterator(last); + } + + /* remove all contents of the list */ + void clear() { + _Node* pCurrent = mpMiddle->getNext(); + _Node* pNext; + + while (pCurrent != mpMiddle) { + pNext = pCurrent->getNext(); + delete pCurrent; + pCurrent = pNext; + } + mpMiddle->setPrev(mpMiddle); + mpMiddle->setNext(mpMiddle); + } + + /* + * Measure the distance between two iterators. On exist, "first" + * will be equal to "last". The iterators must refer to the same + * list. + * + * FIXME: This is actually a generic iterator function. It should be a + * template function at the top-level with specializations for things like + * vector<>, which can just do pointer math). Here we limit it to + * _ListIterator of the same type but different constness. + */ + template< + typename U, + template class CL, + template class CR + > + ptrdiff_t distance( + _ListIterator first, _ListIterator last) const + { + ptrdiff_t count = 0; + while (first != last) { + ++first; + ++count; + } + return count; + } + +private: + /* + * I want a _Node but don't need it to hold valid data. More + * to the point, I don't want T's constructor to fire, since it + * might have side-effects or require arguments. So, we do this + * slightly uncouth storage alloc. + */ + void prep() { + mpMiddle = (_Node*) new unsigned char[sizeof(_Node)]; + mpMiddle->setPrev(mpMiddle); + mpMiddle->setNext(mpMiddle); + } + + /* + * This node plays the role of "pointer to head" and "pointer to tail". + * It sits in the middle of a circular list of nodes. The iterator + * runs around the circle until it encounters this one. + */ + _Node* mpMiddle; +}; + +/* + * Assignment operator. + * + * The simplest way to do this would be to clear out the target list and + * fill it with the source. However, we can speed things along by + * re-using existing elements. + */ +template +List& List::operator=(const List& right) +{ + if (this == &right) + return *this; // self-assignment + iterator firstDst = begin(); + iterator lastDst = end(); + const_iterator firstSrc = right.begin(); + const_iterator lastSrc = right.end(); + while (firstSrc != lastSrc && firstDst != lastDst) + *firstDst++ = *firstSrc++; + if (firstSrc == lastSrc) // ran out of elements in source? + erase(firstDst, lastDst); // yes, erase any extras + else + insert(lastDst, firstSrc, lastSrc); // copy remaining over + return *this; +} + +}; // namespace android + +#endif // _LIBS_UTILS_LIST_H diff --git a/phonelibs/android_system_core/include/utils/Log.h b/phonelibs/android_system_core/include/utils/Log.h new file mode 100644 index 0000000000..4259c86d1a --- /dev/null +++ b/phonelibs/android_system_core/include/utils/Log.h @@ -0,0 +1,71 @@ +/* + * 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. + */ + +// +// C/C++ logging functions. See the logging documentation for API details. +// +// We'd like these to be available from C code (in case we import some from +// somewhere), so this has a C interface. +// +// The output will be correct when the log file is shared between multiple +// threads and/or multiple processes so long as the operating system +// supports O_APPEND. These calls have mutex-protected data structures +// and so are NOT reentrant. Do not use LOG in a signal handler. +// +#ifndef _LIBS_UTILS_LOG_H +#define _LIBS_UTILS_LOG_H + +#include +#include + +#ifdef __cplusplus + +namespace android { + +/* + * A very simple utility that yells in the log when an operation takes too long. + */ +class LogIfSlow { +public: + LogIfSlow(const char* tag, android_LogPriority priority, + int timeoutMillis, const char* message); + ~LogIfSlow(); + +private: + const char* const mTag; + const android_LogPriority mPriority; + const int mTimeoutMillis; + const char* const mMessage; + const int64_t mStart; +}; + +/* + * Writes the specified debug log message if this block takes longer than the + * specified number of milliseconds to run. Includes the time actually taken. + * + * { + * ALOGD_IF_SLOW(50, "Excessive delay doing something."); + * doSomething(); + * } + */ +#define ALOGD_IF_SLOW(timeoutMillis, message) \ + android::LogIfSlow _logIfSlow(LOG_TAG, ANDROID_LOG_DEBUG, timeoutMillis, message); + +} // namespace android + +#endif // __cplusplus + +#endif // _LIBS_UTILS_LOG_H diff --git a/phonelibs/android_system_core/include/utils/Looper.h b/phonelibs/android_system_core/include/utils/Looper.h new file mode 100644 index 0000000000..da2d5f2b5b --- /dev/null +++ b/phonelibs/android_system_core/include/utils/Looper.h @@ -0,0 +1,487 @@ +/* + * 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 UTILS_LOOPER_H +#define UTILS_LOOPER_H + +#include +#include +#include +#include + +#include + +namespace android { + +/* + * NOTE: Since Looper is used to implement the NDK ALooper, the Looper + * enums and the signature of Looper_callbackFunc need to align with + * that implementation. + */ + +/** + * 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 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 (*Looper_callbackFunc)(int fd, int events, void* data); + +/** + * A message that can be posted to a Looper. + */ +struct Message { + Message() : what(0) { } + Message(int what) : what(what) { } + + /* The message type. (interpretation is left up to the handler) */ + int what; +}; + + +/** + * Interface for a Looper message handler. + * + * The Looper holds a strong reference to the message handler whenever it has + * a message to deliver to it. Make sure to call Looper::removeMessages + * to remove any pending messages destined for the handler so that the handler + * can be destroyed. + */ +class MessageHandler : public virtual RefBase { +protected: + virtual ~MessageHandler() { } + +public: + /** + * Handles a message. + */ + virtual void handleMessage(const Message& message) = 0; +}; + + +/** + * A simple proxy that holds a weak reference to a message handler. + */ +class WeakMessageHandler : public MessageHandler { +protected: + virtual ~WeakMessageHandler(); + +public: + WeakMessageHandler(const wp& handler); + virtual void handleMessage(const Message& message); + +private: + wp mHandler; +}; + + +/** + * A looper callback. + */ +class LooperCallback : public virtual RefBase { +protected: + virtual ~LooperCallback() { } + +public: + /** + * Handles a poll event for the given file descriptor. + * It is given the file descriptor it is associated with, + * a bitmask of the poll events that were triggered (typically 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. + */ + virtual int handleEvent(int fd, int events, void* data) = 0; +}; + +/** + * Wraps a Looper_callbackFunc function pointer. + */ +class SimpleLooperCallback : public LooperCallback { +protected: + virtual ~SimpleLooperCallback(); + +public: + SimpleLooperCallback(Looper_callbackFunc callback); + virtual int handleEvent(int fd, int events, void* data); + +private: + Looper_callbackFunc mCallback; +}; + +/** + * A polling loop that supports monitoring file descriptor events, optionally + * using callbacks. The implementation uses epoll() internally. + * + * A looper can be associated with a thread although there is no requirement that it must be. + */ +class Looper : public RefBase { +protected: + virtual ~Looper(); + +public: + enum { + /** + * Result from Looper_pollOnce() and Looper_pollAll(): + * The poll was awoken using wake() before the timeout expired + * and no callbacks were executed and no other file descriptors were ready. + */ + POLL_WAKE = -1, + + /** + * Result from Looper_pollOnce() and Looper_pollAll(): + * One or more callbacks were executed. + */ + POLL_CALLBACK = -2, + + /** + * Result from Looper_pollOnce() and Looper_pollAll(): + * The timeout expired. + */ + POLL_TIMEOUT = -3, + + /** + * Result from Looper_pollOnce() and Looper_pollAll(): + * An error occurred. + */ + POLL_ERROR = -4, + }; + + /** + * 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. + */ + EVENT_INPUT = 1 << 0, + + /** + * The file descriptor is available for write operations. + */ + 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. + */ + 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. + */ + 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. + */ + EVENT_INVALID = 1 << 4, + }; + + enum { + /** + * Option for Looper_prepare: this looper will accept calls to + * Looper_addFd() that do not have a callback (that is provide NULL + * for the callback). In this case the caller of Looper_pollOnce() + * or Looper_pollAll() MUST check the return from these functions to + * discover when data is available on such fds and process it. + */ + PREPARE_ALLOW_NON_CALLBACKS = 1<<0 + }; + + /** + * Creates a looper. + * + * If allowNonCallbaks is true, the looper will allow file descriptors to be + * registered without associated callbacks. This assumes that the caller of + * pollOnce() is prepared to handle callback-less events itself. + */ + Looper(bool allowNonCallbacks); + + /** + * Returns whether this looper instance allows the registration of file descriptors + * using identifiers instead of callbacks. + */ + bool getAllowNonCallbacks() const; + + /** + * 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 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 POLL_CALLBACK if one or more callbacks were invoked. + * + * Returns POLL_TIMEOUT if there was no data before the given + * timeout expired. + * + * Returns POLL_ERROR if an error occurred. + * + * Returns a value >= 0 containing an identifier 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 pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData); + inline int pollOnce(int timeoutMillis) { + return pollOnce(timeoutMillis, NULL, NULL, NULL); + } + + /** + * Like 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 POLL_CALLBACK. + */ + int pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData); + inline int pollAll(int timeoutMillis) { + return pollAll(timeoutMillis, NULL, NULL, NULL); + } + + /** + * Wakes the poll asynchronously. + * + * This method can be called on any thread. + * This method returns immediately. + */ + void wake(); + + /** + * 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 pollOnce(). + * The identifier must be >= 0, or POLL_CALLBACK if providing a non-NULL callback. + * "events" are the poll events to wake up on. Typically this is 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 Looper_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, 0 if the arguments were invalid. + * + * This method can be called on any thread. + * This method may block briefly if it needs to wake the poll. + * + * The callback may either be specified as a bare function pointer or as a smart + * pointer callback object. The smart pointer should be preferred because it is + * easier to avoid races when the callback is removed from a different thread. + * See removeFd() for details. + */ + int addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data); + int addFd(int fd, int ident, int events, const sp& 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. + * + * A simple way to avoid this problem is to use the version of addFd() that takes + * a sp instead of a bare function pointer. The LooperCallback will + * be released at the appropriate time by the Looper. + * + * Returns 1 if the file descriptor was removed, 0 if none was previously registered. + * + * This method can be called on any thread. + * This method may block briefly if it needs to wake the poll. + */ + int removeFd(int fd); + + /** + * Enqueues a message to be processed by the specified handler. + * + * The handler must not be null. + * This method can be called on any thread. + */ + void sendMessage(const sp& handler, const Message& message); + + /** + * Enqueues a message to be processed by the specified handler after all pending messages + * after the specified delay. + * + * The time delay is specified in uptime nanoseconds. + * The handler must not be null. + * This method can be called on any thread. + */ + void sendMessageDelayed(nsecs_t uptimeDelay, const sp& handler, + const Message& message); + + /** + * Enqueues a message to be processed by the specified handler after all pending messages + * at the specified time. + * + * The time is specified in uptime nanoseconds. + * The handler must not be null. + * This method can be called on any thread. + */ + void sendMessageAtTime(nsecs_t uptime, const sp& handler, + const Message& message); + + /** + * Removes all messages for the specified handler from the queue. + * + * The handler must not be null. + * This method can be called on any thread. + */ + void removeMessages(const sp& handler); + + /** + * Removes all messages of a particular type for the specified handler from the queue. + * + * The handler must not be null. + * This method can be called on any thread. + */ + void removeMessages(const sp& handler, int what); + + /** + * Returns whether this looper's thread is currently polling for more work to do. + * This is a good signal that the loop is still alive rather than being stuck + * handling a callback. Note that this method is intrinsically racy, since the + * state of the loop can change before you get the result back. + */ + bool isPolling() const; + + /** + * 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 PREPARE_ALLOW_NON_CALLBACKS or 0. + */ + static sp prepare(int opts); + + /** + * Sets the given looper to be associated with the calling thread. + * If another looper is already associated with the thread, it is replaced. + * + * If "looper" is NULL, removes the currently associated looper. + */ + static void setForThread(const sp& looper); + + /** + * Returns the looper associated with the calling thread, or NULL if + * there is not one. + */ + static sp getForThread(); + +private: + struct Request { + int fd; + int ident; + int events; + int seq; + sp callback; + void* data; + + void initEventItem(struct epoll_event* eventItem) const; + }; + + struct Response { + int events; + Request request; + }; + + struct MessageEnvelope { + MessageEnvelope() : uptime(0) { } + + MessageEnvelope(nsecs_t uptime, const sp handler, + const Message& message) : uptime(uptime), handler(handler), message(message) { + } + + nsecs_t uptime; + sp handler; + Message message; + }; + + const bool mAllowNonCallbacks; // immutable + + int mWakeEventFd; // immutable + Mutex mLock; + + Vector mMessageEnvelopes; // guarded by mLock + bool mSendingMessage; // guarded by mLock + + // Whether we are currently waiting for work. Not protected by a lock, + // any use of it is racy anyway. + volatile bool mPolling; + + int mEpollFd; // guarded by mLock but only modified on the looper thread + bool mEpollRebuildRequired; // guarded by mLock + + // Locked list of file descriptor monitoring requests. + KeyedVector mRequests; // guarded by mLock + int mNextRequestSeq; + + // This state is only used privately by pollOnce and does not require a lock since + // it runs on a single thread. + Vector mResponses; + size_t mResponseIndex; + nsecs_t mNextMessageUptime; // set to LLONG_MAX when none + + int pollInner(int timeoutMillis); + int removeFd(int fd, int seq); + void awoken(); + void pushResponse(int events, const Request& request); + void rebuildEpollLocked(); + void scheduleEpollRebuildLocked(); + + static void initTLSKey(); + static void threadDestructor(void *st); + static void initEpollEvent(struct epoll_event* eventItem); +}; + +} // namespace android + +#endif // UTILS_LOOPER_H diff --git a/phonelibs/android_system_core/include/utils/LruCache.h b/phonelibs/android_system_core/include/utils/LruCache.h new file mode 100644 index 0000000000..cd9d7f94a0 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/LruCache.h @@ -0,0 +1,250 @@ +/* + * 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_UTILS_LRU_CACHE_H +#define ANDROID_UTILS_LRU_CACHE_H + +#include +#include + +namespace android { + +/** + * GenerationCache callback used when an item is removed + */ +template +class OnEntryRemoved { +public: + virtual ~OnEntryRemoved() { }; + virtual void operator()(EntryKey& key, EntryValue& value) = 0; +}; // class OnEntryRemoved + +template +class LruCache { +public: + explicit LruCache(uint32_t maxCapacity); + + enum Capacity { + kUnlimitedCapacity, + }; + + void setOnEntryRemovedListener(OnEntryRemoved* listener); + size_t size() const; + const TValue& get(const TKey& key); + bool put(const TKey& key, const TValue& value); + bool remove(const TKey& key); + bool removeOldest(); + void clear(); + const TValue& peekOldestValue(); + + class Iterator { + public: + Iterator(const LruCache& cache): mCache(cache), mIndex(-1) { + } + + bool next() { + mIndex = mCache.mTable->next(mIndex); + return (ssize_t)mIndex != -1; + } + + size_t index() const { + return mIndex; + } + + const TValue& value() const { + return mCache.mTable->entryAt(mIndex).value; + } + + const TKey& key() const { + return mCache.mTable->entryAt(mIndex).key; + } + private: + const LruCache& mCache; + size_t mIndex; + }; + +private: + LruCache(const LruCache& that); // disallow copy constructor + + struct Entry { + TKey key; + TValue value; + Entry* parent; + Entry* child; + + Entry(TKey key_, TValue value_) : key(key_), value(value_), parent(NULL), child(NULL) { + } + const TKey& getKey() const { return key; } + }; + + void attachToCache(Entry& entry); + void detachFromCache(Entry& entry); + void rehash(size_t newCapacity); + + UniquePtr > mTable; + OnEntryRemoved* mListener; + Entry* mOldest; + Entry* mYoungest; + uint32_t mMaxCapacity; + TValue mNullValue; +}; + +// Implementation is here, because it's fully templated +template +LruCache::LruCache(uint32_t maxCapacity) + : mTable(new BasicHashtable) + , mListener(NULL) + , mOldest(NULL) + , mYoungest(NULL) + , mMaxCapacity(maxCapacity) + , mNullValue(NULL) { +}; + +template +void LruCache::setOnEntryRemovedListener(OnEntryRemoved* listener) { + mListener = listener; +} + +template +size_t LruCache::size() const { + return mTable->size(); +} + +template +const TValue& LruCache::get(const TKey& key) { + hash_t hash = hash_type(key); + ssize_t index = mTable->find(-1, hash, key); + if (index == -1) { + return mNullValue; + } + Entry& entry = mTable->editEntryAt(index); + detachFromCache(entry); + attachToCache(entry); + return entry.value; +} + +template +bool LruCache::put(const TKey& key, const TValue& value) { + if (mMaxCapacity != kUnlimitedCapacity && size() >= mMaxCapacity) { + removeOldest(); + } + + hash_t hash = hash_type(key); + ssize_t index = mTable->find(-1, hash, key); + if (index >= 0) { + return false; + } + if (!mTable->hasMoreRoom()) { + rehash(mTable->capacity() * 2); + } + + // Would it be better to initialize a blank entry and assign key, value? + Entry initEntry(key, value); + index = mTable->add(hash, initEntry); + Entry& entry = mTable->editEntryAt(index); + attachToCache(entry); + return true; +} + +template +bool LruCache::remove(const TKey& key) { + hash_t hash = hash_type(key); + ssize_t index = mTable->find(-1, hash, key); + if (index < 0) { + return false; + } + Entry& entry = mTable->editEntryAt(index); + if (mListener) { + (*mListener)(entry.key, entry.value); + } + detachFromCache(entry); + mTable->removeAt(index); + return true; +} + +template +bool LruCache::removeOldest() { + if (mOldest != NULL) { + return remove(mOldest->key); + // TODO: should probably abort if false + } + return false; +} + +template +const TValue& LruCache::peekOldestValue() { + if (mOldest) { + return mOldest->value; + } + return mNullValue; +} + +template +void LruCache::clear() { + if (mListener) { + for (Entry* p = mOldest; p != NULL; p = p->child) { + (*mListener)(p->key, p->value); + } + } + mYoungest = NULL; + mOldest = NULL; + mTable->clear(); +} + +template +void LruCache::attachToCache(Entry& entry) { + if (mYoungest == NULL) { + mYoungest = mOldest = &entry; + } else { + entry.parent = mYoungest; + mYoungest->child = &entry; + mYoungest = &entry; + } +} + +template +void LruCache::detachFromCache(Entry& entry) { + if (entry.parent != NULL) { + entry.parent->child = entry.child; + } else { + mOldest = entry.child; + } + if (entry.child != NULL) { + entry.child->parent = entry.parent; + } else { + mYoungest = entry.parent; + } + + entry.parent = NULL; + entry.child = NULL; +} + +template +void LruCache::rehash(size_t newCapacity) { + UniquePtr > oldTable(mTable.release()); + Entry* oldest = mOldest; + + mOldest = NULL; + mYoungest = NULL; + mTable.reset(new BasicHashtable(newCapacity)); + for (Entry* p = oldest; p != NULL; p = p->child) { + put(p->key, p->value); + } +} + +} + +#endif // ANDROID_UTILS_LRU_CACHE_H diff --git a/phonelibs/android_system_core/include/utils/Mutex.h b/phonelibs/android_system_core/include/utils/Mutex.h new file mode 100644 index 0000000000..757519b086 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/Mutex.h @@ -0,0 +1,157 @@ +/* + * 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 _LIBS_UTILS_MUTEX_H +#define _LIBS_UTILS_MUTEX_H + +#include +#include +#include + +#if !defined(_WIN32) +# include +#endif + +#include +#include + +// --------------------------------------------------------------------------- +namespace android { +// --------------------------------------------------------------------------- + +class Condition; + +/* + * Simple mutex class. The implementation is system-dependent. + * + * The mutex must be unlocked by the thread that locked it. They are not + * recursive, i.e. the same thread can't lock it multiple times. + */ +class Mutex { +public: + enum { + PRIVATE = 0, + SHARED = 1 + }; + + Mutex(); + Mutex(const char* name); + Mutex(int type, const char* name = NULL); + ~Mutex(); + + // lock or unlock the mutex + status_t lock(); + void unlock(); + + // lock if possible; returns 0 on success, error otherwise + status_t tryLock(); + +#if HAVE_ANDROID_OS + // lock the mutex, but don't wait longer than timeoutMilliseconds. + // Returns 0 on success, TIMED_OUT for failure due to timeout expiration. + // + // OSX doesn't have pthread_mutex_timedlock() or equivalent. To keep + // capabilities consistent across host OSes, this method is only available + // when building Android binaries. + status_t timedLock(nsecs_t timeoutMilliseconds); +#endif + + // Manages the mutex automatically. It'll be locked when Autolock is + // constructed and released when Autolock goes out of scope. + class Autolock { + public: + inline Autolock(Mutex& mutex) : mLock(mutex) { mLock.lock(); } + inline Autolock(Mutex* mutex) : mLock(*mutex) { mLock.lock(); } + inline ~Autolock() { mLock.unlock(); } + private: + Mutex& mLock; + }; + +private: + friend class Condition; + + // A mutex cannot be copied + Mutex(const Mutex&); + Mutex& operator = (const Mutex&); + +#if !defined(_WIN32) + pthread_mutex_t mMutex; +#else + void _init(); + void* mState; +#endif +}; + +// --------------------------------------------------------------------------- + +#if !defined(_WIN32) + +inline Mutex::Mutex() { + pthread_mutex_init(&mMutex, NULL); +} +inline Mutex::Mutex(__attribute__((unused)) const char* name) { + pthread_mutex_init(&mMutex, NULL); +} +inline Mutex::Mutex(int type, __attribute__((unused)) const char* name) { + if (type == SHARED) { + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); + pthread_mutex_init(&mMutex, &attr); + pthread_mutexattr_destroy(&attr); + } else { + pthread_mutex_init(&mMutex, NULL); + } +} +inline Mutex::~Mutex() { + pthread_mutex_destroy(&mMutex); +} +inline status_t Mutex::lock() { + return -pthread_mutex_lock(&mMutex); +} +inline void Mutex::unlock() { + pthread_mutex_unlock(&mMutex); +} +inline status_t Mutex::tryLock() { + return -pthread_mutex_trylock(&mMutex); +} +#if HAVE_ANDROID_OS +inline status_t Mutex::timedLock(nsecs_t timeoutNs) { + const struct timespec ts = { + /* .tv_sec = */ static_cast(timeoutNs / 1000000000), + /* .tv_nsec = */ static_cast(timeoutNs % 1000000000), + }; + return -pthread_mutex_timedlock(&mMutex, &ts); +} +#endif + +#endif // !defined(_WIN32) + +// --------------------------------------------------------------------------- + +/* + * Automatic mutex. Declare one of these at the top of a function. + * When the function returns, it will go out of scope, and release the + * mutex. + */ + +typedef Mutex::Autolock AutoMutex; + +// --------------------------------------------------------------------------- +}; // namespace android +// --------------------------------------------------------------------------- + +#endif // _LIBS_UTILS_MUTEX_H diff --git a/phonelibs/android_system_core/include/utils/NativeHandle.h b/phonelibs/android_system_core/include/utils/NativeHandle.h new file mode 100644 index 0000000000..b82516879a --- /dev/null +++ b/phonelibs/android_system_core/include/utils/NativeHandle.h @@ -0,0 +1,56 @@ +/* + * 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_NATIVE_HANDLE_H +#define ANDROID_NATIVE_HANDLE_H + +#include +#include + +typedef struct native_handle native_handle_t; + +namespace android { + +class NativeHandle: public LightRefBase { +public: + // Create a refcounted wrapper around a native_handle_t, and declare + // whether the wrapper owns the handle (so that it should clean up the + // handle upon destruction) or not. + // If handle is NULL, no NativeHandle will be created. + static sp create(native_handle_t* handle, bool ownsHandle); + + const native_handle_t* handle() const { + return mHandle; + } + +private: + // for access to the destructor + friend class LightRefBase; + + NativeHandle(native_handle_t* handle, bool ownsHandle); + virtual ~NativeHandle(); + + native_handle_t* mHandle; + bool mOwnsHandle; + + // non-copyable + NativeHandle(const NativeHandle&); + NativeHandle& operator=(const NativeHandle&); +}; + +} // namespace android + +#endif // ANDROID_NATIVE_HANDLE_H diff --git a/phonelibs/android_system_core/include/utils/Printer.h b/phonelibs/android_system_core/include/utils/Printer.h new file mode 100644 index 0000000000..bb6628767c --- /dev/null +++ b/phonelibs/android_system_core/include/utils/Printer.h @@ -0,0 +1,119 @@ +/* + * 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_PRINTER_H +#define ANDROID_PRINTER_H + +#include + +namespace android { + +// Interface for printing to an arbitrary data stream +class Printer { +public: + // Print a new line specified by 'string'. \n is appended automatically. + // -- Assumes that the string has no new line in it. + virtual void printLine(const char* string = "") = 0; + + // Print a new line specified by the format string. \n is appended automatically. + // -- Assumes that the resulting string has no new line in it. + virtual void printFormatLine(const char* format, ...) __attribute__((format (printf, 2, 3))); + +protected: + Printer(); + virtual ~Printer(); +}; // class Printer + +// Print to logcat +class LogPrinter : public Printer { +public: + // Create a printer using the specified logcat and log priority + // - Unless ignoreBlankLines is false, print blank lines to logcat + // (Note that the default ALOG behavior is to ignore blank lines) + LogPrinter(const char* logtag, + android_LogPriority priority = ANDROID_LOG_DEBUG, + const char* prefix = 0, + bool ignoreBlankLines = false); + + // Print the specified line to logcat. No \n at the end is necessary. + virtual void printLine(const char* string); + +private: + void printRaw(const char* string); + + const char* mLogTag; + android_LogPriority mPriority; + const char* mPrefix; + bool mIgnoreBlankLines; +}; // class LogPrinter + +// Print to a file descriptor +class FdPrinter : public Printer { +public: + // Create a printer using the specified file descriptor. + // - Each line will be prefixed with 'indent' number of blank spaces. + // - In addition, each line will be prefixed with the 'prefix' string. + FdPrinter(int fd, unsigned int indent = 0, const char* prefix = 0); + + // Print the specified line to the file descriptor. \n is appended automatically. + virtual void printLine(const char* string); + +private: + enum { + MAX_FORMAT_STRING = 20, + }; + + int mFd; + unsigned int mIndent; + const char* mPrefix; + char mFormatString[MAX_FORMAT_STRING]; +}; // class FdPrinter + +class String8; + +// Print to a String8 +class String8Printer : public Printer { +public: + // Create a printer using the specified String8 as the target. + // - In addition, each line will be prefixed with the 'prefix' string. + // - target's memory lifetime must be a superset of this String8Printer. + String8Printer(String8* target, const char* prefix = 0); + + // Append the specified line to the String8. \n is appended automatically. + virtual void printLine(const char* string); + +private: + String8* mTarget; + const char* mPrefix; +}; // class String8Printer + +// Print to an existing Printer by adding a prefix to each line +class PrefixPrinter : public Printer { +public: + // Create a printer using the specified printer as the target. + PrefixPrinter(Printer& printer, const char* prefix); + + // Print the line (prefixed with prefix) using the printer. + virtual void printLine(const char* string); + +private: + Printer& mPrinter; + const char* mPrefix; +}; + +}; // namespace android + +#endif // ANDROID_PRINTER_H diff --git a/phonelibs/android_system_core/include/utils/ProcessCallStack.h b/phonelibs/android_system_core/include/utils/ProcessCallStack.h new file mode 100644 index 0000000000..32458b8b14 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/ProcessCallStack.h @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_PROCESS_CALLSTACK_H +#define ANDROID_PROCESS_CALLSTACK_H + +#include +#include +#include +#include + +#include +#include + +namespace android { + +class Printer; + +// Collect/print the call stack (function, file, line) traces for all threads in a process. +class ProcessCallStack { +public: + // Create an empty call stack. No-op. + ProcessCallStack(); + // Copy the existing process callstack (no other side effects). + ProcessCallStack(const ProcessCallStack& rhs); + ~ProcessCallStack(); + + // Immediately collect the stack traces for all threads. + void update(); + + // Print all stack traces to the log using the supplied logtag. + void log(const char* logtag, android_LogPriority priority = ANDROID_LOG_DEBUG, + const char* prefix = 0) const; + + // Dump all stack traces to the specified file descriptor. + void dump(int fd, int indent = 0, const char* prefix = 0) const; + + // Return a string (possibly very long) containing all the stack traces. + String8 toString(const char* prefix = 0) const; + + // Dump a serialized representation of all the stack traces to the specified printer. + void print(Printer& printer) const; + + // Get the number of threads whose stack traces were collected. + size_t size() const; + +private: + void printInternal(Printer& printer, Printer& csPrinter) const; + + // Reset the process's stack frames and metadata. + void clear(); + + struct ThreadInfo { + CallStack callStack; + String8 threadName; + }; + + // tid -> ThreadInfo + KeyedVector mThreadMap; + // Time that update() was last called + struct tm mTimeUpdated; +}; + +}; // namespace android + +#endif // ANDROID_PROCESS_CALLSTACK_H diff --git a/phonelibs/android_system_core/include/utils/PropertyMap.h b/phonelibs/android_system_core/include/utils/PropertyMap.h new file mode 100644 index 0000000000..a9e674f9af --- /dev/null +++ b/phonelibs/android_system_core/include/utils/PropertyMap.h @@ -0,0 +1,106 @@ +/* + * 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 _UTILS_PROPERTY_MAP_H +#define _UTILS_PROPERTY_MAP_H + +#include +#include +#include +#include + +namespace android { + +/* + * Provides a mechanism for passing around string-based property key / value pairs + * and loading them from property files. + * + * The property files have the following simple structure: + * + * # Comment + * key = value + * + * Keys and values are any sequence of printable ASCII characters. + * The '=' separates the key from the value. + * The key and value may not contain whitespace. + * + * The '\' character is reserved for escape sequences and is not currently supported. + * The '"" character is reserved for quoting and is not currently supported. + * Files that contain the '\' or '"' character will fail to parse. + * + * The file must not contain duplicate keys. + * + * TODO Support escape sequences and quoted values when needed. + */ +class PropertyMap { +public: + /* Creates an empty property map. */ + PropertyMap(); + ~PropertyMap(); + + /* Clears the property map. */ + void clear(); + + /* Adds a property. + * Replaces the property with the same key if it is already present. + */ + void addProperty(const String8& key, const String8& value); + + /* Returns true if the property map contains the specified key. */ + bool hasProperty(const String8& key) const; + + /* Gets the value of a property and parses it. + * Returns true and sets outValue if the key was found and its value was parsed successfully. + * Otherwise returns false and does not modify outValue. (Also logs a warning.) + */ + bool tryGetProperty(const String8& key, String8& outValue) const; + bool tryGetProperty(const String8& key, bool& outValue) const; + bool tryGetProperty(const String8& key, int32_t& outValue) const; + bool tryGetProperty(const String8& key, float& outValue) const; + + /* Adds all values from the specified property map. */ + void addAll(const PropertyMap* map); + + /* Gets the underlying property map. */ + inline const KeyedVector& getProperties() const { return mProperties; } + + /* Loads a property map from a file. */ + static status_t load(const String8& filename, PropertyMap** outMap); + +private: + class Parser { + PropertyMap* mMap; + Tokenizer* mTokenizer; + + public: + Parser(PropertyMap* map, Tokenizer* tokenizer); + ~Parser(); + status_t parse(); + + private: + status_t parseType(); + status_t parseKey(); + status_t parseKeyProperty(); + status_t parseModifier(const String8& token, int32_t* outMetaState); + status_t parseCharacterLiteral(char16_t* outCharacter); + }; + + KeyedVector mProperties; +}; + +} // namespace android + +#endif // _UTILS_PROPERTY_MAP_H diff --git a/phonelibs/android_system_core/include/utils/RWLock.h b/phonelibs/android_system_core/include/utils/RWLock.h new file mode 100644 index 0000000000..e743b1c8ce --- /dev/null +++ b/phonelibs/android_system_core/include/utils/RWLock.h @@ -0,0 +1,126 @@ +/* + * 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 _LIBS_UTILS_RWLOCK_H +#define _LIBS_UTILS_RWLOCK_H + +#include +#include + +#if !defined(_WIN32) +# include +#endif + +#include +#include + +// --------------------------------------------------------------------------- +namespace android { +// --------------------------------------------------------------------------- + +#if !defined(_WIN32) + +/* + * Simple mutex class. The implementation is system-dependent. + * + * The mutex must be unlocked by the thread that locked it. They are not + * recursive, i.e. the same thread can't lock it multiple times. + */ +class RWLock { +public: + enum { + PRIVATE = 0, + SHARED = 1 + }; + + RWLock(); + RWLock(const char* name); + RWLock(int type, const char* name = NULL); + ~RWLock(); + + status_t readLock(); + status_t tryReadLock(); + status_t writeLock(); + status_t tryWriteLock(); + void unlock(); + + class AutoRLock { + public: + inline AutoRLock(RWLock& rwlock) : mLock(rwlock) { mLock.readLock(); } + inline ~AutoRLock() { mLock.unlock(); } + private: + RWLock& mLock; + }; + + class AutoWLock { + public: + inline AutoWLock(RWLock& rwlock) : mLock(rwlock) { mLock.writeLock(); } + inline ~AutoWLock() { mLock.unlock(); } + private: + RWLock& mLock; + }; + +private: + // A RWLock cannot be copied + RWLock(const RWLock&); + RWLock& operator = (const RWLock&); + + pthread_rwlock_t mRWLock; +}; + +inline RWLock::RWLock() { + pthread_rwlock_init(&mRWLock, NULL); +} +inline RWLock::RWLock(__attribute__((unused)) const char* name) { + pthread_rwlock_init(&mRWLock, NULL); +} +inline RWLock::RWLock(int type, __attribute__((unused)) const char* name) { + if (type == SHARED) { + pthread_rwlockattr_t attr; + pthread_rwlockattr_init(&attr); + pthread_rwlockattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); + pthread_rwlock_init(&mRWLock, &attr); + pthread_rwlockattr_destroy(&attr); + } else { + pthread_rwlock_init(&mRWLock, NULL); + } +} +inline RWLock::~RWLock() { + pthread_rwlock_destroy(&mRWLock); +} +inline status_t RWLock::readLock() { + return -pthread_rwlock_rdlock(&mRWLock); +} +inline status_t RWLock::tryReadLock() { + return -pthread_rwlock_tryrdlock(&mRWLock); +} +inline status_t RWLock::writeLock() { + return -pthread_rwlock_wrlock(&mRWLock); +} +inline status_t RWLock::tryWriteLock() { + return -pthread_rwlock_trywrlock(&mRWLock); +} +inline void RWLock::unlock() { + pthread_rwlock_unlock(&mRWLock); +} + +#endif // !defined(_WIN32) + +// --------------------------------------------------------------------------- +}; // namespace android +// --------------------------------------------------------------------------- + +#endif // _LIBS_UTILS_RWLOCK_H diff --git a/phonelibs/android_system_core/include/utils/RefBase.h b/phonelibs/android_system_core/include/utils/RefBase.h new file mode 100644 index 0000000000..eac6a78402 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/RefBase.h @@ -0,0 +1,555 @@ +/* + * 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_REF_BASE_H +#define ANDROID_REF_BASE_H + +#include + +#include +#include +#include +#include + +#include +#include + +// --------------------------------------------------------------------------- +namespace android { + +class TextOutput; +TextOutput& printWeakPointer(TextOutput& to, const void* val); + +// --------------------------------------------------------------------------- + +#define COMPARE_WEAK(_op_) \ +inline bool operator _op_ (const sp& o) const { \ + return m_ptr _op_ o.m_ptr; \ +} \ +inline bool operator _op_ (const T* o) const { \ + return m_ptr _op_ o; \ +} \ +template \ +inline bool operator _op_ (const sp& o) const { \ + return m_ptr _op_ o.m_ptr; \ +} \ +template \ +inline bool operator _op_ (const U* o) const { \ + return m_ptr _op_ o; \ +} + +// --------------------------------------------------------------------------- + +class ReferenceRenamer { +protected: + // destructor is purposedly not virtual so we avoid code overhead from + // subclasses; we have to make it protected to guarantee that it + // cannot be called from this base class (and to make strict compilers + // happy). + ~ReferenceRenamer() { } +public: + virtual void operator()(size_t i) const = 0; +}; + +// --------------------------------------------------------------------------- + +class RefBase +{ +public: + void incStrong(const void* id) const; + void decStrong(const void* id) const; + + void forceIncStrong(const void* id) const; + + //! DEBUGGING ONLY: Get current strong ref count. + int32_t getStrongCount() const; + + class weakref_type + { + public: + RefBase* refBase() const; + + void incWeak(const void* id); + void decWeak(const void* id); + + // acquires a strong reference if there is already one. + bool attemptIncStrong(const void* id); + + // acquires a weak reference if there is already one. + // This is not always safe. see ProcessState.cpp and BpBinder.cpp + // for proper use. + bool attemptIncWeak(const void* id); + + //! DEBUGGING ONLY: Get current weak ref count. + int32_t getWeakCount() const; + + //! DEBUGGING ONLY: Print references held on object. + void printRefs() const; + + //! DEBUGGING ONLY: Enable tracking for this object. + // enable -- enable/disable tracking + // retain -- when tracking is enable, if true, then we save a stack trace + // for each reference and dereference; when retain == false, we + // match up references and dereferences and keep only the + // outstanding ones. + + void trackMe(bool enable, bool retain); + }; + + weakref_type* createWeak(const void* id) const; + + weakref_type* getWeakRefs() const; + + //! DEBUGGING ONLY: Print references held on object. + inline void printRefs() const { getWeakRefs()->printRefs(); } + + //! DEBUGGING ONLY: Enable tracking of object. + inline void trackMe(bool enable, bool retain) + { + getWeakRefs()->trackMe(enable, retain); + } + + typedef RefBase basetype; + +protected: + RefBase(); + virtual ~RefBase(); + + //! Flags for extendObjectLifetime() + enum { + OBJECT_LIFETIME_STRONG = 0x0000, + OBJECT_LIFETIME_WEAK = 0x0001, + OBJECT_LIFETIME_MASK = 0x0001 + }; + + void extendObjectLifetime(int32_t mode); + + //! Flags for onIncStrongAttempted() + enum { + FIRST_INC_STRONG = 0x0001 + }; + + virtual void onFirstRef(); + virtual void onLastStrongRef(const void* id); + virtual bool onIncStrongAttempted(uint32_t flags, const void* id); + virtual void onLastWeakRef(const void* id); + +private: + friend class weakref_type; + class weakref_impl; + + RefBase(const RefBase& o); + RefBase& operator=(const RefBase& o); + +private: + friend class ReferenceMover; + + static void renameRefs(size_t n, const ReferenceRenamer& renamer); + + static void renameRefId(weakref_type* ref, + const void* old_id, const void* new_id); + + static void renameRefId(RefBase* ref, + const void* old_id, const void* new_id); + + weakref_impl* const mRefs; +}; + +// --------------------------------------------------------------------------- + +template +class LightRefBase +{ +public: + inline LightRefBase() : mCount(0) { } + inline void incStrong(__attribute__((unused)) const void* id) const { + android_atomic_inc(&mCount); + } + inline void decStrong(__attribute__((unused)) const void* id) const { + if (android_atomic_dec(&mCount) == 1) { + delete static_cast(this); + } + } + //! DEBUGGING ONLY: Get current strong ref count. + inline int32_t getStrongCount() const { + return mCount; + } + + typedef LightRefBase basetype; + +protected: + inline ~LightRefBase() { } + +private: + friend class ReferenceMover; + inline static void renameRefs(size_t n, const ReferenceRenamer& renamer) { } + inline static void renameRefId(T* ref, + const void* old_id, const void* new_id) { } + +private: + mutable volatile int32_t mCount; +}; + +// This is a wrapper around LightRefBase that simply enforces a virtual +// destructor to eliminate the template requirement of LightRefBase +class VirtualLightRefBase : public LightRefBase { +public: + virtual ~VirtualLightRefBase() {} +}; + +// --------------------------------------------------------------------------- + +template +class wp +{ +public: + typedef typename RefBase::weakref_type weakref_type; + + inline wp() : m_ptr(0) { } + + wp(T* other); + wp(const wp& other); + wp(const sp& other); + template wp(U* other); + template wp(const sp& other); + template wp(const wp& other); + + ~wp(); + + // Assignment + + wp& operator = (T* other); + wp& operator = (const wp& other); + wp& operator = (const sp& other); + + template wp& operator = (U* other); + template wp& operator = (const wp& other); + template wp& operator = (const sp& other); + + void set_object_and_refs(T* other, weakref_type* refs); + + // promotion to sp + + sp promote() const; + + // Reset + + void clear(); + + // Accessors + + inline weakref_type* get_refs() const { return m_refs; } + + inline T* unsafe_get() const { return m_ptr; } + + // Operators + + COMPARE_WEAK(==) + COMPARE_WEAK(!=) + COMPARE_WEAK(>) + COMPARE_WEAK(<) + COMPARE_WEAK(<=) + COMPARE_WEAK(>=) + + inline bool operator == (const wp& o) const { + return (m_ptr == o.m_ptr) && (m_refs == o.m_refs); + } + template + inline bool operator == (const wp& o) const { + return m_ptr == o.m_ptr; + } + + inline bool operator > (const wp& o) const { + return (m_ptr == o.m_ptr) ? (m_refs > o.m_refs) : (m_ptr > o.m_ptr); + } + template + inline bool operator > (const wp& o) const { + return (m_ptr == o.m_ptr) ? (m_refs > o.m_refs) : (m_ptr > o.m_ptr); + } + + inline bool operator < (const wp& o) const { + return (m_ptr == o.m_ptr) ? (m_refs < o.m_refs) : (m_ptr < o.m_ptr); + } + template + inline bool operator < (const wp& o) const { + return (m_ptr == o.m_ptr) ? (m_refs < o.m_refs) : (m_ptr < o.m_ptr); + } + inline bool operator != (const wp& o) const { return m_refs != o.m_refs; } + template inline bool operator != (const wp& o) const { return !operator == (o); } + inline bool operator <= (const wp& o) const { return !operator > (o); } + template inline bool operator <= (const wp& o) const { return !operator > (o); } + inline bool operator >= (const wp& o) const { return !operator < (o); } + template inline bool operator >= (const wp& o) const { return !operator < (o); } + +private: + template friend class sp; + template friend class wp; + + T* m_ptr; + weakref_type* m_refs; +}; + +template +TextOutput& operator<<(TextOutput& to, const wp& val); + +#undef COMPARE_WEAK + +// --------------------------------------------------------------------------- +// No user serviceable parts below here. + +template +wp::wp(T* other) + : m_ptr(other) +{ + if (other) m_refs = other->createWeak(this); +} + +template +wp::wp(const wp& other) + : m_ptr(other.m_ptr), m_refs(other.m_refs) +{ + if (m_ptr) m_refs->incWeak(this); +} + +template +wp::wp(const sp& other) + : m_ptr(other.m_ptr) +{ + if (m_ptr) { + m_refs = m_ptr->createWeak(this); + } +} + +template template +wp::wp(U* other) + : m_ptr(other) +{ + if (other) m_refs = other->createWeak(this); +} + +template template +wp::wp(const wp& other) + : m_ptr(other.m_ptr) +{ + if (m_ptr) { + m_refs = other.m_refs; + m_refs->incWeak(this); + } +} + +template template +wp::wp(const sp& other) + : m_ptr(other.m_ptr) +{ + if (m_ptr) { + m_refs = m_ptr->createWeak(this); + } +} + +template +wp::~wp() +{ + if (m_ptr) m_refs->decWeak(this); +} + +template +wp& wp::operator = (T* other) +{ + weakref_type* newRefs = + other ? other->createWeak(this) : 0; + if (m_ptr) m_refs->decWeak(this); + m_ptr = other; + m_refs = newRefs; + return *this; +} + +template +wp& wp::operator = (const wp& other) +{ + weakref_type* otherRefs(other.m_refs); + T* otherPtr(other.m_ptr); + if (otherPtr) otherRefs->incWeak(this); + if (m_ptr) m_refs->decWeak(this); + m_ptr = otherPtr; + m_refs = otherRefs; + return *this; +} + +template +wp& wp::operator = (const sp& other) +{ + weakref_type* newRefs = + other != NULL ? other->createWeak(this) : 0; + T* otherPtr(other.m_ptr); + if (m_ptr) m_refs->decWeak(this); + m_ptr = otherPtr; + m_refs = newRefs; + return *this; +} + +template template +wp& wp::operator = (U* other) +{ + weakref_type* newRefs = + other ? other->createWeak(this) : 0; + if (m_ptr) m_refs->decWeak(this); + m_ptr = other; + m_refs = newRefs; + return *this; +} + +template template +wp& wp::operator = (const wp& other) +{ + weakref_type* otherRefs(other.m_refs); + U* otherPtr(other.m_ptr); + if (otherPtr) otherRefs->incWeak(this); + if (m_ptr) m_refs->decWeak(this); + m_ptr = otherPtr; + m_refs = otherRefs; + return *this; +} + +template template +wp& wp::operator = (const sp& other) +{ + weakref_type* newRefs = + other != NULL ? other->createWeak(this) : 0; + U* otherPtr(other.m_ptr); + if (m_ptr) m_refs->decWeak(this); + m_ptr = otherPtr; + m_refs = newRefs; + return *this; +} + +template +void wp::set_object_and_refs(T* other, weakref_type* refs) +{ + if (other) refs->incWeak(this); + if (m_ptr) m_refs->decWeak(this); + m_ptr = other; + m_refs = refs; +} + +template +sp wp::promote() const +{ + sp result; + if (m_ptr && m_refs->attemptIncStrong(&result)) { + result.set_pointer(m_ptr); + } + return result; +} + +template +void wp::clear() +{ + if (m_ptr) { + m_refs->decWeak(this); + m_ptr = 0; + } +} + +template +inline TextOutput& operator<<(TextOutput& to, const wp& val) +{ + return printWeakPointer(to, val.unsafe_get()); +} + +// --------------------------------------------------------------------------- + +// this class just serves as a namespace so TYPE::moveReferences can stay +// private. +class ReferenceMover { +public: + // it would be nice if we could make sure no extra code is generated + // for sp or wp when TYPE is a descendant of RefBase: + // Using a sp override doesn't work; it's a bit like we wanted + // a template template... + + template static inline + void move_references(sp* d, sp const* s, size_t n) { + + class Renamer : public ReferenceRenamer { + sp* d; + sp const* s; + virtual void operator()(size_t i) const { + // The id are known to be the sp<>'s this pointer + TYPE::renameRefId(d[i].get(), &s[i], &d[i]); + } + public: + Renamer(sp* d, sp const* s) : d(d), s(s) { } + virtual ~Renamer() { } + }; + + memmove(d, s, n*sizeof(sp)); + TYPE::renameRefs(n, Renamer(d, s)); + } + + + template static inline + void move_references(wp* d, wp const* s, size_t n) { + + class Renamer : public ReferenceRenamer { + wp* d; + wp const* s; + virtual void operator()(size_t i) const { + // The id are known to be the wp<>'s this pointer + TYPE::renameRefId(d[i].get_refs(), &s[i], &d[i]); + } + public: + Renamer(wp* d, wp const* s) : d(d), s(s) { } + virtual ~Renamer() { } + }; + + memmove(d, s, n*sizeof(wp)); + TYPE::renameRefs(n, Renamer(d, s)); + } +}; + +// specialization for moving sp<> and wp<> types. +// these are used by the [Sorted|Keyed]Vector<> implementations +// sp<> and wp<> need to be handled specially, because they do not +// have trivial copy operation in the general case (see RefBase.cpp +// when DEBUG ops are enabled), but can be implemented very +// efficiently in most cases. + +template inline +void move_forward_type(sp* d, sp const* s, size_t n) { + ReferenceMover::move_references(d, s, n); +} + +template inline +void move_backward_type(sp* d, sp const* s, size_t n) { + ReferenceMover::move_references(d, s, n); +} + +template inline +void move_forward_type(wp* d, wp const* s, size_t n) { + ReferenceMover::move_references(d, s, n); +} + +template inline +void move_backward_type(wp* d, wp const* s, size_t n) { + ReferenceMover::move_references(d, s, n); +} + + +}; // namespace android + +// --------------------------------------------------------------------------- + +#endif // ANDROID_REF_BASE_H diff --git a/phonelibs/android_system_core/include/utils/SharedBuffer.h b/phonelibs/android_system_core/include/utils/SharedBuffer.h new file mode 100644 index 0000000000..b6709537e6 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/SharedBuffer.h @@ -0,0 +1,137 @@ +/* + * 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_SHARED_BUFFER_H +#define ANDROID_SHARED_BUFFER_H + +#include +#include + +// --------------------------------------------------------------------------- + +namespace android { + +class SharedBuffer +{ +public: + + /* flags to use with release() */ + enum { + eKeepStorage = 0x00000001 + }; + + /*! allocate a buffer of size 'size' and acquire() it. + * call release() to free it. + */ + static SharedBuffer* alloc(size_t size); + + /*! free the memory associated with the SharedBuffer. + * Fails if there are any users associated with this SharedBuffer. + * In other words, the buffer must have been release by all its + * users. + */ + static ssize_t dealloc(const SharedBuffer* released); + + //! access the data for read + inline const void* data() const; + + //! access the data for read/write + inline void* data(); + + //! get size of the buffer + inline size_t size() const; + + //! get back a SharedBuffer object from its data + static inline SharedBuffer* bufferFromData(void* data); + + //! get back a SharedBuffer object from its data + static inline const SharedBuffer* bufferFromData(const void* data); + + //! get the size of a SharedBuffer object from its data + static inline size_t sizeFromData(const void* data); + + //! edit the buffer (get a writtable, or non-const, version of it) + SharedBuffer* edit() const; + + //! edit the buffer, resizing if needed + SharedBuffer* editResize(size_t size) const; + + //! like edit() but fails if a copy is required + SharedBuffer* attemptEdit() const; + + //! resize and edit the buffer, loose it's content. + SharedBuffer* reset(size_t size) const; + + //! acquire/release a reference on this buffer + void acquire() const; + + /*! release a reference on this buffer, with the option of not + * freeing the memory associated with it if it was the last reference + * returns the previous reference count + */ + int32_t release(uint32_t flags = 0) const; + + //! returns wether or not we're the only owner + inline bool onlyOwner() const; + + +private: + inline SharedBuffer() { } + inline ~SharedBuffer() { } + SharedBuffer(const SharedBuffer&); + SharedBuffer& operator = (const SharedBuffer&); + + // 16 bytes. must be sized to preserve correct alignment. + mutable int32_t mRefs; + size_t mSize; + uint32_t mReserved[2]; +}; + +// --------------------------------------------------------------------------- + +const void* SharedBuffer::data() const { + return this + 1; +} + +void* SharedBuffer::data() { + return this + 1; +} + +size_t SharedBuffer::size() const { + return mSize; +} + +SharedBuffer* SharedBuffer::bufferFromData(void* data) { + return data ? static_cast(data)-1 : 0; +} + +const SharedBuffer* SharedBuffer::bufferFromData(const void* data) { + return data ? static_cast(data)-1 : 0; +} + +size_t SharedBuffer::sizeFromData(const void* data) { + return data ? bufferFromData(data)->mSize : 0; +} + +bool SharedBuffer::onlyOwner() const { + return (mRefs == 1); +} + +}; // namespace android + +// --------------------------------------------------------------------------- + +#endif // ANDROID_VECTOR_H diff --git a/phonelibs/android_system_core/include/utils/Singleton.h b/phonelibs/android_system_core/include/utils/Singleton.h new file mode 100644 index 0000000000..ffc03cb5d6 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/Singleton.h @@ -0,0 +1,78 @@ +/* + * 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_UTILS_SINGLETON_H +#define ANDROID_UTILS_SINGLETON_H + +#include +#include +#include +#include + +namespace android { +// --------------------------------------------------------------------------- + +template +class ANDROID_API Singleton +{ +public: + static TYPE& getInstance() { + Mutex::Autolock _l(sLock); + TYPE* instance = sInstance; + if (instance == 0) { + instance = new TYPE(); + sInstance = instance; + } + return *instance; + } + + static bool hasInstance() { + Mutex::Autolock _l(sLock); + return sInstance != 0; + } + +protected: + ~Singleton() { }; + Singleton() { }; + +private: + Singleton(const Singleton&); + Singleton& operator = (const Singleton&); + static Mutex sLock; + static TYPE* sInstance; +}; + +/* + * use ANDROID_SINGLETON_STATIC_INSTANCE(TYPE) in your implementation file + * (eg: .cpp) to create the static instance of Singleton<>'s attributes, + * and avoid to have a copy of them in each compilation units Singleton + * is used. + * NOTE: we use a version of Mutex ctor that takes a parameter, because + * for some unknown reason using the default ctor doesn't emit the variable! + */ + +#define ANDROID_SINGLETON_STATIC_INSTANCE(TYPE) \ + template<> ::android::Mutex \ + (::android::Singleton< TYPE >::sLock)(::android::Mutex::PRIVATE); \ + template<> TYPE* ::android::Singleton< TYPE >::sInstance(0); \ + template class ::android::Singleton< TYPE >; + + +// --------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_UTILS_SINGLETON_H + diff --git a/phonelibs/android_system_core/include/utils/SortedVector.h b/phonelibs/android_system_core/include/utils/SortedVector.h new file mode 100644 index 0000000000..2d3e82a7c0 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/SortedVector.h @@ -0,0 +1,282 @@ +/* + * 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_SORTED_VECTOR_H +#define ANDROID_SORTED_VECTOR_H + +#include +#include +#include + +#include + +#include +#include +#include + +// --------------------------------------------------------------------------- + +namespace android { + +template +class SortedVector : private SortedVectorImpl +{ + friend class Vector; + +public: + typedef TYPE value_type; + + /*! + * Constructors and destructors + */ + + SortedVector(); + SortedVector(const SortedVector& rhs); + virtual ~SortedVector(); + + /*! copy operator */ + const SortedVector& operator = (const SortedVector& rhs) const; + SortedVector& operator = (const SortedVector& rhs); + + /* + * empty the vector + */ + + inline void clear() { VectorImpl::clear(); } + + /*! + * vector stats + */ + + //! returns number of items in the vector + inline size_t size() const { return VectorImpl::size(); } + //! returns whether or not the vector is empty + inline bool isEmpty() const { return VectorImpl::isEmpty(); } + //! returns how many items can be stored without reallocating the backing store + inline size_t capacity() const { return VectorImpl::capacity(); } + //! sets the capacity. capacity can never be reduced less than size() + inline ssize_t setCapacity(size_t size) { return VectorImpl::setCapacity(size); } + + /*! + * C-style array access + */ + + //! read-only C-style access + inline const TYPE* array() const; + + //! read-write C-style access. BE VERY CAREFUL when modifying the array + //! you must keep it sorted! You usually don't use this function. + TYPE* editArray(); + + //! finds the index of an item + ssize_t indexOf(const TYPE& item) const; + + //! finds where this item should be inserted + size_t orderOf(const TYPE& item) const; + + + /*! + * accessors + */ + + //! read-only access to an item at a given index + inline const TYPE& operator [] (size_t index) const; + //! alternate name for operator [] + inline const TYPE& itemAt(size_t index) const; + //! stack-usage of the vector. returns the top of the stack (last element) + const TYPE& top() const; + + /*! + * modifying the array + */ + + //! add an item in the right place (and replace the one that is there) + ssize_t add(const TYPE& item); + + //! editItemAt() MUST NOT change the order of this item + TYPE& editItemAt(size_t index) { + return *( static_cast(VectorImpl::editItemLocation(index)) ); + } + + //! merges a vector into this one + ssize_t merge(const Vector& vector); + ssize_t merge(const SortedVector& vector); + + //! removes an item + ssize_t remove(const TYPE&); + + //! remove several items + inline ssize_t removeItemsAt(size_t index, size_t count = 1); + //! remove one item + inline ssize_t removeAt(size_t index) { return removeItemsAt(index); } + +protected: + virtual void do_construct(void* storage, size_t num) const; + virtual void do_destroy(void* storage, size_t num) const; + virtual void do_copy(void* dest, const void* from, size_t num) const; + virtual void do_splat(void* dest, const void* item, size_t num) const; + virtual void do_move_forward(void* dest, const void* from, size_t num) const; + virtual void do_move_backward(void* dest, const void* from, size_t num) const; + virtual int do_compare(const void* lhs, const void* rhs) const; +}; + +// SortedVector can be trivially moved using memcpy() because moving does not +// require any change to the underlying SharedBuffer contents or reference count. +template struct trait_trivial_move > { enum { value = true }; }; + +// --------------------------------------------------------------------------- +// No user serviceable parts from here... +// --------------------------------------------------------------------------- + +template inline +SortedVector::SortedVector() + : SortedVectorImpl(sizeof(TYPE), + ((traits::has_trivial_ctor ? HAS_TRIVIAL_CTOR : 0) + |(traits::has_trivial_dtor ? HAS_TRIVIAL_DTOR : 0) + |(traits::has_trivial_copy ? HAS_TRIVIAL_COPY : 0)) + ) +{ +} + +template inline +SortedVector::SortedVector(const SortedVector& rhs) + : SortedVectorImpl(rhs) { +} + +template inline +SortedVector::~SortedVector() { + finish_vector(); +} + +template inline +SortedVector& SortedVector::operator = (const SortedVector& rhs) { + SortedVectorImpl::operator = (rhs); + return *this; +} + +template inline +const SortedVector& SortedVector::operator = (const SortedVector& rhs) const { + SortedVectorImpl::operator = (rhs); + return *this; +} + +template inline +const TYPE* SortedVector::array() const { + return static_cast(arrayImpl()); +} + +template inline +TYPE* SortedVector::editArray() { + return static_cast(editArrayImpl()); +} + + +template inline +const TYPE& SortedVector::operator[](size_t index) const { + LOG_FATAL_IF(index>=size(), + "%s: index=%u out of range (%u)", __PRETTY_FUNCTION__, + int(index), int(size())); + return *(array() + index); +} + +template inline +const TYPE& SortedVector::itemAt(size_t index) const { + return operator[](index); +} + +template inline +const TYPE& SortedVector::top() const { + return *(array() + size() - 1); +} + +template inline +ssize_t SortedVector::add(const TYPE& item) { + return SortedVectorImpl::add(&item); +} + +template inline +ssize_t SortedVector::indexOf(const TYPE& item) const { + return SortedVectorImpl::indexOf(&item); +} + +template inline +size_t SortedVector::orderOf(const TYPE& item) const { + return SortedVectorImpl::orderOf(&item); +} + +template inline +ssize_t SortedVector::merge(const Vector& vector) { + return SortedVectorImpl::merge(reinterpret_cast(vector)); +} + +template inline +ssize_t SortedVector::merge(const SortedVector& vector) { + return SortedVectorImpl::merge(reinterpret_cast(vector)); +} + +template inline +ssize_t SortedVector::remove(const TYPE& item) { + return SortedVectorImpl::remove(&item); +} + +template inline +ssize_t SortedVector::removeItemsAt(size_t index, size_t count) { + return VectorImpl::removeItemsAt(index, count); +} + +// --------------------------------------------------------------------------- + +template +void SortedVector::do_construct(void* storage, size_t num) const { + construct_type( reinterpret_cast(storage), num ); +} + +template +void SortedVector::do_destroy(void* storage, size_t num) const { + destroy_type( reinterpret_cast(storage), num ); +} + +template +void SortedVector::do_copy(void* dest, const void* from, size_t num) const { + copy_type( reinterpret_cast(dest), reinterpret_cast(from), num ); +} + +template +void SortedVector::do_splat(void* dest, const void* item, size_t num) const { + splat_type( reinterpret_cast(dest), reinterpret_cast(item), num ); +} + +template +void SortedVector::do_move_forward(void* dest, const void* from, size_t num) const { + move_forward_type( reinterpret_cast(dest), reinterpret_cast(from), num ); +} + +template +void SortedVector::do_move_backward(void* dest, const void* from, size_t num) const { + move_backward_type( reinterpret_cast(dest), reinterpret_cast(from), num ); +} + +template +int SortedVector::do_compare(const void* lhs, const void* rhs) const { + return compare_type( *reinterpret_cast(lhs), *reinterpret_cast(rhs) ); +} + +}; // namespace android + + +// --------------------------------------------------------------------------- + +#endif // ANDROID_SORTED_VECTOR_H diff --git a/phonelibs/android_system_core/include/utils/StopWatch.h b/phonelibs/android_system_core/include/utils/StopWatch.h new file mode 100644 index 0000000000..693dd3ccfc --- /dev/null +++ b/phonelibs/android_system_core/include/utils/StopWatch.h @@ -0,0 +1,64 @@ +/* + * 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_STOPWATCH_H +#define ANDROID_STOPWATCH_H + +#include +#include + +#include + +// --------------------------------------------------------------------------- + +namespace android { + +class StopWatch +{ +public: + StopWatch( const char *name, + int clock = SYSTEM_TIME_MONOTONIC, + uint32_t flags = 0); + ~StopWatch(); + + const char* name() const; + nsecs_t lap(); + nsecs_t elapsedTime() const; + + void reset(); + +private: + const char* mName; + int mClock; + uint32_t mFlags; + + struct lap_t { + nsecs_t soFar; + nsecs_t thisLap; + }; + + nsecs_t mStartTime; + lap_t mLaps[8]; + int mNumLaps; +}; + + +}; // namespace android + + +// --------------------------------------------------------------------------- + +#endif // ANDROID_STOPWATCH_H diff --git a/phonelibs/android_system_core/include/utils/String16.h b/phonelibs/android_system_core/include/utils/String16.h new file mode 100644 index 0000000000..d131bfc6a7 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/String16.h @@ -0,0 +1,250 @@ +/* + * 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_STRING16_H +#define ANDROID_STRING16_H + +#include +#include +#include +#include + +// --------------------------------------------------------------------------- + +extern "C" { + +} + +// --------------------------------------------------------------------------- + +namespace android { + +// --------------------------------------------------------------------------- + +class String8; +class TextOutput; + +//! This is a string holding UTF-16 characters. +class String16 +{ +public: + /* use String16(StaticLinkage) if you're statically linking against + * libutils and declaring an empty static String16, e.g.: + * + * static String16 sAStaticEmptyString(String16::kEmptyString); + * static String16 sAnotherStaticEmptyString(sAStaticEmptyString); + */ + enum StaticLinkage { kEmptyString }; + + String16(); + explicit String16(StaticLinkage); + String16(const String16& o); + String16(const String16& o, + size_t len, + size_t begin=0); + explicit String16(const char16_t* o); + explicit String16(const char16_t* o, size_t len); + explicit String16(const String8& o); + explicit String16(const char* o); + explicit String16(const char* o, size_t len); + + ~String16(); + + inline const char16_t* string() const; + inline size_t size() const; + + inline const SharedBuffer* sharedBuffer() const; + + void setTo(const String16& other); + status_t setTo(const char16_t* other); + status_t setTo(const char16_t* other, size_t len); + status_t setTo(const String16& other, + size_t len, + size_t begin=0); + + status_t append(const String16& other); + status_t append(const char16_t* other, size_t len); + + inline String16& operator=(const String16& other); + + inline String16& operator+=(const String16& other); + inline String16 operator+(const String16& other) const; + + status_t insert(size_t pos, const char16_t* chrs); + status_t insert(size_t pos, + const char16_t* chrs, size_t len); + + ssize_t findFirst(char16_t c) const; + ssize_t findLast(char16_t c) const; + + bool startsWith(const String16& prefix) const; + bool startsWith(const char16_t* prefix) const; + + status_t makeLower(); + + status_t replaceAll(char16_t replaceThis, + char16_t withThis); + + status_t remove(size_t len, size_t begin=0); + + inline int compare(const String16& other) const; + + inline bool operator<(const String16& other) const; + inline bool operator<=(const String16& other) const; + inline bool operator==(const String16& other) const; + inline bool operator!=(const String16& other) const; + inline bool operator>=(const String16& other) const; + inline bool operator>(const String16& other) const; + + inline bool operator<(const char16_t* other) const; + inline bool operator<=(const char16_t* other) const; + inline bool operator==(const char16_t* other) const; + inline bool operator!=(const char16_t* other) const; + inline bool operator>=(const char16_t* other) const; + inline bool operator>(const char16_t* other) const; + + inline operator const char16_t*() const; + +private: + const char16_t* mString; +}; + +// String16 can be trivially moved using memcpy() because moving does not +// require any change to the underlying SharedBuffer contents or reference count. +ANDROID_TRIVIAL_MOVE_TRAIT(String16) + +// --------------------------------------------------------------------------- +// No user servicable parts below. + +inline int compare_type(const String16& lhs, const String16& rhs) +{ + return lhs.compare(rhs); +} + +inline int strictly_order_type(const String16& lhs, const String16& rhs) +{ + return compare_type(lhs, rhs) < 0; +} + +inline const char16_t* String16::string() const +{ + return mString; +} + +inline size_t String16::size() const +{ + return SharedBuffer::sizeFromData(mString)/sizeof(char16_t)-1; +} + +inline const SharedBuffer* String16::sharedBuffer() const +{ + return SharedBuffer::bufferFromData(mString); +} + +inline String16& String16::operator=(const String16& other) +{ + setTo(other); + return *this; +} + +inline String16& String16::operator+=(const String16& other) +{ + append(other); + return *this; +} + +inline String16 String16::operator+(const String16& other) const +{ + String16 tmp(*this); + tmp += other; + return tmp; +} + +inline int String16::compare(const String16& other) const +{ + return strzcmp16(mString, size(), other.mString, other.size()); +} + +inline bool String16::operator<(const String16& other) const +{ + return strzcmp16(mString, size(), other.mString, other.size()) < 0; +} + +inline bool String16::operator<=(const String16& other) const +{ + return strzcmp16(mString, size(), other.mString, other.size()) <= 0; +} + +inline bool String16::operator==(const String16& other) const +{ + return strzcmp16(mString, size(), other.mString, other.size()) == 0; +} + +inline bool String16::operator!=(const String16& other) const +{ + return strzcmp16(mString, size(), other.mString, other.size()) != 0; +} + +inline bool String16::operator>=(const String16& other) const +{ + return strzcmp16(mString, size(), other.mString, other.size()) >= 0; +} + +inline bool String16::operator>(const String16& other) const +{ + return strzcmp16(mString, size(), other.mString, other.size()) > 0; +} + +inline bool String16::operator<(const char16_t* other) const +{ + return strcmp16(mString, other) < 0; +} + +inline bool String16::operator<=(const char16_t* other) const +{ + return strcmp16(mString, other) <= 0; +} + +inline bool String16::operator==(const char16_t* other) const +{ + return strcmp16(mString, other) == 0; +} + +inline bool String16::operator!=(const char16_t* other) const +{ + return strcmp16(mString, other) != 0; +} + +inline bool String16::operator>=(const char16_t* other) const +{ + return strcmp16(mString, other) >= 0; +} + +inline bool String16::operator>(const char16_t* other) const +{ + return strcmp16(mString, other) > 0; +} + +inline String16::operator const char16_t*() const +{ + return mString; +} + +}; // namespace android + +// --------------------------------------------------------------------------- + +#endif // ANDROID_STRING16_H diff --git a/phonelibs/android_system_core/include/utils/String8.h b/phonelibs/android_system_core/include/utils/String8.h new file mode 100644 index 0000000000..ecfcf10be7 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/String8.h @@ -0,0 +1,408 @@ +/* + * 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_STRING8_H +#define ANDROID_STRING8_H + +#include +#include +#include +#include + +#include // for strcmp +#include + +// --------------------------------------------------------------------------- + +namespace android { + +class String16; +class TextOutput; + +//! This is a string holding UTF-8 characters. Does not allow the value more +// than 0x10FFFF, which is not valid unicode codepoint. +class String8 +{ +public: + /* use String8(StaticLinkage) if you're statically linking against + * libutils and declaring an empty static String8, e.g.: + * + * static String8 sAStaticEmptyString(String8::kEmptyString); + * static String8 sAnotherStaticEmptyString(sAStaticEmptyString); + */ + enum StaticLinkage { kEmptyString }; + + String8(); + explicit String8(StaticLinkage); + String8(const String8& o); + explicit String8(const char* o); + explicit String8(const char* o, size_t numChars); + + explicit String8(const String16& o); + explicit String8(const char16_t* o); + explicit String8(const char16_t* o, size_t numChars); + explicit String8(const char32_t* o); + explicit String8(const char32_t* o, size_t numChars); + ~String8(); + + static inline const String8 empty(); + + static String8 format(const char* fmt, ...) __attribute__((format (printf, 1, 2))); + static String8 formatV(const char* fmt, va_list args); + + inline const char* string() const; + inline size_t size() const; + inline size_t length() const; + inline size_t bytes() const; + inline bool isEmpty() const; + + inline const SharedBuffer* sharedBuffer() const; + + void clear(); + + void setTo(const String8& other); + status_t setTo(const char* other); + status_t setTo(const char* other, size_t numChars); + status_t setTo(const char16_t* other, size_t numChars); + status_t setTo(const char32_t* other, + size_t length); + + status_t append(const String8& other); + status_t append(const char* other); + status_t append(const char* other, size_t numChars); + + status_t appendFormat(const char* fmt, ...) + __attribute__((format (printf, 2, 3))); + status_t appendFormatV(const char* fmt, va_list args); + + // Note that this function takes O(N) time to calculate the value. + // No cache value is stored. + size_t getUtf32Length() const; + int32_t getUtf32At(size_t index, + size_t *next_index) const; + void getUtf32(char32_t* dst) const; + + inline String8& operator=(const String8& other); + inline String8& operator=(const char* other); + + inline String8& operator+=(const String8& other); + inline String8 operator+(const String8& other) const; + + inline String8& operator+=(const char* other); + inline String8 operator+(const char* other) const; + + inline int compare(const String8& other) const; + + inline bool operator<(const String8& other) const; + inline bool operator<=(const String8& other) const; + inline bool operator==(const String8& other) const; + inline bool operator!=(const String8& other) const; + inline bool operator>=(const String8& other) const; + inline bool operator>(const String8& other) const; + + inline bool operator<(const char* other) const; + inline bool operator<=(const char* other) const; + inline bool operator==(const char* other) const; + inline bool operator!=(const char* other) const; + inline bool operator>=(const char* other) const; + inline bool operator>(const char* other) const; + + inline operator const char*() const; + + char* lockBuffer(size_t size); + void unlockBuffer(); + status_t unlockBuffer(size_t size); + + // return the index of the first byte of other in this at or after + // start, or -1 if not found + ssize_t find(const char* other, size_t start = 0) const; + + // return true if this string contains the specified substring + inline bool contains(const char* other) const; + + // removes all occurrence of the specified substring + // returns true if any were found and removed + bool removeAll(const char* other); + + void toLower(); + void toLower(size_t start, size_t numChars); + void toUpper(); + void toUpper(size_t start, size_t numChars); + + + /* + * These methods operate on the string as if it were a path name. + */ + + /* + * Set the filename field to a specific value. + * + * Normalizes the filename, removing a trailing '/' if present. + */ + void setPathName(const char* name); + void setPathName(const char* name, size_t numChars); + + /* + * Get just the filename component. + * + * "/tmp/foo/bar.c" --> "bar.c" + */ + String8 getPathLeaf(void) const; + + /* + * Remove the last (file name) component, leaving just the directory + * name. + * + * "/tmp/foo/bar.c" --> "/tmp/foo" + * "/tmp" --> "" // ????? shouldn't this be "/" ???? XXX + * "bar.c" --> "" + */ + String8 getPathDir(void) const; + + /* + * Retrieve the front (root dir) component. Optionally also return the + * remaining components. + * + * "/tmp/foo/bar.c" --> "tmp" (remain = "foo/bar.c") + * "/tmp" --> "tmp" (remain = "") + * "bar.c" --> "bar.c" (remain = "") + */ + String8 walkPath(String8* outRemains = NULL) const; + + /* + * Return the filename extension. This is the last '.' and any number + * of characters that follow it. The '.' is included in case we + * decide to expand our definition of what constitutes an extension. + * + * "/tmp/foo/bar.c" --> ".c" + * "/tmp" --> "" + * "/tmp/foo.bar/baz" --> "" + * "foo.jpeg" --> ".jpeg" + * "foo." --> "" + */ + String8 getPathExtension(void) const; + + /* + * Return the path without the extension. Rules for what constitutes + * an extension are described in the comment for getPathExtension(). + * + * "/tmp/foo/bar.c" --> "/tmp/foo/bar" + */ + String8 getBasePath(void) const; + + /* + * Add a component to the pathname. We guarantee that there is + * exactly one path separator between the old path and the new. + * If there is no existing name, we just copy the new name in. + * + * If leaf is a fully qualified path (i.e. starts with '/', it + * replaces whatever was there before. + */ + String8& appendPath(const char* leaf); + String8& appendPath(const String8& leaf) { return appendPath(leaf.string()); } + + /* + * Like appendPath(), but does not affect this string. Returns a new one instead. + */ + String8 appendPathCopy(const char* leaf) const + { String8 p(*this); p.appendPath(leaf); return p; } + String8 appendPathCopy(const String8& leaf) const { return appendPathCopy(leaf.string()); } + + /* + * Converts all separators in this string to /, the default path separator. + * + * If the default OS separator is backslash, this converts all + * backslashes to slashes, in-place. Otherwise it does nothing. + * Returns self. + */ + String8& convertToResPath(); + +private: + status_t real_append(const char* other, size_t numChars); + char* find_extension(void) const; + + const char* mString; +}; + +// String8 can be trivially moved using memcpy() because moving does not +// require any change to the underlying SharedBuffer contents or reference count. +ANDROID_TRIVIAL_MOVE_TRAIT(String8) + +// --------------------------------------------------------------------------- +// No user servicable parts below. + +inline int compare_type(const String8& lhs, const String8& rhs) +{ + return lhs.compare(rhs); +} + +inline int strictly_order_type(const String8& lhs, const String8& rhs) +{ + return compare_type(lhs, rhs) < 0; +} + +inline const String8 String8::empty() { + return String8(); +} + +inline const char* String8::string() const +{ + return mString; +} + +inline size_t String8::length() const +{ + return SharedBuffer::sizeFromData(mString)-1; +} + +inline size_t String8::size() const +{ + return length(); +} + +inline bool String8::isEmpty() const +{ + return length() == 0; +} + +inline size_t String8::bytes() const +{ + return SharedBuffer::sizeFromData(mString)-1; +} + +inline const SharedBuffer* String8::sharedBuffer() const +{ + return SharedBuffer::bufferFromData(mString); +} + +inline bool String8::contains(const char* other) const +{ + return find(other) >= 0; +} + +inline String8& String8::operator=(const String8& other) +{ + setTo(other); + return *this; +} + +inline String8& String8::operator=(const char* other) +{ + setTo(other); + return *this; +} + +inline String8& String8::operator+=(const String8& other) +{ + append(other); + return *this; +} + +inline String8 String8::operator+(const String8& other) const +{ + String8 tmp(*this); + tmp += other; + return tmp; +} + +inline String8& String8::operator+=(const char* other) +{ + append(other); + return *this; +} + +inline String8 String8::operator+(const char* other) const +{ + String8 tmp(*this); + tmp += other; + return tmp; +} + +inline int String8::compare(const String8& other) const +{ + return strcmp(mString, other.mString); +} + +inline bool String8::operator<(const String8& other) const +{ + return strcmp(mString, other.mString) < 0; +} + +inline bool String8::operator<=(const String8& other) const +{ + return strcmp(mString, other.mString) <= 0; +} + +inline bool String8::operator==(const String8& other) const +{ + return strcmp(mString, other.mString) == 0; +} + +inline bool String8::operator!=(const String8& other) const +{ + return strcmp(mString, other.mString) != 0; +} + +inline bool String8::operator>=(const String8& other) const +{ + return strcmp(mString, other.mString) >= 0; +} + +inline bool String8::operator>(const String8& other) const +{ + return strcmp(mString, other.mString) > 0; +} + +inline bool String8::operator<(const char* other) const +{ + return strcmp(mString, other) < 0; +} + +inline bool String8::operator<=(const char* other) const +{ + return strcmp(mString, other) <= 0; +} + +inline bool String8::operator==(const char* other) const +{ + return strcmp(mString, other) == 0; +} + +inline bool String8::operator!=(const char* other) const +{ + return strcmp(mString, other) != 0; +} + +inline bool String8::operator>=(const char* other) const +{ + return strcmp(mString, other) >= 0; +} + +inline bool String8::operator>(const char* other) const +{ + return strcmp(mString, other) > 0; +} + +inline String8::operator const char*() const +{ + return mString; +} + +} // namespace android + +// --------------------------------------------------------------------------- + +#endif // ANDROID_STRING8_H diff --git a/phonelibs/android_system_core/include/utils/StrongPointer.h b/phonelibs/android_system_core/include/utils/StrongPointer.h new file mode 100644 index 0000000000..aba9577da4 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/StrongPointer.h @@ -0,0 +1,211 @@ +/* + * 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_STRONG_POINTER_H +#define ANDROID_STRONG_POINTER_H + +#include + +#include +#include +#include + +// --------------------------------------------------------------------------- +namespace android { + +template class wp; + +// --------------------------------------------------------------------------- + +#define COMPARE(_op_) \ +inline bool operator _op_ (const sp& o) const { \ + return m_ptr _op_ o.m_ptr; \ +} \ +inline bool operator _op_ (const T* o) const { \ + return m_ptr _op_ o; \ +} \ +template \ +inline bool operator _op_ (const sp& o) const { \ + return m_ptr _op_ o.m_ptr; \ +} \ +template \ +inline bool operator _op_ (const U* o) const { \ + return m_ptr _op_ o; \ +} \ +inline bool operator _op_ (const wp& o) const { \ + return m_ptr _op_ o.m_ptr; \ +} \ +template \ +inline bool operator _op_ (const wp& o) const { \ + return m_ptr _op_ o.m_ptr; \ +} + +// --------------------------------------------------------------------------- + +template +class sp { +public: + inline sp() : m_ptr(0) { } + + sp(T* other); + sp(const sp& other); + template sp(U* other); + template sp(const sp& other); + + ~sp(); + + // Assignment + + sp& operator = (T* other); + sp& operator = (const sp& other); + + template sp& operator = (const sp& other); + template sp& operator = (U* other); + + //! Special optimization for use by ProcessState (and nobody else). + void force_set(T* other); + + // Reset + + void clear(); + + // Accessors + + inline T& operator* () const { return *m_ptr; } + inline T* operator-> () const { return m_ptr; } + inline T* get() const { return m_ptr; } + + // Operators + + COMPARE(==) + COMPARE(!=) + COMPARE(>) + COMPARE(<) + COMPARE(<=) + COMPARE(>=) + +private: + template friend class sp; + template friend class wp; + void set_pointer(T* ptr); + T* m_ptr; +}; + +#undef COMPARE + +// --------------------------------------------------------------------------- +// No user serviceable parts below here. + +template +sp::sp(T* other) + : m_ptr(other) { + if (other) + other->incStrong(this); +} + +template +sp::sp(const sp& other) + : m_ptr(other.m_ptr) { + if (m_ptr) + m_ptr->incStrong(this); +} + +template template +sp::sp(U* other) + : m_ptr(other) { + if (other) + ((T*) other)->incStrong(this); +} + +template template +sp::sp(const sp& other) + : m_ptr(other.m_ptr) { + if (m_ptr) + m_ptr->incStrong(this); +} + +template +sp::~sp() { + if (m_ptr) + m_ptr->decStrong(this); +} + +template +sp& sp::operator =(const sp& other) { + T* otherPtr(other.m_ptr); + if (otherPtr) + otherPtr->incStrong(this); + if (m_ptr) + m_ptr->decStrong(this); + m_ptr = otherPtr; + return *this; +} + +template +sp& sp::operator =(T* other) { + if (other) + other->incStrong(this); + if (m_ptr) + m_ptr->decStrong(this); + m_ptr = other; + return *this; +} + +template template +sp& sp::operator =(const sp& other) { + T* otherPtr(other.m_ptr); + if (otherPtr) + otherPtr->incStrong(this); + if (m_ptr) + m_ptr->decStrong(this); + m_ptr = otherPtr; + return *this; +} + +template template +sp& sp::operator =(U* other) { + if (other) + ((T*) other)->incStrong(this); + if (m_ptr) + m_ptr->decStrong(this); + m_ptr = other; + return *this; +} + +template +void sp::force_set(T* other) { + other->forceIncStrong(this); + m_ptr = other; +} + +template +void sp::clear() { + if (m_ptr) { + m_ptr->decStrong(this); + m_ptr = 0; + } +} + +template +void sp::set_pointer(T* ptr) { + m_ptr = ptr; +} + +}; // namespace android + +// --------------------------------------------------------------------------- + +#endif // ANDROID_STRONG_POINTER_H diff --git a/phonelibs/android_system_core/include/utils/SystemClock.h b/phonelibs/android_system_core/include/utils/SystemClock.h new file mode 100644 index 0000000000..01db340780 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/SystemClock.h @@ -0,0 +1,32 @@ +/* + * 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_UTILS_SYSTEMCLOCK_H +#define ANDROID_UTILS_SYSTEMCLOCK_H + +#include +#include + +namespace android { + +int64_t uptimeMillis(); +int64_t elapsedRealtime(); +int64_t elapsedRealtimeNano(); + +}; // namespace android + +#endif // ANDROID_UTILS_SYSTEMCLOCK_H + diff --git a/phonelibs/android_system_core/include/utils/Thread.h b/phonelibs/android_system_core/include/utils/Thread.h new file mode 100644 index 0000000000..28839fdedc --- /dev/null +++ b/phonelibs/android_system_core/include/utils/Thread.h @@ -0,0 +1,116 @@ +/* + * 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 _LIBS_UTILS_THREAD_H +#define _LIBS_UTILS_THREAD_H + +#include +#include +#include + +#if !defined(_WIN32) +# include +#endif + +#include +#include +#include +#include +#include +#include + +// --------------------------------------------------------------------------- +namespace android { +// --------------------------------------------------------------------------- + +class Thread : virtual public RefBase +{ +public: + // Create a Thread object, but doesn't create or start the associated + // thread. See the run() method. + Thread(bool canCallJava = true); + virtual ~Thread(); + + // Start the thread in threadLoop() which needs to be implemented. + virtual status_t run( const char* name = 0, + int32_t priority = PRIORITY_DEFAULT, + size_t stack = 0); + + // Ask this object's thread to exit. This function is asynchronous, when the + // function returns the thread might still be running. Of course, this + // function can be called from a different thread. + virtual void requestExit(); + + // Good place to do one-time initializations + virtual status_t readyToRun(); + + // Call requestExit() and wait until this object's thread exits. + // BE VERY CAREFUL of deadlocks. In particular, it would be silly to call + // this function from this object's thread. Will return WOULD_BLOCK in + // that case. + status_t requestExitAndWait(); + + // Wait until this object's thread exits. Returns immediately if not yet running. + // Do not call from this object's thread; will return WOULD_BLOCK in that case. + status_t join(); + + // Indicates whether this thread is running or not. + bool isRunning() const; + +#ifdef HAVE_ANDROID_OS + // Return the thread's kernel ID, same as the thread itself calling gettid(), + // or -1 if the thread is not running. + pid_t getTid() const; +#endif + +protected: + // exitPending() returns true if requestExit() has been called. + bool exitPending() const; + +private: + // Derived class must implement threadLoop(). The thread starts its life + // here. There are two ways of using the Thread object: + // 1) loop: if threadLoop() returns true, it will be called again if + // requestExit() wasn't called. + // 2) once: if threadLoop() returns false, the thread will exit upon return. + virtual bool threadLoop() = 0; + +private: + Thread& operator=(const Thread&); + static int _threadLoop(void* user); + const bool mCanCallJava; + // always hold mLock when reading or writing + thread_id_t mThread; + mutable Mutex mLock; + Condition mThreadExitedCondition; + status_t mStatus; + // note that all accesses of mExitPending and mRunning need to hold mLock + volatile bool mExitPending; + volatile bool mRunning; + sp mHoldSelf; +#ifdef HAVE_ANDROID_OS + // legacy for debugging, not used by getTid() as it is set by the child thread + // and so is not initialized until the child reaches that point + pid_t mTid; +#endif +}; + + +}; // namespace android + +// --------------------------------------------------------------------------- +#endif // _LIBS_UTILS_THREAD_H +// --------------------------------------------------------------------------- diff --git a/phonelibs/android_system_core/include/utils/ThreadDefs.h b/phonelibs/android_system_core/include/utils/ThreadDefs.h new file mode 100644 index 0000000000..9711c13792 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/ThreadDefs.h @@ -0,0 +1,70 @@ +/* + * 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 _LIBS_UTILS_THREAD_DEFS_H +#define _LIBS_UTILS_THREAD_DEFS_H + +#include +#include +#include +#include + +// --------------------------------------------------------------------------- +// C API + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void* android_thread_id_t; + +typedef int (*android_thread_func_t)(void*); + +#ifdef __cplusplus +} // extern "C" +#endif + +// --------------------------------------------------------------------------- +// C++ API +#ifdef __cplusplus +namespace android { +// --------------------------------------------------------------------------- + +typedef android_thread_id_t thread_id_t; +typedef android_thread_func_t thread_func_t; + +enum { + PRIORITY_LOWEST = ANDROID_PRIORITY_LOWEST, + PRIORITY_BACKGROUND = ANDROID_PRIORITY_BACKGROUND, + PRIORITY_NORMAL = ANDROID_PRIORITY_NORMAL, + PRIORITY_FOREGROUND = ANDROID_PRIORITY_FOREGROUND, + PRIORITY_DISPLAY = ANDROID_PRIORITY_DISPLAY, + PRIORITY_URGENT_DISPLAY = ANDROID_PRIORITY_URGENT_DISPLAY, + PRIORITY_AUDIO = ANDROID_PRIORITY_AUDIO, + PRIORITY_URGENT_AUDIO = ANDROID_PRIORITY_URGENT_AUDIO, + PRIORITY_HIGHEST = ANDROID_PRIORITY_HIGHEST, + PRIORITY_DEFAULT = ANDROID_PRIORITY_DEFAULT, + PRIORITY_MORE_FAVORABLE = ANDROID_PRIORITY_MORE_FAVORABLE, + PRIORITY_LESS_FAVORABLE = ANDROID_PRIORITY_LESS_FAVORABLE, +}; + +// --------------------------------------------------------------------------- +}; // namespace android +#endif // __cplusplus +// --------------------------------------------------------------------------- + + +#endif // _LIBS_UTILS_THREAD_DEFS_H diff --git a/phonelibs/android_system_core/include/utils/Timers.h b/phonelibs/android_system_core/include/utils/Timers.h new file mode 100644 index 0000000000..54ec47489f --- /dev/null +++ b/phonelibs/android_system_core/include/utils/Timers.h @@ -0,0 +1,108 @@ +/* + * 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. + */ + +// +// Timer functions. +// +#ifndef _LIBS_UTILS_TIMERS_H +#define _LIBS_UTILS_TIMERS_H + +#include +#include +#include + +#include + +// ------------------------------------------------------------------ +// C API + +#ifdef __cplusplus +extern "C" { +#endif + +typedef int64_t nsecs_t; // nano-seconds + +static CONSTEXPR inline nsecs_t seconds_to_nanoseconds(nsecs_t secs) +{ + return secs*1000000000; +} + +static CONSTEXPR inline nsecs_t milliseconds_to_nanoseconds(nsecs_t secs) +{ + return secs*1000000; +} + +static CONSTEXPR inline nsecs_t microseconds_to_nanoseconds(nsecs_t secs) +{ + return secs*1000; +} + +static CONSTEXPR inline nsecs_t nanoseconds_to_seconds(nsecs_t secs) +{ + return secs/1000000000; +} + +static CONSTEXPR inline nsecs_t nanoseconds_to_milliseconds(nsecs_t secs) +{ + return secs/1000000; +} + +static CONSTEXPR inline nsecs_t nanoseconds_to_microseconds(nsecs_t secs) +{ + return secs/1000; +} + +static CONSTEXPR inline nsecs_t s2ns(nsecs_t v) {return seconds_to_nanoseconds(v);} +static CONSTEXPR inline nsecs_t ms2ns(nsecs_t v) {return milliseconds_to_nanoseconds(v);} +static CONSTEXPR inline nsecs_t us2ns(nsecs_t v) {return microseconds_to_nanoseconds(v);} +static CONSTEXPR inline nsecs_t ns2s(nsecs_t v) {return nanoseconds_to_seconds(v);} +static CONSTEXPR inline nsecs_t ns2ms(nsecs_t v) {return nanoseconds_to_milliseconds(v);} +static CONSTEXPR inline nsecs_t ns2us(nsecs_t v) {return nanoseconds_to_microseconds(v);} + +static CONSTEXPR inline nsecs_t seconds(nsecs_t v) { return s2ns(v); } +static CONSTEXPR inline nsecs_t milliseconds(nsecs_t v) { return ms2ns(v); } +static CONSTEXPR inline nsecs_t microseconds(nsecs_t v) { return us2ns(v); } + +enum { + SYSTEM_TIME_REALTIME = 0, // system-wide realtime clock + SYSTEM_TIME_MONOTONIC = 1, // monotonic time since unspecified starting point + SYSTEM_TIME_PROCESS = 2, // high-resolution per-process clock + SYSTEM_TIME_THREAD = 3, // high-resolution per-thread clock + SYSTEM_TIME_BOOTTIME = 4 // same as SYSTEM_TIME_MONOTONIC, but including CPU suspend time +}; + +// return the system-time according to the specified clock +#ifdef __cplusplus +nsecs_t systemTime(int clock = SYSTEM_TIME_MONOTONIC); +#else +nsecs_t systemTime(int clock); +#endif // def __cplusplus + +/** + * Returns the number of milliseconds to wait between the reference time and the timeout time. + * If the timeout is in the past relative to the reference time, returns 0. + * If the timeout is more than INT_MAX milliseconds in the future relative to the reference time, + * such as when timeoutTime == LLONG_MAX, returns -1 to indicate an infinite timeout delay. + * Otherwise, returns the difference between the reference time and timeout time + * rounded up to the next millisecond. + */ +int toMillisecondTimeoutDelay(nsecs_t referenceTime, nsecs_t timeoutTime); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // _LIBS_UTILS_TIMERS_H diff --git a/phonelibs/android_system_core/include/utils/Tokenizer.h b/phonelibs/android_system_core/include/utils/Tokenizer.h new file mode 100644 index 0000000000..bb25f374cb --- /dev/null +++ b/phonelibs/android_system_core/include/utils/Tokenizer.h @@ -0,0 +1,136 @@ +/* + * 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 _UTILS_TOKENIZER_H +#define _UTILS_TOKENIZER_H + +#include +#include +#include +#include + +namespace android { + +/** + * A simple tokenizer for loading and parsing ASCII text files line by line. + */ +class Tokenizer { + Tokenizer(const String8& filename, FileMap* fileMap, char* buffer, + bool ownBuffer, size_t length); + +public: + ~Tokenizer(); + + /** + * Opens a file and maps it into memory. + * + * Returns NO_ERROR and a tokenizer for the file, if successful. + * Otherwise returns an error and sets outTokenizer to NULL. + */ + static status_t open(const String8& filename, Tokenizer** outTokenizer); + + /** + * Prepares to tokenize the contents of a string. + * + * Returns NO_ERROR and a tokenizer for the string, if successful. + * Otherwise returns an error and sets outTokenizer to NULL. + */ + static status_t fromContents(const String8& filename, + const char* contents, Tokenizer** outTokenizer); + + /** + * Returns true if at the end of the file. + */ + inline bool isEof() const { return mCurrent == getEnd(); } + + /** + * Returns true if at the end of the line or end of the file. + */ + inline bool isEol() const { return isEof() || *mCurrent == '\n'; } + + /** + * Gets the name of the file. + */ + inline String8 getFilename() const { return mFilename; } + + /** + * Gets a 1-based line number index for the current position. + */ + inline int32_t getLineNumber() const { return mLineNumber; } + + /** + * Formats a location string consisting of the filename and current line number. + * Returns a string like "MyFile.txt:33". + */ + String8 getLocation() const; + + /** + * Gets the character at the current position. + * Returns null at end of file. + */ + inline char peekChar() const { return isEof() ? '\0' : *mCurrent; } + + /** + * Gets the remainder of the current line as a string, excluding the newline character. + */ + String8 peekRemainderOfLine() const; + + /** + * Gets the character at the current position and advances past it. + * Returns null at end of file. + */ + inline char nextChar() { return isEof() ? '\0' : *(mCurrent++); } + + /** + * Gets the next token on this line stopping at the specified delimiters + * or the end of the line whichever comes first and advances past it. + * Also stops at embedded nulls. + * Returns the token or an empty string if the current character is a delimiter + * or is at the end of the line. + */ + String8 nextToken(const char* delimiters); + + /** + * Advances to the next line. + * Does nothing if already at the end of the file. + */ + void nextLine(); + + /** + * Skips over the specified delimiters in the line. + * Also skips embedded nulls. + */ + void skipDelimiters(const char* delimiters); + +private: + Tokenizer(const Tokenizer& other); // not copyable + + String8 mFilename; + FileMap* mFileMap; + char* mBuffer; + bool mOwnBuffer; + size_t mLength; + + const char* mCurrent; + int32_t mLineNumber; + + inline const char* getEnd() const { return mBuffer + mLength; } + +}; + +} // namespace android + +#endif // _UTILS_TOKENIZER_H diff --git a/phonelibs/android_system_core/include/utils/Trace.h b/phonelibs/android_system_core/include/utils/Trace.h new file mode 100644 index 0000000000..6ee343d79a --- /dev/null +++ b/phonelibs/android_system_core/include/utils/Trace.h @@ -0,0 +1,69 @@ +/* + * 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_TRACE_H +#define ANDROID_TRACE_H + +#ifdef HAVE_ANDROID_OS + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +// See for more ATRACE_* macros. + +// ATRACE_NAME traces the beginning and end of the current scope. To trace +// the correct start and end times this macro should be declared first in the +// scope body. +#define ATRACE_NAME(name) android::ScopedTrace ___tracer(ATRACE_TAG, name) +// ATRACE_CALL is an ATRACE_NAME that uses the current function name. +#define ATRACE_CALL() ATRACE_NAME(__FUNCTION__) + +namespace android { + +class ScopedTrace { +public: +inline ScopedTrace(uint64_t tag, const char* name) + : mTag(tag) { + atrace_begin(mTag,name); +} + +inline ~ScopedTrace() { + atrace_end(mTag); +} + +private: + uint64_t mTag; +}; + +}; // namespace android + +#else // HAVE_ANDROID_OS + +#define ATRACE_NAME(...) +#define ATRACE_CALL() + +#endif // HAVE_ANDROID_OS + +#endif // ANDROID_TRACE_H diff --git a/phonelibs/android_system_core/include/utils/TypeHelpers.h b/phonelibs/android_system_core/include/utils/TypeHelpers.h new file mode 100644 index 0000000000..13c9081599 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/TypeHelpers.h @@ -0,0 +1,302 @@ +/* + * 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_TYPE_HELPERS_H +#define ANDROID_TYPE_HELPERS_H + +#include +#include +#include +#include + +// --------------------------------------------------------------------------- + +namespace android { + +/* + * Types traits + */ + +template struct trait_trivial_ctor { enum { value = false }; }; +template struct trait_trivial_dtor { enum { value = false }; }; +template struct trait_trivial_copy { enum { value = false }; }; +template struct trait_trivial_move { enum { value = false }; }; +template struct trait_pointer { enum { value = false }; }; +template struct trait_pointer { enum { value = true }; }; + +template +struct traits { + enum { + // whether this type is a pointer + is_pointer = trait_pointer::value, + // whether this type's constructor is a no-op + has_trivial_ctor = is_pointer || trait_trivial_ctor::value, + // whether this type's destructor is a no-op + has_trivial_dtor = is_pointer || trait_trivial_dtor::value, + // whether this type type can be copy-constructed with memcpy + has_trivial_copy = is_pointer || trait_trivial_copy::value, + // whether this type can be moved with memmove + has_trivial_move = is_pointer || trait_trivial_move::value + }; +}; + +template +struct aggregate_traits { + enum { + is_pointer = false, + has_trivial_ctor = + traits::has_trivial_ctor && traits::has_trivial_ctor, + has_trivial_dtor = + traits::has_trivial_dtor && traits::has_trivial_dtor, + has_trivial_copy = + traits::has_trivial_copy && traits::has_trivial_copy, + has_trivial_move = + traits::has_trivial_move && traits::has_trivial_move + }; +}; + +#define ANDROID_TRIVIAL_CTOR_TRAIT( T ) \ + template<> struct trait_trivial_ctor< T > { enum { value = true }; }; + +#define ANDROID_TRIVIAL_DTOR_TRAIT( T ) \ + template<> struct trait_trivial_dtor< T > { enum { value = true }; }; + +#define ANDROID_TRIVIAL_COPY_TRAIT( T ) \ + template<> struct trait_trivial_copy< T > { enum { value = true }; }; + +#define ANDROID_TRIVIAL_MOVE_TRAIT( T ) \ + template<> struct trait_trivial_move< T > { enum { value = true }; }; + +#define ANDROID_BASIC_TYPES_TRAITS( T ) \ + ANDROID_TRIVIAL_CTOR_TRAIT( T ) \ + ANDROID_TRIVIAL_DTOR_TRAIT( T ) \ + ANDROID_TRIVIAL_COPY_TRAIT( T ) \ + ANDROID_TRIVIAL_MOVE_TRAIT( T ) + +// --------------------------------------------------------------------------- + +/* + * basic types traits + */ + +ANDROID_BASIC_TYPES_TRAITS( void ) +ANDROID_BASIC_TYPES_TRAITS( bool ) +ANDROID_BASIC_TYPES_TRAITS( char ) +ANDROID_BASIC_TYPES_TRAITS( unsigned char ) +ANDROID_BASIC_TYPES_TRAITS( short ) +ANDROID_BASIC_TYPES_TRAITS( unsigned short ) +ANDROID_BASIC_TYPES_TRAITS( int ) +ANDROID_BASIC_TYPES_TRAITS( unsigned int ) +ANDROID_BASIC_TYPES_TRAITS( long ) +ANDROID_BASIC_TYPES_TRAITS( unsigned long ) +ANDROID_BASIC_TYPES_TRAITS( long long ) +ANDROID_BASIC_TYPES_TRAITS( unsigned long long ) +ANDROID_BASIC_TYPES_TRAITS( float ) +ANDROID_BASIC_TYPES_TRAITS( double ) + +// --------------------------------------------------------------------------- + + +/* + * compare and order types + */ + +template inline +int strictly_order_type(const TYPE& lhs, const TYPE& rhs) { + return (lhs < rhs) ? 1 : 0; +} + +template inline +int compare_type(const TYPE& lhs, const TYPE& rhs) { + return strictly_order_type(rhs, lhs) - strictly_order_type(lhs, rhs); +} + +/* + * create, destroy, copy and move types... + */ + +template inline +void construct_type(TYPE* p, size_t n) { + if (!traits::has_trivial_ctor) { + while (n--) { + new(p++) TYPE; + } + } +} + +template inline +void destroy_type(TYPE* p, size_t n) { + if (!traits::has_trivial_dtor) { + while (n--) { + p->~TYPE(); + p++; + } + } +} + +template inline +void copy_type(TYPE* d, const TYPE* s, size_t n) { + if (!traits::has_trivial_copy) { + while (n--) { + new(d) TYPE(*s); + d++, s++; + } + } else { + memcpy(d,s,n*sizeof(TYPE)); + } +} + +template inline +void splat_type(TYPE* where, const TYPE* what, size_t n) { + if (!traits::has_trivial_copy) { + while (n--) { + new(where) TYPE(*what); + where++; + } + } else { + while (n--) { + *where++ = *what; + } + } +} + +template inline +void move_forward_type(TYPE* d, const TYPE* s, size_t n = 1) { + if ((traits::has_trivial_dtor && traits::has_trivial_copy) + || traits::has_trivial_move) + { + memmove(d,s,n*sizeof(TYPE)); + } else { + d += n; + s += n; + while (n--) { + --d, --s; + if (!traits::has_trivial_copy) { + new(d) TYPE(*s); + } else { + *d = *s; + } + if (!traits::has_trivial_dtor) { + s->~TYPE(); + } + } + } +} + +template inline +void move_backward_type(TYPE* d, const TYPE* s, size_t n = 1) { + if ((traits::has_trivial_dtor && traits::has_trivial_copy) + || traits::has_trivial_move) + { + memmove(d,s,n*sizeof(TYPE)); + } else { + while (n--) { + if (!traits::has_trivial_copy) { + new(d) TYPE(*s); + } else { + *d = *s; + } + if (!traits::has_trivial_dtor) { + s->~TYPE(); + } + d++, s++; + } + } +} + +// --------------------------------------------------------------------------- + +/* + * a key/value pair + */ + +template +struct key_value_pair_t { + typedef KEY key_t; + typedef VALUE value_t; + + KEY key; + VALUE value; + key_value_pair_t() { } + key_value_pair_t(const key_value_pair_t& o) : key(o.key), value(o.value) { } + key_value_pair_t(const KEY& k, const VALUE& v) : key(k), value(v) { } + key_value_pair_t(const KEY& k) : key(k) { } + inline bool operator < (const key_value_pair_t& o) const { + return strictly_order_type(key, o.key); + } + inline const KEY& getKey() const { + return key; + } + inline const VALUE& getValue() const { + return value; + } +}; + +template +struct trait_trivial_ctor< key_value_pair_t > +{ enum { value = aggregate_traits::has_trivial_ctor }; }; +template +struct trait_trivial_dtor< key_value_pair_t > +{ enum { value = aggregate_traits::has_trivial_dtor }; }; +template +struct trait_trivial_copy< key_value_pair_t > +{ enum { value = aggregate_traits::has_trivial_copy }; }; +template +struct trait_trivial_move< key_value_pair_t > +{ enum { value = aggregate_traits::has_trivial_move }; }; + +// --------------------------------------------------------------------------- + +/* + * Hash codes. + */ +typedef uint32_t hash_t; + +template +hash_t hash_type(const TKey& key); + +/* Built-in hash code specializations. + * Assumes pointers are 32bit. */ +#define ANDROID_INT32_HASH(T) \ + template <> inline hash_t hash_type(const T& value) { return hash_t(value); } +#define ANDROID_INT64_HASH(T) \ + template <> inline hash_t hash_type(const T& value) { \ + return hash_t((value >> 32) ^ value); } +#define ANDROID_REINTERPRET_HASH(T, R) \ + template <> inline hash_t hash_type(const T& value) { \ + return hash_type(*reinterpret_cast(&value)); } + +ANDROID_INT32_HASH(bool) +ANDROID_INT32_HASH(int8_t) +ANDROID_INT32_HASH(uint8_t) +ANDROID_INT32_HASH(int16_t) +ANDROID_INT32_HASH(uint16_t) +ANDROID_INT32_HASH(int32_t) +ANDROID_INT32_HASH(uint32_t) +ANDROID_INT64_HASH(int64_t) +ANDROID_INT64_HASH(uint64_t) +ANDROID_REINTERPRET_HASH(float, uint32_t) +ANDROID_REINTERPRET_HASH(double, uint64_t) + +template inline hash_t hash_type(T* const & value) { + return hash_type(uintptr_t(value)); +} + +}; // namespace android + +// --------------------------------------------------------------------------- + +#endif // ANDROID_TYPE_HELPERS_H diff --git a/phonelibs/android_system_core/include/utils/Unicode.h b/phonelibs/android_system_core/include/utils/Unicode.h new file mode 100644 index 0000000000..4e17cc3d9c --- /dev/null +++ b/phonelibs/android_system_core/include/utils/Unicode.h @@ -0,0 +1,172 @@ +/* + * 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_UNICODE_H +#define ANDROID_UNICODE_H + +#include +#include + +extern "C" { + +// Standard string functions on char16_t strings. +int strcmp16(const char16_t *, const char16_t *); +int strncmp16(const char16_t *s1, const char16_t *s2, size_t n); +size_t strlen16(const char16_t *); +size_t strnlen16(const char16_t *, size_t); +char16_t *strcpy16(char16_t *, const char16_t *); +char16_t *strncpy16(char16_t *, const char16_t *, size_t); + +// Version of comparison that supports embedded nulls. +// This is different than strncmp() because we don't stop +// at a nul character and consider the strings to be different +// if the lengths are different (thus we need to supply the +// lengths of both strings). This can also be used when +// your string is not nul-terminated as it will have the +// equivalent result as strcmp16 (unlike strncmp16). +int strzcmp16(const char16_t *s1, size_t n1, const char16_t *s2, size_t n2); + +// Version of strzcmp16 for comparing strings in different endianness. +int strzcmp16_h_n(const char16_t *s1H, size_t n1, const char16_t *s2N, size_t n2); + +// Standard string functions on char32_t strings. +size_t strlen32(const char32_t *); +size_t strnlen32(const char32_t *, size_t); + +/** + * Measure the length of a UTF-32 string in UTF-8. If the string is invalid + * such as containing a surrogate character, -1 will be returned. + */ +ssize_t utf32_to_utf8_length(const char32_t *src, size_t src_len); + +/** + * Stores a UTF-8 string converted from "src" in "dst", if "dst_length" is not + * large enough to store the string, the part of the "src" string is stored + * into "dst" as much as possible. See the examples for more detail. + * Returns the size actually used for storing the string. + * dst" is not null-terminated when dst_len is fully used (like strncpy). + * + * Example 1 + * "src" == \u3042\u3044 (\xE3\x81\x82\xE3\x81\x84) + * "src_len" == 2 + * "dst_len" >= 7 + * -> + * Returned value == 6 + * "dst" becomes \xE3\x81\x82\xE3\x81\x84\0 + * (note that "dst" is null-terminated) + * + * Example 2 + * "src" == \u3042\u3044 (\xE3\x81\x82\xE3\x81\x84) + * "src_len" == 2 + * "dst_len" == 5 + * -> + * Returned value == 3 + * "dst" becomes \xE3\x81\x82\0 + * (note that "dst" is null-terminated, but \u3044 is not stored in "dst" + * since "dst" does not have enough size to store the character) + * + * Example 3 + * "src" == \u3042\u3044 (\xE3\x81\x82\xE3\x81\x84) + * "src_len" == 2 + * "dst_len" == 6 + * -> + * Returned value == 6 + * "dst" becomes \xE3\x81\x82\xE3\x81\x84 + * (note that "dst" is NOT null-terminated, like strncpy) + */ +void utf32_to_utf8(const char32_t* src, size_t src_len, char* dst, size_t dst_len); + +/** + * Returns the unicode value at "index". + * Returns -1 when the index is invalid (equals to or more than "src_len"). + * If returned value is positive, it is able to be converted to char32_t, which + * is unsigned. Then, if "next_index" is not NULL, the next index to be used is + * stored in "next_index". "next_index" can be NULL. + */ +int32_t utf32_from_utf8_at(const char *src, size_t src_len, size_t index, size_t *next_index); + + +/** + * Returns the UTF-8 length of UTF-16 string "src". + */ +ssize_t utf16_to_utf8_length(const char16_t *src, size_t src_len); + +/** + * Converts a UTF-16 string to UTF-8. The destination buffer must be large + * enough to fit the UTF-16 as measured by utf16_to_utf8_length with an added + * NULL terminator. + */ +void utf16_to_utf8(const char16_t* src, size_t src_len, char* dst, size_t dst_len); + +/** + * Returns the length of "src" when "src" is valid UTF-8 string. + * Returns 0 if src is NULL or 0-length string. Returns -1 when the source + * is an invalid string. + * + * This function should be used to determine whether "src" is valid UTF-8 + * characters with valid unicode codepoints. "src" must be null-terminated. + * + * If you are going to use other utf8_to_... functions defined in this header + * with string which may not be valid UTF-8 with valid codepoint (form 0 to + * 0x10FFFF), you should use this function before calling others, since the + * other functions do not check whether the string is valid UTF-8 or not. + * + * If you do not care whether "src" is valid UTF-8 or not, you should use + * strlen() as usual, which should be much faster. + */ +ssize_t utf8_length(const char *src); + +/** + * Measure the length of a UTF-32 string. + */ +size_t utf8_to_utf32_length(const char *src, size_t src_len); + +/** + * Stores a UTF-32 string converted from "src" in "dst". "dst" must be large + * enough to store the entire converted string as measured by + * utf8_to_utf32_length plus space for a NULL terminator. + */ +void utf8_to_utf32(const char* src, size_t src_len, char32_t* dst); + +/** + * Returns the UTF-16 length of UTF-8 string "src". + */ +ssize_t utf8_to_utf16_length(const uint8_t* src, size_t srcLen); + +/** + * Convert UTF-8 to UTF-16 including surrogate pairs. + * Returns a pointer to the end of the string (where a null terminator might go + * if you wanted to add one). + */ +char16_t* utf8_to_utf16_no_null_terminator(const uint8_t* src, size_t srcLen, char16_t* dst); + +/** + * Convert UTF-8 to UTF-16 including surrogate pairs. The destination buffer + * must be large enough to hold the result as measured by utf8_to_utf16_length + * plus an added NULL terminator. + */ +void utf8_to_utf16(const uint8_t* src, size_t srcLen, char16_t* dst); + +/** + * Like utf8_to_utf16_no_null_terminator, but you can supply a maximum length of the + * decoded string. The decoded string will fill up to that length; if it is longer + * the returned pointer will be to the character after dstLen. + */ +char16_t* utf8_to_utf16_n(const uint8_t* src, size_t srcLen, char16_t* dst, size_t dstLen); + +} + +#endif diff --git a/phonelibs/android_system_core/include/utils/Vector.h b/phonelibs/android_system_core/include/utils/Vector.h new file mode 100644 index 0000000000..ed7b725213 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/Vector.h @@ -0,0 +1,423 @@ +/* + * 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_VECTOR_H +#define ANDROID_VECTOR_H + +#include +#include +#include + +#include + +#include +#include + +// --------------------------------------------------------------------------- + +namespace android { + +template +class SortedVector; + +/*! + * The main templated vector class ensuring type safety + * while making use of VectorImpl. + * This is the class users want to use. + */ + +template +class Vector : private VectorImpl +{ +public: + typedef TYPE value_type; + + /*! + * Constructors and destructors + */ + + Vector(); + Vector(const Vector& rhs); + explicit Vector(const SortedVector& rhs); + virtual ~Vector(); + + /*! copy operator */ + const Vector& operator = (const Vector& rhs) const; + Vector& operator = (const Vector& rhs); + + const Vector& operator = (const SortedVector& rhs) const; + Vector& operator = (const SortedVector& rhs); + + /* + * empty the vector + */ + + inline void clear() { VectorImpl::clear(); } + + /*! + * vector stats + */ + + //! returns number of items in the vector + inline size_t size() const { return VectorImpl::size(); } + //! returns whether or not the vector is empty + inline bool isEmpty() const { return VectorImpl::isEmpty(); } + //! returns how many items can be stored without reallocating the backing store + inline size_t capacity() const { return VectorImpl::capacity(); } + //! sets the capacity. capacity can never be reduced less than size() + inline ssize_t setCapacity(size_t size) { return VectorImpl::setCapacity(size); } + + /*! + * set the size of the vector. items are appended with the default + * constructor, or removed from the end as needed. + */ + inline ssize_t resize(size_t size) { return VectorImpl::resize(size); } + + /*! + * C-style array access + */ + + //! read-only C-style access + inline const TYPE* array() const; + //! read-write C-style access + TYPE* editArray(); + + /*! + * accessors + */ + + //! read-only access to an item at a given index + inline const TYPE& operator [] (size_t index) const; + //! alternate name for operator [] + inline const TYPE& itemAt(size_t index) const; + //! stack-usage of the vector. returns the top of the stack (last element) + const TYPE& top() const; + + /*! + * modifying the array + */ + + //! copy-on write support, grants write access to an item + TYPE& editItemAt(size_t index); + //! grants right access to the top of the stack (last element) + TYPE& editTop(); + + /*! + * append/insert another vector + */ + + //! insert another vector at a given index + ssize_t insertVectorAt(const Vector& vector, size_t index); + + //! append another vector at the end of this one + ssize_t appendVector(const Vector& vector); + + + //! insert an array at a given index + ssize_t insertArrayAt(const TYPE* array, size_t index, size_t length); + + //! append an array at the end of this vector + ssize_t appendArray(const TYPE* array, size_t length); + + /*! + * add/insert/replace items + */ + + //! insert one or several items initialized with their default constructor + inline ssize_t insertAt(size_t index, size_t numItems = 1); + //! insert one or several items initialized from a prototype item + ssize_t insertAt(const TYPE& prototype_item, size_t index, size_t numItems = 1); + //! pop the top of the stack (removes the last element). No-op if the stack's empty + inline void pop(); + //! pushes an item initialized with its default constructor + inline void push(); + //! pushes an item on the top of the stack + void push(const TYPE& item); + //! same as push() but returns the index the item was added at (or an error) + inline ssize_t add(); + //! same as push() but returns the index the item was added at (or an error) + ssize_t add(const TYPE& item); + //! replace an item with a new one initialized with its default constructor + inline ssize_t replaceAt(size_t index); + //! replace an item with a new one + ssize_t replaceAt(const TYPE& item, size_t index); + + /*! + * remove items + */ + + //! remove several items + inline ssize_t removeItemsAt(size_t index, size_t count = 1); + //! remove one item + inline ssize_t removeAt(size_t index) { return removeItemsAt(index); } + + /*! + * sort (stable) the array + */ + + typedef int (*compar_t)(const TYPE* lhs, const TYPE* rhs); + typedef int (*compar_r_t)(const TYPE* lhs, const TYPE* rhs, void* state); + + inline status_t sort(compar_t cmp); + inline status_t sort(compar_r_t cmp, void* state); + + // for debugging only + inline size_t getItemSize() const { return itemSize(); } + + + /* + * these inlines add some level of compatibility with STL. eventually + * we should probably turn things around. + */ + typedef TYPE* iterator; + typedef TYPE const* const_iterator; + + inline iterator begin() { return editArray(); } + inline iterator end() { return editArray() + size(); } + inline const_iterator begin() const { return array(); } + inline const_iterator end() const { return array() + size(); } + inline void reserve(size_t n) { setCapacity(n); } + inline bool empty() const{ return isEmpty(); } + inline void push_back(const TYPE& item) { insertAt(item, size(), 1); } + inline void push_front(const TYPE& item) { insertAt(item, 0, 1); } + inline iterator erase(iterator pos) { + ssize_t index = removeItemsAt(pos-array()); + return begin() + index; + } + +protected: + virtual void do_construct(void* storage, size_t num) const; + virtual void do_destroy(void* storage, size_t num) const; + virtual void do_copy(void* dest, const void* from, size_t num) const; + virtual void do_splat(void* dest, const void* item, size_t num) const; + virtual void do_move_forward(void* dest, const void* from, size_t num) const; + virtual void do_move_backward(void* dest, const void* from, size_t num) const; +}; + +// Vector can be trivially moved using memcpy() because moving does not +// require any change to the underlying SharedBuffer contents or reference count. +template struct trait_trivial_move > { enum { value = true }; }; + +// --------------------------------------------------------------------------- +// No user serviceable parts from here... +// --------------------------------------------------------------------------- + +template inline +Vector::Vector() + : VectorImpl(sizeof(TYPE), + ((traits::has_trivial_ctor ? HAS_TRIVIAL_CTOR : 0) + |(traits::has_trivial_dtor ? HAS_TRIVIAL_DTOR : 0) + |(traits::has_trivial_copy ? HAS_TRIVIAL_COPY : 0)) + ) +{ +} + +template inline +Vector::Vector(const Vector& rhs) + : VectorImpl(rhs) { +} + +template inline +Vector::Vector(const SortedVector& rhs) + : VectorImpl(static_cast(rhs)) { +} + +template inline +Vector::~Vector() { + finish_vector(); +} + +template inline +Vector& Vector::operator = (const Vector& rhs) { + VectorImpl::operator = (rhs); + return *this; +} + +template inline +const Vector& Vector::operator = (const Vector& rhs) const { + VectorImpl::operator = (static_cast(rhs)); + return *this; +} + +template inline +Vector& Vector::operator = (const SortedVector& rhs) { + VectorImpl::operator = (static_cast(rhs)); + return *this; +} + +template inline +const Vector& Vector::operator = (const SortedVector& rhs) const { + VectorImpl::operator = (rhs); + return *this; +} + +template inline +const TYPE* Vector::array() const { + return static_cast(arrayImpl()); +} + +template inline +TYPE* Vector::editArray() { + return static_cast(editArrayImpl()); +} + + +template inline +const TYPE& Vector::operator[](size_t index) const { + LOG_FATAL_IF(index>=size(), + "%s: index=%u out of range (%u)", __PRETTY_FUNCTION__, + int(index), int(size())); + return *(array() + index); +} + +template inline +const TYPE& Vector::itemAt(size_t index) const { + return operator[](index); +} + +template inline +const TYPE& Vector::top() const { + return *(array() + size() - 1); +} + +template inline +TYPE& Vector::editItemAt(size_t index) { + return *( static_cast(editItemLocation(index)) ); +} + +template inline +TYPE& Vector::editTop() { + return *( static_cast(editItemLocation(size()-1)) ); +} + +template inline +ssize_t Vector::insertVectorAt(const Vector& vector, size_t index) { + return VectorImpl::insertVectorAt(reinterpret_cast(vector), index); +} + +template inline +ssize_t Vector::appendVector(const Vector& vector) { + return VectorImpl::appendVector(reinterpret_cast(vector)); +} + +template inline +ssize_t Vector::insertArrayAt(const TYPE* array, size_t index, size_t length) { + return VectorImpl::insertArrayAt(array, index, length); +} + +template inline +ssize_t Vector::appendArray(const TYPE* array, size_t length) { + return VectorImpl::appendArray(array, length); +} + +template inline +ssize_t Vector::insertAt(const TYPE& item, size_t index, size_t numItems) { + return VectorImpl::insertAt(&item, index, numItems); +} + +template inline +void Vector::push(const TYPE& item) { + return VectorImpl::push(&item); +} + +template inline +ssize_t Vector::add(const TYPE& item) { + return VectorImpl::add(&item); +} + +template inline +ssize_t Vector::replaceAt(const TYPE& item, size_t index) { + return VectorImpl::replaceAt(&item, index); +} + +template inline +ssize_t Vector::insertAt(size_t index, size_t numItems) { + return VectorImpl::insertAt(index, numItems); +} + +template inline +void Vector::pop() { + VectorImpl::pop(); +} + +template inline +void Vector::push() { + VectorImpl::push(); +} + +template inline +ssize_t Vector::add() { + return VectorImpl::add(); +} + +template inline +ssize_t Vector::replaceAt(size_t index) { + return VectorImpl::replaceAt(index); +} + +template inline +ssize_t Vector::removeItemsAt(size_t index, size_t count) { + return VectorImpl::removeItemsAt(index, count); +} + +template inline +status_t Vector::sort(Vector::compar_t cmp) { + return VectorImpl::sort((VectorImpl::compar_t)cmp); +} + +template inline +status_t Vector::sort(Vector::compar_r_t cmp, void* state) { + return VectorImpl::sort((VectorImpl::compar_r_t)cmp, state); +} + +// --------------------------------------------------------------------------- + +template +void Vector::do_construct(void* storage, size_t num) const { + construct_type( reinterpret_cast(storage), num ); +} + +template +void Vector::do_destroy(void* storage, size_t num) const { + destroy_type( reinterpret_cast(storage), num ); +} + +template +void Vector::do_copy(void* dest, const void* from, size_t num) const { + copy_type( reinterpret_cast(dest), reinterpret_cast(from), num ); +} + +template +void Vector::do_splat(void* dest, const void* item, size_t num) const { + splat_type( reinterpret_cast(dest), reinterpret_cast(item), num ); +} + +template +void Vector::do_move_forward(void* dest, const void* from, size_t num) const { + move_forward_type( reinterpret_cast(dest), reinterpret_cast(from), num ); +} + +template +void Vector::do_move_backward(void* dest, const void* from, size_t num) const { + move_backward_type( reinterpret_cast(dest), reinterpret_cast(from), num ); +} + +}; // namespace android + + +// --------------------------------------------------------------------------- + +#endif // ANDROID_VECTOR_H diff --git a/phonelibs/android_system_core/include/utils/VectorImpl.h b/phonelibs/android_system_core/include/utils/VectorImpl.h new file mode 100644 index 0000000000..21ad71ce60 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/VectorImpl.h @@ -0,0 +1,183 @@ +/* + * 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_VECTOR_IMPL_H +#define ANDROID_VECTOR_IMPL_H + +#include +#include +#include +#include + +// --------------------------------------------------------------------------- +// No user serviceable parts in here... +// --------------------------------------------------------------------------- + +namespace android { + +/*! + * Implementation of the guts of the vector<> class + * this ensures backward binary compatibility and + * reduces code size. + * For performance reasons, we expose mStorage and mCount + * so these fields are set in stone. + * + */ + +class VectorImpl +{ +public: + enum { // flags passed to the ctor + HAS_TRIVIAL_CTOR = 0x00000001, + HAS_TRIVIAL_DTOR = 0x00000002, + HAS_TRIVIAL_COPY = 0x00000004, + }; + + VectorImpl(size_t itemSize, uint32_t flags); + VectorImpl(const VectorImpl& rhs); + virtual ~VectorImpl(); + + /*! must be called from subclasses destructor */ + void finish_vector(); + + VectorImpl& operator = (const VectorImpl& rhs); + + /*! C-style array access */ + inline const void* arrayImpl() const { return mStorage; } + void* editArrayImpl(); + + /*! vector stats */ + inline size_t size() const { return mCount; } + inline bool isEmpty() const { return mCount == 0; } + size_t capacity() const; + ssize_t setCapacity(size_t size); + ssize_t resize(size_t size); + + /*! append/insert another vector or array */ + ssize_t insertVectorAt(const VectorImpl& vector, size_t index); + ssize_t appendVector(const VectorImpl& vector); + ssize_t insertArrayAt(const void* array, size_t index, size_t length); + ssize_t appendArray(const void* array, size_t length); + + /*! add/insert/replace items */ + ssize_t insertAt(size_t where, size_t numItems = 1); + ssize_t insertAt(const void* item, size_t where, size_t numItems = 1); + void pop(); + void push(); + void push(const void* item); + ssize_t add(); + ssize_t add(const void* item); + ssize_t replaceAt(size_t index); + ssize_t replaceAt(const void* item, size_t index); + + /*! remove items */ + ssize_t removeItemsAt(size_t index, size_t count = 1); + void clear(); + + const void* itemLocation(size_t index) const; + void* editItemLocation(size_t index); + + typedef int (*compar_t)(const void* lhs, const void* rhs); + typedef int (*compar_r_t)(const void* lhs, const void* rhs, void* state); + status_t sort(compar_t cmp); + status_t sort(compar_r_t cmp, void* state); + +protected: + size_t itemSize() const; + void release_storage(); + + virtual void do_construct(void* storage, size_t num) const = 0; + virtual void do_destroy(void* storage, size_t num) const = 0; + virtual void do_copy(void* dest, const void* from, size_t num) const = 0; + virtual void do_splat(void* dest, const void* item, size_t num) const = 0; + virtual void do_move_forward(void* dest, const void* from, size_t num) const = 0; + virtual void do_move_backward(void* dest, const void* from, size_t num) const = 0; + +private: + void* _grow(size_t where, size_t amount); + void _shrink(size_t where, size_t amount); + + inline void _do_construct(void* storage, size_t num) const; + inline void _do_destroy(void* storage, size_t num) const; + inline void _do_copy(void* dest, const void* from, size_t num) const; + inline void _do_splat(void* dest, const void* item, size_t num) const; + inline void _do_move_forward(void* dest, const void* from, size_t num) const; + inline void _do_move_backward(void* dest, const void* from, size_t num) const; + + // These 2 fields are exposed in the inlines below, + // so they're set in stone. + void * mStorage; // base address of the vector + size_t mCount; // number of items + + const uint32_t mFlags; + const size_t mItemSize; +}; + + + +class SortedVectorImpl : public VectorImpl +{ +public: + SortedVectorImpl(size_t itemSize, uint32_t flags); + SortedVectorImpl(const VectorImpl& rhs); + virtual ~SortedVectorImpl(); + + SortedVectorImpl& operator = (const SortedVectorImpl& rhs); + + //! finds the index of an item + ssize_t indexOf(const void* item) const; + + //! finds where this item should be inserted + size_t orderOf(const void* item) const; + + //! add an item in the right place (or replaces it if there is one) + ssize_t add(const void* item); + + //! merges a vector into this one + ssize_t merge(const VectorImpl& vector); + ssize_t merge(const SortedVectorImpl& vector); + + //! removes an item + ssize_t remove(const void* item); + +protected: + virtual int do_compare(const void* lhs, const void* rhs) const = 0; + +private: + ssize_t _indexOrderOf(const void* item, size_t* order = 0) const; + + // these are made private, because they can't be used on a SortedVector + // (they don't have an implementation either) + ssize_t add(); + void pop(); + void push(); + void push(const void* item); + ssize_t insertVectorAt(const VectorImpl& vector, size_t index); + ssize_t appendVector(const VectorImpl& vector); + ssize_t insertArrayAt(const void* array, size_t index, size_t length); + ssize_t appendArray(const void* array, size_t length); + ssize_t insertAt(size_t where, size_t numItems = 1); + ssize_t insertAt(const void* item, size_t where, size_t numItems = 1); + ssize_t replaceAt(size_t index); + ssize_t replaceAt(const void* item, size_t index); +}; + +}; // namespace android + + +// --------------------------------------------------------------------------- + +#endif // ANDROID_VECTOR_IMPL_H diff --git a/phonelibs/android_system_core/include/utils/ashmem.h b/phonelibs/android_system_core/include/utils/ashmem.h new file mode 100644 index 0000000000..0854775780 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/ashmem.h @@ -0,0 +1,41 @@ +/* utils/ashmem.h + ** + ** Copyright 2008 The Android Open Source Project + ** + ** This file is dual licensed. It may be redistributed and/or modified + ** under the terms of the Apache 2.0 License OR version 2 of the GNU + ** General Public License. + */ + +#ifndef _UTILS_ASHMEM_H +#define _UTILS_ASHMEM_H + +#include +#include + +#define ASHMEM_NAME_LEN 256 + +#define ASHMEM_NAME_DEF "dev/ashmem" + +/* Return values from ASHMEM_PIN: Was the mapping purged while unpinned? */ +#define ASHMEM_NOT_REAPED 0 +#define ASHMEM_WAS_REAPED 1 + +/* Return values from ASHMEM_UNPIN: Is the mapping now pinned or unpinned? */ +#define ASHMEM_NOW_UNPINNED 0 +#define ASHMEM_NOW_PINNED 1 + +#define __ASHMEMIOC 0x77 + +#define ASHMEM_SET_NAME _IOW(__ASHMEMIOC, 1, char[ASHMEM_NAME_LEN]) +#define ASHMEM_GET_NAME _IOR(__ASHMEMIOC, 2, char[ASHMEM_NAME_LEN]) +#define ASHMEM_SET_SIZE _IOW(__ASHMEMIOC, 3, size_t) +#define ASHMEM_GET_SIZE _IO(__ASHMEMIOC, 4) +#define ASHMEM_SET_PROT_MASK _IOW(__ASHMEMIOC, 5, unsigned long) +#define ASHMEM_GET_PROT_MASK _IO(__ASHMEMIOC, 6) +#define ASHMEM_PIN _IO(__ASHMEMIOC, 7) +#define ASHMEM_UNPIN _IO(__ASHMEMIOC, 8) +#define ASHMEM_ISPINNED _IO(__ASHMEMIOC, 9) +#define ASHMEM_PURGE_ALL_CACHES _IO(__ASHMEMIOC, 10) + +#endif /* _UTILS_ASHMEM_H */ diff --git a/phonelibs/android_system_core/include/utils/misc.h b/phonelibs/android_system_core/include/utils/misc.h new file mode 100644 index 0000000000..6cccec387d --- /dev/null +++ b/phonelibs/android_system_core/include/utils/misc.h @@ -0,0 +1,38 @@ +/* + * 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. + */ + +// +// Handy utility functions and portability code. +// +#ifndef _LIBS_UTILS_MISC_H +#define _LIBS_UTILS_MISC_H + +#include + +/* get #of elements in a static array */ +#ifndef NELEM +# define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0]))) +#endif + +namespace android { + +typedef void (*sysprop_change_callback)(void); +void add_sysprop_change_callback(sysprop_change_callback cb, int priority); +void report_sysprop_change(); + +}; // namespace android + +#endif // _LIBS_UTILS_MISC_H diff --git a/phonelibs/android_system_core/include/utils/threads.h b/phonelibs/android_system_core/include/utils/threads.h new file mode 100644 index 0000000000..9de3382118 --- /dev/null +++ b/phonelibs/android_system_core/include/utils/threads.h @@ -0,0 +1,38 @@ +/* + * 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 _LIBS_UTILS_THREADS_H +#define _LIBS_UTILS_THREADS_H + +/* + * Please, DO NOT USE! + * + * This file is here only for legacy reasons. Instead, include directly + * the headers you need below. + * + */ + +#include + +#ifdef __cplusplus +#include +#include +#include +#include +#include +#endif + +#endif // _LIBS_UTILS_THREADS_H diff --git a/phonelibs/capnp-c/include/capnp_c.h b/phonelibs/capnp-c/include/capnp_c.h deleted file mode 100644 index 9fa2718f7f..0000000000 --- a/phonelibs/capnp-c/include/capnp_c.h +++ /dev/null @@ -1,426 +0,0 @@ -/* vim: set sw=8 ts=8 sts=8 noet: */ -/* capnp_c.h - * - * Copyright (C) 2013 James McKaskill - * Copyright (C) 2014 Steve Dee - * - * This software may be modified and distributed under the terms - * of the MIT license. See the LICENSE file for details. - */ - -#ifndef CAPNP_C_H -#define CAPNP_C_H - -#include -#include -#if defined(unix) && !defined(__APPLE__) -#include -#endif - -// ssize_t is not defined in stdint.h in MSVC. -#ifdef _MSC_VER -typedef intmax_t ssize_t; -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(__cplusplus) || (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) -#define CAPN_INLINE static inline -#else -#define CAPN_INLINE static -#endif - -#define CAPN_VERSION 1 - -/* struct capn is a common structure shared between segments in the same - * session/context so that far pointers between segments will be created. - * - * lookup is used to lookup segments by id when derefencing a far pointer - * - * create is used to create or lookup an alternate segment that has at least - * sz available (ie returned seg->len + sz <= seg->cap) - * - * create_local is used to create a segment for the copy tree and should be - * allocated in the local memory space. - * - * Allocated segments must be zero initialized. - * - * create and lookup can be NULL if you don't need multiple segments and don't - * want to support copying - * - * seglist and copylist are linked lists which can be used to free up segments - * on cleanup, but should not be modified by the user. - * - * lookup, create, create_local, and user can be set by the user. Other values - * should be zero initialized. - */ -struct capn { - /* user settable */ - struct capn_segment *(*lookup)(void* /*user*/, uint32_t /*id */); - struct capn_segment *(*create)(void* /*user*/, uint32_t /*id */, int /*sz*/); - struct capn_segment *(*create_local)(void* /*user*/, int /*sz*/); - void *user; - /* zero initialized, user should not modify */ - uint32_t segnum; - struct capn_tree *copy; - struct capn_tree *segtree; - struct capn_segment *seglist, *lastseg; - struct capn_segment *copylist; -}; - -/* struct capn_tree is a rb tree header used internally for the segment id - * lookup and copy tree */ -struct capn_tree { - struct capn_tree *parent, *link[2]; - unsigned int red : 1; -}; - -struct capn_tree *capn_tree_insert(struct capn_tree *root, struct capn_tree *n); - -/* struct capn_segment contains the information about a single segment. - * - * capn points to a struct capn that is shared between segments in the - * same session - * - * id specifies the segment id, used for far pointers - * - * data specifies the segment data. This should not move after creation. - * - * len specifies the current segment length. This is 0 for a blank - * segment. - * - * cap specifies the segment capacity. - * - * When creating new structures len will be incremented until it reaces cap, - * at which point a new segment will be requested via capn->create. The - * create callback can either create a new segment or expand an existing - * one by incrementing cap and returning the expanded segment. - * - * data, len, and cap must all by 8 byte aligned - * - * data, len, cap, and user should all set by the user. Other values - * should be zero initialized. - */ -#ifdef _MSC_VER -__declspec(align(64)) -#endif -struct capn_segment { - struct capn_tree hdr; - struct capn_segment *next; - struct capn *capn; - uint32_t id; - /* user settable */ - char *data; - size_t len, cap; - void *user; -}; - -enum CAPN_TYPE { - CAPN_NULL = 0, - CAPN_STRUCT = 1, - CAPN_LIST = 2, - CAPN_PTR_LIST = 3, - CAPN_BIT_LIST = 4, - CAPN_FAR_POINTER = 5, -}; - -struct capn_ptr { - unsigned int type : 4; - unsigned int has_ptr_tag : 1; - unsigned int is_list_member : 1; - unsigned int is_composite_list : 1; - unsigned int datasz : 19; - unsigned int ptrs : 16; - int len; - char *data; - struct capn_segment *seg; -}; - -struct capn_text { - int len; - const char *str; - struct capn_segment *seg; -}; - -typedef struct capn_ptr capn_ptr; -typedef struct capn_text capn_text; -typedef struct {capn_ptr p;} capn_data; -typedef struct {capn_ptr p;} capn_list1; -typedef struct {capn_ptr p;} capn_list8; -typedef struct {capn_ptr p;} capn_list16; -typedef struct {capn_ptr p;} capn_list32; -typedef struct {capn_ptr p;} capn_list64; - -struct capn_msg { - struct capn_segment *seg; - uint64_t iface; - uint16_t method; - capn_ptr args; -}; - -/* capn_append_segment appends a segment to a session */ -void capn_append_segment(struct capn*, struct capn_segment*); - -capn_ptr capn_root(struct capn *c); -void capn_resolve(capn_ptr *p); - -#define capn_len(list) ((list).p.type == CAPN_FAR_POINTER ? (capn_resolve(&(list).p), (list).p.len) : (list).p.len) - -/* capn_getp|setp functions get/set ptrs in list/structs - * off is the list index or pointer index in a struct - * capn_setp will copy the data, create far pointers, etc if the target - * is in a different segment/context. - * Both of these will use/return inner pointers for composite lists. - */ -capn_ptr capn_getp(capn_ptr p, int off, int resolve); -int capn_setp(capn_ptr p, int off, capn_ptr tgt); - -capn_text capn_get_text(capn_ptr p, int off, capn_text def); -capn_data capn_get_data(capn_ptr p, int off); -int capn_set_text(capn_ptr p, int off, capn_text tgt); - -/* capn_get* functions get data from a list - * The length of the list is given by p->size - * off specifies how far into the list to start - * sz indicates the number of elements to get - * The function returns the number of elements read or -1 on an error. - * off must be byte aligned for capn_getv1 - */ -int capn_get1(capn_list1 p, int off); -uint8_t capn_get8(capn_list8 p, int off); -uint16_t capn_get16(capn_list16 p, int off); -uint32_t capn_get32(capn_list32 p, int off); -uint64_t capn_get64(capn_list64 p, int off); -int capn_getv1(capn_list1 p, int off, uint8_t *data, int sz); -int capn_getv8(capn_list8 p, int off, uint8_t *data, int sz); -int capn_getv16(capn_list16 p, int off, uint16_t *data, int sz); -int capn_getv32(capn_list32 p, int off, uint32_t *data, int sz); -int capn_getv64(capn_list64 p, int off, uint64_t *data, int sz); - -/* capn_set* functions set data in a list - * off specifies how far into the list to start - * sz indicates the number of elements to write - * The function returns the number of elemnts written or -1 on an error. - * off must be byte aligned for capn_setv1 - */ -int capn_set1(capn_list1 p, int off, int v); -int capn_set8(capn_list8 p, int off, uint8_t v); -int capn_set16(capn_list16 p, int off, uint16_t v); -int capn_set32(capn_list32 p, int off, uint32_t v); -int capn_set64(capn_list64 p, int off, uint64_t v); -int capn_setv1(capn_list1 p, int off, const uint8_t *data, int sz); -int capn_setv8(capn_list8 p, int off, const uint8_t *data, int sz); -int capn_setv16(capn_list16 p, int off, const uint16_t *data, int sz); -int capn_setv32(capn_list32 p, int off, const uint32_t *data, int sz); -int capn_setv64(capn_list64 p, int off, const uint64_t *data, int sz); - -/* capn_new_* functions create a new object - * datasz is in bytes, ptrs is # of pointers, sz is # of elements in the list - * On an error a CAPN_NULL pointer is returned - */ -capn_ptr capn_new_string(struct capn_segment *seg, const char *str, ssize_t sz); -capn_ptr capn_new_struct(struct capn_segment *seg, int datasz, int ptrs); -capn_ptr capn_new_interface(struct capn_segment *seg, int datasz, int ptrs); -capn_ptr capn_new_ptr_list(struct capn_segment *seg, int sz); -capn_ptr capn_new_list(struct capn_segment *seg, int sz, int datasz, int ptrs); -capn_list1 capn_new_list1(struct capn_segment *seg, int sz); -capn_list8 capn_new_list8(struct capn_segment *seg, int sz); -capn_list16 capn_new_list16(struct capn_segment *seg, int sz); -capn_list32 capn_new_list32(struct capn_segment *seg, int sz); -capn_list64 capn_new_list64(struct capn_segment *seg, int sz); - -/* capn_read|write* functions read/write struct values - * off is the offset into the structure in bytes - * Rarely should these be called directly, instead use the generated code. - * Data must be xored with the default value - * These are inlined - */ -CAPN_INLINE uint8_t capn_read8(capn_ptr p, int off); -CAPN_INLINE uint16_t capn_read16(capn_ptr p, int off); -CAPN_INLINE uint32_t capn_read32(capn_ptr p, int off); -CAPN_INLINE uint64_t capn_read64(capn_ptr p, int off); -CAPN_INLINE int capn_write1(capn_ptr p, int off, int val); -CAPN_INLINE int capn_write8(capn_ptr p, int off, uint8_t val); -CAPN_INLINE int capn_write16(capn_ptr p, int off, uint16_t val); -CAPN_INLINE int capn_write32(capn_ptr p, int off, uint32_t val); -CAPN_INLINE int capn_write64(capn_ptr p, int off, uint64_t val); - -/* capn_init_malloc inits the capn struct with a create function which - * allocates segments on the heap using malloc - * - * capn_init_(fp|mem) inits by reading segments in from the file/memory buffer - * in serialized form (optionally packed). It will then setup the create - * function ala capn_init_malloc so that further segments can be created. - * - * capn_free frees all the segment headers and data created by the create - * function setup by capn_init_* - */ -void capn_init_malloc(struct capn *c); -int capn_init_fp(struct capn *c, FILE *f, int packed); -int capn_init_mem(struct capn *c, const uint8_t *p, size_t sz, int packed); - -/* capn_write_(fp|mem) writes segments to the file/memory buffer in - * serialized form and returns the number of bytes written. - */ -/* TODO */ -/*int capn_write_fp(struct capn *c, FILE *f, int packed);*/ -int capn_write_fd(struct capn *c, ssize_t (*write_fd)(int fd, void *p, size_t count), int fd, int packed); -int capn_write_mem(struct capn *c, uint8_t *p, size_t sz, int packed); - -void capn_free(struct capn *c); -void capn_reset_copy(struct capn *c); - -/* Inline functions */ - - -CAPN_INLINE uint8_t capn_flip8(uint8_t v) { - return v; -} -CAPN_INLINE uint16_t capn_flip16(uint16_t v) { -#if defined(__BYTE_ORDER) && (__BYTE_ORDER == __LITTLE_ENDIAN) - return v; -#elif defined(__BYTE_ORDER) && (__BYTE_ORDER == __BIG_ENDIAN) && \ - defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 8 - return __builtin_bswap16(v); -#else - union { uint16_t u; uint8_t v[2]; } s; - s.v[0] = (uint8_t)v; - s.v[1] = (uint8_t)(v>>8); - return s.u; -#endif -} -CAPN_INLINE uint32_t capn_flip32(uint32_t v) { -#if defined(__BYTE_ORDER) && (__BYTE_ORDER == __LITTLE_ENDIAN) - return v; -#elif defined(__BYTE_ORDER) && (__BYTE_ORDER == __BIG_ENDIAN) && \ - defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 8 - return __builtin_bswap32(v); -#else - union { uint32_t u; uint8_t v[4]; } s; - s.v[0] = (uint8_t)v; - s.v[1] = (uint8_t)(v>>8); - s.v[2] = (uint8_t)(v>>16); - s.v[3] = (uint8_t)(v>>24); - return s.u; -#endif -} -CAPN_INLINE uint64_t capn_flip64(uint64_t v) { -#if defined(__BYTE_ORDER) && (__BYTE_ORDER == __LITTLE_ENDIAN) - return v; -#elif defined(__BYTE_ORDER) && (__BYTE_ORDER == __BIG_ENDIAN) && \ - defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 8 - return __builtin_bswap64(v); -#else - union { uint64_t u; uint8_t v[8]; } s; - s.v[0] = (uint8_t)v; - s.v[1] = (uint8_t)(v>>8); - s.v[2] = (uint8_t)(v>>16); - s.v[3] = (uint8_t)(v>>24); - s.v[4] = (uint8_t)(v>>32); - s.v[5] = (uint8_t)(v>>40); - s.v[6] = (uint8_t)(v>>48); - s.v[7] = (uint8_t)(v>>56); - return s.u; -#endif -} - -CAPN_INLINE int capn_write1(capn_ptr p, int off, int val) { - if (off >= p.datasz*8) { - return -1; - } else if (val) { - uint8_t tmp = (uint8_t)(1 << (off & 7)); - ((uint8_t*) p.data)[off >> 3] |= tmp; - return 0; - } else { - uint8_t tmp = (uint8_t)(~(1 << (off & 7))); - ((uint8_t*) p.data)[off >> 3] &= tmp; - return 0; - } -} - -CAPN_INLINE uint8_t capn_read8(capn_ptr p, int off) { - return off+1 <= p.datasz ? capn_flip8(*(uint8_t*) (p.data+off)) : 0; -} -CAPN_INLINE int capn_write8(capn_ptr p, int off, uint8_t val) { - if (off+1 <= p.datasz) { - *(uint8_t*) (p.data+off) = capn_flip8(val); - return 0; - } else { - return -1; - } -} - -CAPN_INLINE uint16_t capn_read16(capn_ptr p, int off) { - return off+2 <= p.datasz ? capn_flip16(*(uint16_t*) (p.data+off)) : 0; -} -CAPN_INLINE int capn_write16(capn_ptr p, int off, uint16_t val) { - if (off+2 <= p.datasz) { - *(uint16_t*) (p.data+off) = capn_flip16(val); - return 0; - } else { - return -1; - } -} - -CAPN_INLINE uint32_t capn_read32(capn_ptr p, int off) { - return off+4 <= p.datasz ? capn_flip32(*(uint32_t*) (p.data+off)) : 0; -} -CAPN_INLINE int capn_write32(capn_ptr p, int off, uint32_t val) { - if (off+4 <= p.datasz) { - *(uint32_t*) (p.data+off) = capn_flip32(val); - return 0; - } else { - return -1; - } -} - -CAPN_INLINE uint64_t capn_read64(capn_ptr p, int off) { - return off+8 <= p.datasz ? capn_flip64(*(uint64_t*) (p.data+off)) : 0; -} -CAPN_INLINE int capn_write64(capn_ptr p, int off, uint64_t val) { - if (off+8 <= p.datasz) { - *(uint64_t*) (p.data+off) = capn_flip64(val); - return 0; - } else { - return -1; - } -} - -union capn_conv_f32 { - uint32_t u; - float f; -}; - -union capn_conv_f64 { - uint64_t u; - double f; -}; - -CAPN_INLINE float capn_to_f32(uint32_t v) { - union capn_conv_f32 u; - u.u = v; - return u.f; -} -CAPN_INLINE double capn_to_f64(uint64_t v) { - union capn_conv_f64 u; - u.u = v; - return u.f; -} -CAPN_INLINE uint32_t capn_from_f32(float v) { - union capn_conv_f32 u; - u.f = v; - return u.u; -} -CAPN_INLINE uint64_t capn_from_f64(double v) { - union capn_conv_f64 u; - u.f = v; - return u.u; -} - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/capnp-cpp/aarch64/bin/capnp b/phonelibs/capnp-cpp/aarch64/bin/capnp deleted file mode 100755 index e60fe7fe3c..0000000000 Binary files a/phonelibs/capnp-cpp/aarch64/bin/capnp and /dev/null differ diff --git a/phonelibs/capnp-cpp/aarch64/bin/capnpc b/phonelibs/capnp-cpp/aarch64/bin/capnpc deleted file mode 120000 index 5668473f09..0000000000 --- a/phonelibs/capnp-cpp/aarch64/bin/capnpc +++ /dev/null @@ -1 +0,0 @@ -capnp \ No newline at end of file diff --git a/phonelibs/capnp-cpp/aarch64/bin/capnpc-c++ b/phonelibs/capnp-cpp/aarch64/bin/capnpc-c++ deleted file mode 100755 index d309091144..0000000000 Binary files a/phonelibs/capnp-cpp/aarch64/bin/capnpc-c++ and /dev/null differ diff --git a/phonelibs/capnp-cpp/aarch64/bin/capnpc-capnp b/phonelibs/capnp-cpp/aarch64/bin/capnpc-capnp deleted file mode 100755 index b1c7a9a9b8..0000000000 Binary files a/phonelibs/capnp-cpp/aarch64/bin/capnpc-capnp and /dev/null differ diff --git a/phonelibs/capnp-cpp/aarch64/lib/libcapnp.a b/phonelibs/capnp-cpp/aarch64/lib/libcapnp.a deleted file mode 100644 index a997023caa..0000000000 Binary files a/phonelibs/capnp-cpp/aarch64/lib/libcapnp.a and /dev/null differ diff --git a/phonelibs/capnp-cpp/aarch64/lib/libcapnpc.a b/phonelibs/capnp-cpp/aarch64/lib/libcapnpc.a deleted file mode 100644 index 2ede39fb91..0000000000 Binary files a/phonelibs/capnp-cpp/aarch64/lib/libcapnpc.a and /dev/null differ diff --git a/phonelibs/capnp-cpp/aarch64/lib/libkj.a b/phonelibs/capnp-cpp/aarch64/lib/libkj.a deleted file mode 100644 index 58cf096637..0000000000 Binary files a/phonelibs/capnp-cpp/aarch64/lib/libkj.a and /dev/null differ diff --git a/phonelibs/capnp-cpp/include/capnp/any.h b/phonelibs/capnp-cpp/include/capnp/any.h deleted file mode 100644 index 6df9dc8dc2..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/any.h +++ /dev/null @@ -1,1073 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_ANY_H_ -#define CAPNP_ANY_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include "layout.h" -#include "pointer-helpers.h" -#include "orphan.h" -#include "list.h" - -namespace capnp { - -class StructSchema; -class ListSchema; -class InterfaceSchema; -class Orphanage; -class ClientHook; -class PipelineHook; -struct PipelineOp; -struct AnyPointer; - -struct AnyList { - AnyList() = delete; - - class Reader; - class Builder; -}; - -struct AnyStruct { - AnyStruct() = delete; - - class Reader; - class Builder; - class Pipeline; -}; - -template<> -struct List { - List() = delete; - - class Reader; - class Builder; -}; - -namespace _ { // private -template <> struct Kind_ { static constexpr Kind kind = Kind::OTHER; }; -template <> struct Kind_ { static constexpr Kind kind = Kind::OTHER; }; -template <> struct Kind_ { static constexpr Kind kind = Kind::OTHER; }; -} // namespace _ (private) - -// ======================================================================================= -// AnyPointer! - -enum class Equality { - NOT_EQUAL, - EQUAL, - UNKNOWN_CONTAINS_CAPS -}; - -kj::StringPtr KJ_STRINGIFY(Equality res); - -struct AnyPointer { - // Reader/Builder for the `AnyPointer` field type, i.e. a pointer that can point to an arbitrary - // object. - - AnyPointer() = delete; - - class Reader { - public: - typedef AnyPointer Reads; - - Reader() = default; - inline Reader(_::PointerReader reader): reader(reader) {} - - inline MessageSize targetSize() const; - // Get the total size of the target object and all its children. - - inline PointerType getPointerType() const; - - inline bool isNull() const { return getPointerType() == PointerType::NULL_; } - inline bool isStruct() const { return getPointerType() == PointerType::STRUCT; } - inline bool isList() const { return getPointerType() == PointerType::LIST; } - inline bool isCapability() const { return getPointerType() == PointerType::CAPABILITY; } - - Equality equals(AnyPointer::Reader right); - bool operator==(AnyPointer::Reader right); - inline bool operator!=(AnyPointer::Reader right) { - return !(*this == right); - } - - template - inline ReaderFor getAs() const; - // Valid for T = any generated struct type, interface type, List, Text, or Data. - - template - inline ReaderFor getAs(StructSchema schema) const; - // Only valid for T = DynamicStruct. Requires `#include `. - - template - inline ReaderFor getAs(ListSchema schema) const; - // Only valid for T = DynamicList. Requires `#include `. - - template - inline ReaderFor getAs(InterfaceSchema schema) const; - // Only valid for T = DynamicCapability. Requires `#include `. - -#if !CAPNP_LITE - kj::Own getPipelinedCap(kj::ArrayPtr ops) const; - // Used by RPC system to implement pipelining. Applications generally shouldn't use this - // directly. -#endif // !CAPNP_LITE - - private: - _::PointerReader reader; - friend struct AnyPointer; - friend class Orphanage; - friend class CapReaderContext; - friend struct _::PointerHelpers; - }; - - class Builder { - public: - typedef AnyPointer Builds; - - Builder() = delete; - inline Builder(decltype(nullptr)) {} - inline Builder(_::PointerBuilder builder): builder(builder) {} - - inline MessageSize targetSize() const; - // Get the total size of the target object and all its children. - - inline PointerType getPointerType(); - - inline bool isNull() { return getPointerType() == PointerType::NULL_; } - inline bool isStruct() { return getPointerType() == PointerType::STRUCT; } - inline bool isList() { return getPointerType() == PointerType::LIST; } - inline bool isCapability() { return getPointerType() == PointerType::CAPABILITY; } - - inline Equality equals(AnyPointer::Reader right) { - return asReader().equals(right); - } - inline bool operator==(AnyPointer::Reader right) { - return asReader() == right; - } - inline bool operator!=(AnyPointer::Reader right) { - return !(*this == right); - } - - inline void clear(); - // Set to null. - - template - inline BuilderFor getAs(); - // Valid for T = any generated struct type, List, Text, or Data. - - template - inline BuilderFor getAs(StructSchema schema); - // Only valid for T = DynamicStruct. Requires `#include `. - - template - inline BuilderFor getAs(ListSchema schema); - // Only valid for T = DynamicList. Requires `#include `. - - template - inline BuilderFor getAs(InterfaceSchema schema); - // Only valid for T = DynamicCapability. Requires `#include `. - - template - inline BuilderFor initAs(); - // Valid for T = any generated struct type. - - template - inline BuilderFor initAs(uint elementCount); - // Valid for T = List, Text, or Data. - - template - inline BuilderFor initAs(StructSchema schema); - // Only valid for T = DynamicStruct. Requires `#include `. - - template - inline BuilderFor initAs(ListSchema schema, uint elementCount); - // Only valid for T = DynamicList. Requires `#include `. - - inline AnyList::Builder initAsAnyList(ElementSize elementSize, uint elementCount); - // Note: Does not accept INLINE_COMPOSITE for elementSize. - - inline List::Builder initAsListOfAnyStruct( - uint16_t dataWordCount, uint16_t pointerCount, uint elementCount); - - inline AnyStruct::Builder initAsAnyStruct(uint16_t dataWordCount, uint16_t pointerCount); - - template - inline void setAs(ReaderFor value); - // Valid for ReaderType = T::Reader for T = any generated struct type, List, Text, Data, - // DynamicStruct, or DynamicList (the dynamic types require `#include `). - - template - inline void setAs(std::initializer_list>> list); - // Valid for T = List. - - template - inline void setCanonicalAs(ReaderFor value); - - inline void set(Reader value) { builder.copyFrom(value.reader); } - // Set to a copy of another AnyPointer. - - inline void setCanonical(Reader value) { builder.copyFrom(value.reader, true); } - - template - inline void adopt(Orphan&& orphan); - // Valid for T = any generated struct type, List, Text, Data, DynamicList, DynamicStruct, - // or DynamicValue (the dynamic types require `#include `). - - template - inline Orphan disownAs(); - // Valid for T = any generated struct type, List, Text, Data. - - template - inline Orphan disownAs(StructSchema schema); - // Only valid for T = DynamicStruct. Requires `#include `. - - template - inline Orphan disownAs(ListSchema schema); - // Only valid for T = DynamicList. Requires `#include `. - - template - inline Orphan disownAs(InterfaceSchema schema); - // Only valid for T = DynamicCapability. Requires `#include `. - - inline Orphan disown(); - // Disown without a type. - - inline Reader asReader() const { return Reader(builder.asReader()); } - inline operator Reader() const { return Reader(builder.asReader()); } - - private: - _::PointerBuilder builder; - friend class Orphanage; - friend class CapBuilderContext; - friend struct _::PointerHelpers; - }; - -#if !CAPNP_LITE - class Pipeline { - public: - typedef AnyPointer Pipelines; - - inline Pipeline(decltype(nullptr)) {} - inline explicit Pipeline(kj::Own&& hook): hook(kj::mv(hook)) {} - - Pipeline noop(); - // Just make a copy. - - Pipeline getPointerField(uint16_t pointerIndex); - // Deprecated. In the future, we should use .asAnyStruct.getPointerField. - - inline AnyStruct::Pipeline asAnyStruct(); - - kj::Own asCap(); - // Expect that the result is a capability and construct a pipelined version of it now. - - inline kj::Own releasePipelineHook() { return kj::mv(hook); } - // For use by RPC implementations. - - template ) == Kind::INTERFACE>> - inline operator T() { return T(asCap()); } - - private: - kj::Own hook; - kj::Array ops; - - inline Pipeline(kj::Own&& hook, kj::Array&& ops) - : hook(kj::mv(hook)), ops(kj::mv(ops)) {} - - friend class LocalClient; - friend class PipelineHook; - friend class AnyStruct::Pipeline; - }; -#endif // !CAPNP_LITE -}; - -template <> -class Orphan { - // An orphaned object of unknown type. - -public: - Orphan() = default; - KJ_DISALLOW_COPY(Orphan); - Orphan(Orphan&&) = default; - inline Orphan(_::OrphanBuilder&& builder) - : builder(kj::mv(builder)) {} - - Orphan& operator=(Orphan&&) = default; - - template - inline Orphan(Orphan&& other): builder(kj::mv(other.builder)) {} - template - inline Orphan& operator=(Orphan&& other) { builder = kj::mv(other.builder); return *this; } - // Cast from typed orphan. - - // It's not possible to get an AnyPointer::{Reader,Builder} directly since there is no - // underlying pointer (the pointer would normally live in the parent, but this object is - // orphaned). It is possible, however, to request typed readers/builders. - - template - inline BuilderFor getAs(); - template - inline BuilderFor getAs(StructSchema schema); - template - inline BuilderFor getAs(ListSchema schema); - template - inline typename T::Client getAs(InterfaceSchema schema); - template - inline ReaderFor getAsReader() const; - template - inline ReaderFor getAsReader(StructSchema schema) const; - template - inline ReaderFor getAsReader(ListSchema schema) const; - template - inline typename T::Client getAsReader(InterfaceSchema schema) const; - - template - inline Orphan releaseAs(); - template - inline Orphan releaseAs(StructSchema schema); - template - inline Orphan releaseAs(ListSchema schema); - template - inline Orphan releaseAs(InterfaceSchema schema); - // Down-cast the orphan to a specific type. - - inline bool operator==(decltype(nullptr)) const { return builder == nullptr; } - inline bool operator!=(decltype(nullptr)) const { return builder != nullptr; } - -private: - _::OrphanBuilder builder; - - template - friend struct _::PointerHelpers; - friend class Orphanage; - template - friend class Orphan; - friend class AnyPointer::Builder; -}; - -template struct AnyTypeFor_; -template <> struct AnyTypeFor_ { typedef AnyStruct Type; }; -template <> struct AnyTypeFor_ { typedef AnyList Type; }; - -template -using AnyTypeFor = typename AnyTypeFor_::Type; - -template -inline ReaderFor>> toAny(T&& value) { - return ReaderFor>>( - _::PointerHelpers>::getInternalReader(value)); -} -template -inline BuilderFor>> toAny(T&& value) { - return BuilderFor>>( - _::PointerHelpers>::getInternalBuilder(kj::mv(value))); -} - -template <> -struct List { - // Note: This cannot be used for a list of structs, since such lists are not encoded as pointer - // lists! Use List. - - List() = delete; - - class Reader { - public: - typedef List Reads; - - inline Reader(): reader(ElementSize::POINTER) {} - inline explicit Reader(_::ListReader reader): reader(reader) {} - - inline uint size() const { return unbound(reader.size() / ELEMENTS); } - inline AnyPointer::Reader operator[](uint index) const { - KJ_IREQUIRE(index < size()); - return AnyPointer::Reader(reader.getPointerElement(bounded(index) * ELEMENTS)); - } - - typedef _::IndexingIterator Iterator; - inline Iterator begin() const { return Iterator(this, 0); } - inline Iterator end() const { return Iterator(this, size()); } - - private: - _::ListReader reader; - template - friend struct _::PointerHelpers; - template - friend struct List; - friend class Orphanage; - template - friend struct ToDynamic_; - }; - - class Builder { - public: - typedef List Builds; - - Builder() = delete; - inline Builder(decltype(nullptr)): builder(ElementSize::POINTER) {} - inline explicit Builder(_::ListBuilder builder): builder(builder) {} - - inline operator Reader() const { return Reader(builder.asReader()); } - inline Reader asReader() const { return Reader(builder.asReader()); } - - inline uint size() const { return unbound(builder.size() / ELEMENTS); } - inline AnyPointer::Builder operator[](uint index) { - KJ_IREQUIRE(index < size()); - return AnyPointer::Builder(builder.getPointerElement(bounded(index) * ELEMENTS)); - } - - typedef _::IndexingIterator Iterator; - inline Iterator begin() { return Iterator(this, 0); } - inline Iterator end() { return Iterator(this, size()); } - - private: - _::ListBuilder builder; - template - friend struct _::PointerHelpers; - friend class Orphanage; - template - friend struct ToDynamic_; - }; -}; - -class AnyStruct::Reader { -public: - typedef AnyStruct Reads; - - Reader() = default; - inline Reader(_::StructReader reader): _reader(reader) {} - - template ) == Kind::STRUCT>> - inline Reader(T&& value) - : _reader(_::PointerHelpers>::getInternalReader(kj::fwd(value))) {} - - kj::ArrayPtr getDataSection() { - return _reader.getDataSectionAsBlob(); - } - List::Reader getPointerSection() { - return List::Reader(_reader.getPointerSectionAsList()); - } - - kj::Array canonicalize() { - return _reader.canonicalize(); - } - - Equality equals(AnyStruct::Reader right); - bool operator==(AnyStruct::Reader right); - inline bool operator!=(AnyStruct::Reader right) { - return !(*this == right); - } - - template - ReaderFor as() const { - // T must be a struct type. - return typename T::Reader(_reader); - } -private: - _::StructReader _reader; - - template - friend struct _::PointerHelpers; - friend class Orphanage; -}; - -class AnyStruct::Builder { -public: - typedef AnyStruct Builds; - - inline Builder(decltype(nullptr)) {} - inline Builder(_::StructBuilder builder): _builder(builder) {} - -#if !_MSC_VER // TODO(msvc): MSVC ICEs on this. Try restoring when compiler improves. - template ) == Kind::STRUCT>> - inline Builder(T&& value) - : _builder(_::PointerHelpers>::getInternalBuilder(kj::fwd(value))) {} -#endif - - inline kj::ArrayPtr getDataSection() { - return _builder.getDataSectionAsBlob(); - } - List::Builder getPointerSection() { - return List::Builder(_builder.getPointerSectionAsList()); - } - - inline Equality equals(AnyStruct::Reader right) { - return asReader().equals(right); - } - inline bool operator==(AnyStruct::Reader right) { - return asReader() == right; - } - inline bool operator!=(AnyStruct::Reader right) { - return !(*this == right); - } - - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return Reader(_builder.asReader()); } - - template - BuilderFor as() { - // T must be a struct type. - return typename T::Builder(_builder); - } -private: - _::StructBuilder _builder; - friend class Orphanage; - friend class CapBuilderContext; -}; - -#if !CAPNP_LITE -class AnyStruct::Pipeline { -public: - inline Pipeline(decltype(nullptr)): typeless(nullptr) {} - inline explicit Pipeline(AnyPointer::Pipeline&& typeless) - : typeless(kj::mv(typeless)) {} - - inline AnyPointer::Pipeline getPointerField(uint16_t pointerIndex) { - // Return a new Promise representing a sub-object of the result. `pointerIndex` is the index - // of the sub-object within the pointer section of the result (the result must be a struct). - // - // TODO(perf): On GCC 4.8 / Clang 3.3, use rvalue qualifiers to avoid the need for copies. - // Also make `ops` into a Vector to optimize this. - return typeless.getPointerField(pointerIndex); - } - -private: - AnyPointer::Pipeline typeless; -}; -#endif // !CAPNP_LITE - -class List::Reader { -public: - typedef List Reads; - - inline Reader(): reader(ElementSize::INLINE_COMPOSITE) {} - inline explicit Reader(_::ListReader reader): reader(reader) {} - - inline uint size() const { return unbound(reader.size() / ELEMENTS); } - inline AnyStruct::Reader operator[](uint index) const { - KJ_IREQUIRE(index < size()); - return AnyStruct::Reader(reader.getStructElement(bounded(index) * ELEMENTS)); - } - - typedef _::IndexingIterator Iterator; - inline Iterator begin() const { return Iterator(this, 0); } - inline Iterator end() const { return Iterator(this, size()); } - -private: - _::ListReader reader; - template - friend struct _::PointerHelpers; - template - friend struct List; - friend class Orphanage; - template - friend struct ToDynamic_; -}; - -class List::Builder { -public: - typedef List Builds; - - Builder() = delete; - inline Builder(decltype(nullptr)): builder(ElementSize::INLINE_COMPOSITE) {} - inline explicit Builder(_::ListBuilder builder): builder(builder) {} - - inline operator Reader() const { return Reader(builder.asReader()); } - inline Reader asReader() const { return Reader(builder.asReader()); } - - inline uint size() const { return unbound(builder.size() / ELEMENTS); } - inline AnyStruct::Builder operator[](uint index) { - KJ_IREQUIRE(index < size()); - return AnyStruct::Builder(builder.getStructElement(bounded(index) * ELEMENTS)); - } - - typedef _::IndexingIterator Iterator; - inline Iterator begin() { return Iterator(this, 0); } - inline Iterator end() { return Iterator(this, size()); } - -private: - _::ListBuilder builder; - template - friend struct _::PointerHelpers; - friend class Orphanage; - template - friend struct ToDynamic_; -}; - -class AnyList::Reader { -public: - typedef AnyList Reads; - - inline Reader(): _reader(ElementSize::VOID) {} - inline Reader(_::ListReader reader): _reader(reader) {} - -#if !_MSC_VER // TODO(msvc): MSVC ICEs on this. Try restoring when compiler improves. - template ) == Kind::LIST>> - inline Reader(T&& value) - : _reader(_::PointerHelpers>::getInternalReader(kj::fwd(value))) {} -#endif - - inline ElementSize getElementSize() { return _reader.getElementSize(); } - inline uint size() { return unbound(_reader.size() / ELEMENTS); } - - inline kj::ArrayPtr getRawBytes() { return _reader.asRawBytes(); } - - Equality equals(AnyList::Reader right); - bool operator==(AnyList::Reader right); - inline bool operator!=(AnyList::Reader right) { - return !(*this == right); - } - - template ReaderFor as() { - // T must be List. - return ReaderFor(_reader); - } -private: - _::ListReader _reader; - - template - friend struct _::PointerHelpers; - friend class Orphanage; -}; - -class AnyList::Builder { -public: - typedef AnyList Builds; - - inline Builder(decltype(nullptr)): _builder(ElementSize::VOID) {} - inline Builder(_::ListBuilder builder): _builder(builder) {} - -#if !_MSC_VER // TODO(msvc): MSVC ICEs on this. Try restoring when compiler improves. - template ) == Kind::LIST>> - inline Builder(T&& value) - : _builder(_::PointerHelpers>::getInternalBuilder(kj::fwd(value))) {} -#endif - - inline ElementSize getElementSize() { return _builder.getElementSize(); } - inline uint size() { return unbound(_builder.size() / ELEMENTS); } - - Equality equals(AnyList::Reader right); - inline bool operator==(AnyList::Reader right) { - return asReader() == right; - } - inline bool operator!=(AnyList::Reader right) { - return !(*this == right); - } - - template BuilderFor as() { - // T must be List. - return BuilderFor(_builder); - } - - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return Reader(_builder.asReader()); } - -private: - _::ListBuilder _builder; - - friend class Orphanage; -}; - -// ======================================================================================= -// Pipeline helpers -// -// These relate to capabilities, but we don't declare them in capability.h because generated code -// for structs needs to know about these, even in files that contain no interfaces. - -#if !CAPNP_LITE - -struct PipelineOp { - // Corresponds to rpc.capnp's PromisedAnswer.Op. - - enum Type { - NOOP, // for convenience - - GET_POINTER_FIELD - - // There may be other types in the future... - }; - - Type type; - union { - uint16_t pointerIndex; // for GET_POINTER_FIELD - }; -}; - -class PipelineHook { - // Represents a currently-running call, and implements pipelined requests on its result. - -public: - virtual kj::Own addRef() = 0; - // Increment this object's reference count. - - virtual kj::Own getPipelinedCap(kj::ArrayPtr ops) = 0; - // Extract a promised Capability from the results. - - virtual kj::Own getPipelinedCap(kj::Array&& ops); - // Version of getPipelinedCap() passing the array by move. May avoid a copy in some cases. - // Default implementation just calls the other version. - - template > - static inline kj::Own from(Pipeline&& pipeline); - -private: - template struct FromImpl; -}; - -#endif // !CAPNP_LITE - -// ======================================================================================= -// Inline implementation details - -inline MessageSize AnyPointer::Reader::targetSize() const { - return reader.targetSize().asPublic(); -} - -inline PointerType AnyPointer::Reader::getPointerType() const { - return reader.getPointerType(); -} - -template -inline ReaderFor AnyPointer::Reader::getAs() const { - return _::PointerHelpers::get(reader); -} - -inline MessageSize AnyPointer::Builder::targetSize() const { - return asReader().targetSize(); -} - -inline PointerType AnyPointer::Builder::getPointerType() { - return builder.getPointerType(); -} - -inline void AnyPointer::Builder::clear() { - return builder.clear(); -} - -template -inline BuilderFor AnyPointer::Builder::getAs() { - return _::PointerHelpers::get(builder); -} - -template -inline BuilderFor AnyPointer::Builder::initAs() { - return _::PointerHelpers::init(builder); -} - -template -inline BuilderFor AnyPointer::Builder::initAs(uint elementCount) { - return _::PointerHelpers::init(builder, elementCount); -} - -inline AnyList::Builder AnyPointer::Builder::initAsAnyList( - ElementSize elementSize, uint elementCount) { - return AnyList::Builder(builder.initList(elementSize, bounded(elementCount) * ELEMENTS)); -} - -inline List::Builder AnyPointer::Builder::initAsListOfAnyStruct( - uint16_t dataWordCount, uint16_t pointerCount, uint elementCount) { - return List::Builder(builder.initStructList(bounded(elementCount) * ELEMENTS, - _::StructSize(bounded(dataWordCount) * WORDS, - bounded(pointerCount) * POINTERS))); -} - -inline AnyStruct::Builder AnyPointer::Builder::initAsAnyStruct( - uint16_t dataWordCount, uint16_t pointerCount) { - return AnyStruct::Builder(builder.initStruct( - _::StructSize(bounded(dataWordCount) * WORDS, - bounded(pointerCount) * POINTERS))); -} - -template -inline void AnyPointer::Builder::setAs(ReaderFor value) { - return _::PointerHelpers::set(builder, value); -} - -template -inline void AnyPointer::Builder::setCanonicalAs(ReaderFor value) { - return _::PointerHelpers::setCanonical(builder, value); -} - -template -inline void AnyPointer::Builder::setAs( - std::initializer_list>> list) { - return _::PointerHelpers::set(builder, list); -} - -template -inline void AnyPointer::Builder::adopt(Orphan&& orphan) { - _::PointerHelpers::adopt(builder, kj::mv(orphan)); -} - -template -inline Orphan AnyPointer::Builder::disownAs() { - return _::PointerHelpers::disown(builder); -} - -inline Orphan AnyPointer::Builder::disown() { - return Orphan(builder.disown()); -} - -template <> struct ReaderFor_ { typedef AnyPointer::Reader Type; }; -template <> struct BuilderFor_ { typedef AnyPointer::Builder Type; }; -template <> struct ReaderFor_ { typedef AnyStruct::Reader Type; }; -template <> struct BuilderFor_ { typedef AnyStruct::Builder Type; }; - -template <> -struct Orphanage::GetInnerReader { - static inline _::PointerReader apply(const AnyPointer::Reader& t) { - return t.reader; - } -}; - -template <> -struct Orphanage::GetInnerBuilder { - static inline _::PointerBuilder apply(AnyPointer::Builder& t) { - return t.builder; - } -}; - -template <> -struct Orphanage::GetInnerReader { - static inline _::StructReader apply(const AnyStruct::Reader& t) { - return t._reader; - } -}; - -template <> -struct Orphanage::GetInnerBuilder { - static inline _::StructBuilder apply(AnyStruct::Builder& t) { - return t._builder; - } -}; - -template <> -struct Orphanage::GetInnerReader { - static inline _::ListReader apply(const AnyList::Reader& t) { - return t._reader; - } -}; - -template <> -struct Orphanage::GetInnerBuilder { - static inline _::ListBuilder apply(AnyList::Builder& t) { - return t._builder; - } -}; - -template -inline BuilderFor Orphan::getAs() { - return _::OrphanGetImpl::apply(builder); -} -template -inline ReaderFor Orphan::getAsReader() const { - return _::OrphanGetImpl::applyReader(builder); -} -template -inline Orphan Orphan::releaseAs() { - return Orphan(kj::mv(builder)); -} - -// Using AnyPointer as the template type should work... - -template <> -inline typename AnyPointer::Reader AnyPointer::Reader::getAs() const { - return *this; -} -template <> -inline typename AnyPointer::Builder AnyPointer::Builder::getAs() { - return *this; -} -template <> -inline typename AnyPointer::Builder AnyPointer::Builder::initAs() { - clear(); - return *this; -} -template <> -inline void AnyPointer::Builder::setAs(AnyPointer::Reader value) { - return builder.copyFrom(value.reader); -} -template <> -inline void AnyPointer::Builder::adopt(Orphan&& orphan) { - builder.adopt(kj::mv(orphan.builder)); -} -template <> -inline Orphan AnyPointer::Builder::disownAs() { - return Orphan(builder.disown()); -} -template <> -inline Orphan Orphan::releaseAs() { - return kj::mv(*this); -} - -namespace _ { // private - -// Specialize PointerHelpers for AnyPointer. - -template <> -struct PointerHelpers { - static inline AnyPointer::Reader get(PointerReader reader, - const void* defaultValue = nullptr, - uint defaultBytes = 0) { - return AnyPointer::Reader(reader); - } - static inline AnyPointer::Builder get(PointerBuilder builder, - const void* defaultValue = nullptr, - uint defaultBytes = 0) { - return AnyPointer::Builder(builder); - } - static inline void set(PointerBuilder builder, AnyPointer::Reader value) { - AnyPointer::Builder(builder).set(value); - } - static inline void adopt(PointerBuilder builder, Orphan&& value) { - builder.adopt(kj::mv(value.builder)); - } - static inline Orphan disown(PointerBuilder builder) { - return Orphan(builder.disown()); - } - static inline _::PointerReader getInternalReader(const AnyPointer::Reader& reader) { - return reader.reader; - } - static inline _::PointerBuilder getInternalBuilder(AnyPointer::Builder&& builder) { - return builder.builder; - } -}; - -template <> -struct PointerHelpers { - static inline AnyStruct::Reader get( - PointerReader reader, const word* defaultValue = nullptr) { - return AnyStruct::Reader(reader.getStruct(defaultValue)); - } - static inline AnyStruct::Builder get( - PointerBuilder builder, const word* defaultValue = nullptr) { - // TODO(someday): Allow specifying the size somehow? - return AnyStruct::Builder(builder.getStruct( - _::StructSize(ZERO * WORDS, ZERO * POINTERS), defaultValue)); - } - static inline void set(PointerBuilder builder, AnyStruct::Reader value) { - builder.setStruct(value._reader); - } - static inline AnyStruct::Builder init( - PointerBuilder builder, uint16_t dataWordCount, uint16_t pointerCount) { - return AnyStruct::Builder(builder.initStruct( - StructSize(bounded(dataWordCount) * WORDS, - bounded(pointerCount) * POINTERS))); - } - - static void adopt(PointerBuilder builder, Orphan&& value) { - builder.adopt(kj::mv(value.builder)); - } - static Orphan disown(PointerBuilder builder) { - return Orphan(builder.disown()); - } -}; - -template <> -struct PointerHelpers { - static inline AnyList::Reader get( - PointerReader reader, const word* defaultValue = nullptr) { - return AnyList::Reader(reader.getListAnySize(defaultValue)); - } - static inline AnyList::Builder get( - PointerBuilder builder, const word* defaultValue = nullptr) { - return AnyList::Builder(builder.getListAnySize(defaultValue)); - } - static inline void set(PointerBuilder builder, AnyList::Reader value) { - builder.setList(value._reader); - } - static inline AnyList::Builder init( - PointerBuilder builder, ElementSize elementSize, uint elementCount) { - return AnyList::Builder(builder.initList( - elementSize, bounded(elementCount) * ELEMENTS)); - } - static inline AnyList::Builder init( - PointerBuilder builder, uint16_t dataWordCount, uint16_t pointerCount, uint elementCount) { - return AnyList::Builder(builder.initStructList( - bounded(elementCount) * ELEMENTS, - StructSize(bounded(dataWordCount) * WORDS, - bounded(pointerCount) * POINTERS))); - } - - static void adopt(PointerBuilder builder, Orphan&& value) { - builder.adopt(kj::mv(value.builder)); - } - static Orphan disown(PointerBuilder builder) { - return Orphan(builder.disown()); - } -}; - -template <> -struct OrphanGetImpl { - static inline AnyStruct::Builder apply(_::OrphanBuilder& builder) { - return AnyStruct::Builder(builder.asStruct(_::StructSize(ZERO * WORDS, ZERO * POINTERS))); - } - static inline AnyStruct::Reader applyReader(const _::OrphanBuilder& builder) { - return AnyStruct::Reader(builder.asStructReader(_::StructSize(ZERO * WORDS, ZERO * POINTERS))); - } - static inline void truncateListOf(_::OrphanBuilder& builder, ElementCount size) { - builder.truncate(size, _::StructSize(ZERO * WORDS, ZERO * POINTERS)); - } -}; - -template <> -struct OrphanGetImpl { - static inline AnyList::Builder apply(_::OrphanBuilder& builder) { - return AnyList::Builder(builder.asListAnySize()); - } - static inline AnyList::Reader applyReader(const _::OrphanBuilder& builder) { - return AnyList::Reader(builder.asListReaderAnySize()); - } - static inline void truncateListOf(_::OrphanBuilder& builder, ElementCount size) { - builder.truncate(size, ElementSize::POINTER); - } -}; - -} // namespace _ (private) - -#if !CAPNP_LITE - -template -struct PipelineHook::FromImpl { - static inline kj::Own apply(typename T::Pipeline&& pipeline) { - return from(kj::mv(pipeline._typeless)); - } -}; - -template <> -struct PipelineHook::FromImpl { - static inline kj::Own apply(AnyPointer::Pipeline&& pipeline) { - return kj::mv(pipeline.hook); - } -}; - -template -inline kj::Own PipelineHook::from(Pipeline&& pipeline) { - return FromImpl::apply(kj::fwd(pipeline)); -} - -#endif // !CAPNP_LITE - -} // namespace capnp - -#endif // CAPNP_ANY_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/blob.h b/phonelibs/capnp-cpp/include/capnp/blob.h deleted file mode 100644 index d11f101a5a..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/blob.h +++ /dev/null @@ -1,220 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_BLOB_H_ -#define CAPNP_BLOB_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include -#include -#include "common.h" -#include - -namespace capnp { - -struct Data { - Data() = delete; - class Reader; - class Builder; - class Pipeline {}; -}; - -struct Text { - Text() = delete; - class Reader; - class Builder; - class Pipeline {}; -}; - -class Data::Reader: public kj::ArrayPtr { - // Points to a blob of bytes. The usual Reader rules apply -- Data::Reader behaves like a simple - // pointer which does not own its target, can be passed by value, etc. - -public: - typedef Data Reads; - - Reader() = default; - inline Reader(decltype(nullptr)): ArrayPtr(nullptr) {} - inline Reader(const byte* value, size_t size): ArrayPtr(value, size) {} - inline Reader(const kj::Array& value): ArrayPtr(value) {} - inline Reader(const ArrayPtr& value): ArrayPtr(value) {} - inline Reader(const kj::Array& value): ArrayPtr(value) {} - inline Reader(const ArrayPtr& value): ArrayPtr(value) {} -}; - -class Text::Reader: public kj::StringPtr { - // Like Data::Reader, but points at NUL-terminated UTF-8 text. The NUL terminator is not counted - // in the size but must be present immediately after the last byte. - // - // Text::Reader's interface contract is that its data MUST be NUL-terminated. The producer of - // the Text::Reader must guarantee this, so that the consumer need not check. The data SHOULD - // also be valid UTF-8, but this is NOT guaranteed -- the consumer must verify if it cares. - -public: - typedef Text Reads; - - Reader() = default; - inline Reader(decltype(nullptr)): StringPtr(nullptr) {} - inline Reader(const char* value): StringPtr(value) {} - inline Reader(const char* value, size_t size): StringPtr(value, size) {} - inline Reader(const kj::String& value): StringPtr(value) {} - inline Reader(const StringPtr& value): StringPtr(value) {} - -#if KJ_COMPILER_SUPPORTS_STL_STRING_INTEROP - template ().c_str())> - inline Reader(const T& t): StringPtr(t) {} - // Allow implicit conversion from any class that has a c_str() method (namely, std::string). - // We use a template trick to detect std::string in order to avoid including the header for - // those who don't want it. -#endif -}; - -class Data::Builder: public kj::ArrayPtr { - // Like Data::Reader except the pointers aren't const. - -public: - typedef Data Builds; - - Builder() = default; - inline Builder(decltype(nullptr)): ArrayPtr(nullptr) {} - inline Builder(byte* value, size_t size): ArrayPtr(value, size) {} - inline Builder(kj::Array& value): ArrayPtr(value) {} - inline Builder(ArrayPtr value): ArrayPtr(value) {} - - inline Data::Reader asReader() const { return Data::Reader(*this); } - inline operator Reader() const { return asReader(); } -}; - -class Text::Builder: public kj::DisallowConstCopy { - // Basically identical to kj::StringPtr, except that the contents are non-const. - -public: - inline Builder(): content(nulstr, 1) {} - inline Builder(decltype(nullptr)): content(nulstr, 1) {} - inline Builder(char* value): content(value, strlen(value) + 1) {} - inline Builder(char* value, size_t size): content(value, size + 1) { - KJ_IREQUIRE(value[size] == '\0', "StringPtr must be NUL-terminated."); - } - - inline Reader asReader() const { return Reader(content.begin(), content.size() - 1); } - inline operator Reader() const { return asReader(); } - - inline operator kj::ArrayPtr(); - inline kj::ArrayPtr asArray(); - inline operator kj::ArrayPtr() const; - inline kj::ArrayPtr asArray() const; - inline kj::ArrayPtr asBytes() { return asArray().asBytes(); } - inline kj::ArrayPtr asBytes() const { return asArray().asBytes(); } - // Result does not include NUL terminator. - - inline operator kj::StringPtr() const; - inline kj::StringPtr asString() const; - - inline const char* cStr() const { return content.begin(); } - // Returns NUL-terminated string. - - inline size_t size() const { return content.size() - 1; } - // Result does not include NUL terminator. - - inline char operator[](size_t index) const { return content[index]; } - inline char& operator[](size_t index) { return content[index]; } - - inline char* begin() { return content.begin(); } - inline char* end() { return content.end() - 1; } - inline const char* begin() const { return content.begin(); } - inline const char* end() const { return content.end() - 1; } - - inline bool operator==(decltype(nullptr)) const { return content.size() <= 1; } - inline bool operator!=(decltype(nullptr)) const { return content.size() > 1; } - - inline bool operator==(Builder other) const { return asString() == other.asString(); } - inline bool operator!=(Builder other) const { return asString() != other.asString(); } - inline bool operator< (Builder other) const { return asString() < other.asString(); } - inline bool operator> (Builder other) const { return asString() > other.asString(); } - inline bool operator<=(Builder other) const { return asString() <= other.asString(); } - inline bool operator>=(Builder other) const { return asString() >= other.asString(); } - - inline kj::StringPtr slice(size_t start) const; - inline kj::ArrayPtr slice(size_t start, size_t end) const; - inline Builder slice(size_t start); - inline kj::ArrayPtr slice(size_t start, size_t end); - // A string slice is only NUL-terminated if it is a suffix, so slice() has a one-parameter - // version that assumes end = size(). - -private: - inline explicit Builder(kj::ArrayPtr content): content(content) {} - - kj::ArrayPtr content; - - static char nulstr[1]; -}; - -inline kj::StringPtr KJ_STRINGIFY(Text::Builder builder) { - return builder.asString(); -} - -inline bool operator==(const char* a, const Text::Builder& b) { return a == b.asString(); } -inline bool operator!=(const char* a, const Text::Builder& b) { return a != b.asString(); } - -inline Text::Builder::operator kj::StringPtr() const { - return kj::StringPtr(content.begin(), content.size() - 1); -} - -inline kj::StringPtr Text::Builder::asString() const { - return kj::StringPtr(content.begin(), content.size() - 1); -} - -inline Text::Builder::operator kj::ArrayPtr() { - return content.slice(0, content.size() - 1); -} - -inline kj::ArrayPtr Text::Builder::asArray() { - return content.slice(0, content.size() - 1); -} - -inline Text::Builder::operator kj::ArrayPtr() const { - return content.slice(0, content.size() - 1); -} - -inline kj::ArrayPtr Text::Builder::asArray() const { - return content.slice(0, content.size() - 1); -} - -inline kj::StringPtr Text::Builder::slice(size_t start) const { - return asReader().slice(start); -} -inline kj::ArrayPtr Text::Builder::slice(size_t start, size_t end) const { - return content.slice(start, end); -} - -inline Text::Builder Text::Builder::slice(size_t start) { - return Text::Builder(content.slice(start, content.size())); -} -inline kj::ArrayPtr Text::Builder::slice(size_t start, size_t end) { - return content.slice(start, end); -} - -} // namespace capnp - -#endif // CAPNP_BLOB_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/c++.capnp b/phonelibs/capnp-cpp/include/capnp/c++.capnp deleted file mode 100644 index 2bda547179..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/c++.capnp +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -# Licensed under the MIT License: -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -@0xbdf87d7bb8304e81; -$namespace("capnp::annotations"); - -annotation namespace(file): Text; -annotation name(field, enumerant, struct, enum, interface, method, param, group, union): Text; diff --git a/phonelibs/capnp-cpp/include/capnp/c++.capnp.h b/phonelibs/capnp-cpp/include/capnp/c++.capnp.h deleted file mode 100644 index 6d9817fbde..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/c++.capnp.h +++ /dev/null @@ -1,33 +0,0 @@ -// Generated by Cap'n Proto compiler, DO NOT EDIT -// source: c++.capnp - -#ifndef CAPNP_INCLUDED_bdf87d7bb8304e81_ -#define CAPNP_INCLUDED_bdf87d7bb8304e81_ - -#include - -#if CAPNP_VERSION != 6001 -#error "Version mismatch between generated code and library headers. You must use the same version of the Cap'n Proto compiler and library." -#endif - - -namespace capnp { -namespace schemas { - -CAPNP_DECLARE_SCHEMA(b9c6f99ebf805f2c); -CAPNP_DECLARE_SCHEMA(f264a779fef191ce); - -} // namespace schemas -} // namespace capnp - -namespace capnp { -namespace annotations { - -// ======================================================================================= - -// ======================================================================================= - -} // namespace -} // namespace - -#endif // CAPNP_INCLUDED_bdf87d7bb8304e81_ diff --git a/phonelibs/capnp-cpp/include/capnp/c.capnp b/phonelibs/capnp-cpp/include/capnp/c.capnp deleted file mode 100644 index 5de7e7363a..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/c.capnp +++ /dev/null @@ -1,37 +0,0 @@ -# Copyright (c) 2016 NetDEF, Inc. and contributors -# Licensed under the MIT License: -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -@0xc0183dd65ffef0f3; - -annotation nameinfix @0x85a8d86d736ba637 (file): Text; -# add an infix (middle insert) for output file names -# -# "make" generally has implicit rules for compiling "foo.c" => "foo". This -# is very annoying with capnp since the rule will be "foo" => "foo.c", leading -# to a loop. $nameinfix (recommended parameter: "-gen") inserts its parameter -# before the ".c", so the filename becomes "foo-gen.c" -# -# ("foo" is really "foo.capnp", so it's foo.capnp-gen.c) - -annotation fieldgetset @0xf72bc690355d66de (file): Void; -# generate getter & setter functions for accessing fields -# -# allows grabbing/putting values without de-/encoding the entire struct. diff --git a/phonelibs/capnp-cpp/include/capnp/capability.h b/phonelibs/capnp-cpp/include/capnp/capability.h deleted file mode 100644 index 56a5e6f6de..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/capability.h +++ /dev/null @@ -1,884 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_CAPABILITY_H_ -#define CAPNP_CAPABILITY_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#if CAPNP_LITE -#error "RPC APIs, including this header, are not available in lite mode." -#endif - -#include -#include -#include "raw-schema.h" -#include "any.h" -#include "pointer-helpers.h" - -namespace capnp { - -template -class Response; - -template -class RemotePromise: public kj::Promise>, public T::Pipeline { - // A Promise which supports pipelined calls. T is typically a struct type. T must declare - // an inner "mix-in" type "Pipeline" which implements pipelining; RemotePromise simply - // multiply-inherits that type along with Promise>. T::Pipeline must be movable, - // but does not need to be copyable (i.e. just like Promise). - // - // The promise is for an owned pointer so that the RPC system can allocate the MessageReader - // itself. - -public: - inline RemotePromise(kj::Promise>&& promise, typename T::Pipeline&& pipeline) - : kj::Promise>(kj::mv(promise)), - T::Pipeline(kj::mv(pipeline)) {} - inline RemotePromise(decltype(nullptr)) - : kj::Promise>(nullptr), - T::Pipeline(nullptr) {} - KJ_DISALLOW_COPY(RemotePromise); - RemotePromise(RemotePromise&& other) = default; - RemotePromise& operator=(RemotePromise&& other) = default; -}; - -class LocalClient; -namespace _ { // private -extern const RawSchema NULL_INTERFACE_SCHEMA; // defined in schema.c++ -class CapabilityServerSetBase; -} // namespace _ (private) - -struct Capability { - // A capability without type-safe methods. Typed capability clients wrap `Client` and typed - // capability servers subclass `Server` to dispatch to the regular, typed methods. - - class Client; - class Server; - - struct _capnpPrivate { - struct IsInterface; - static constexpr uint64_t typeId = 0x3; - static constexpr Kind kind = Kind::INTERFACE; - static constexpr _::RawSchema const* schema = &_::NULL_INTERFACE_SCHEMA; - - static const _::RawBrandedSchema* brand() { - return &_::NULL_INTERFACE_SCHEMA.defaultBrand; - } - }; -}; - -// ======================================================================================= -// Capability clients - -class RequestHook; -class ResponseHook; -class PipelineHook; -class ClientHook; - -template -class Request: public Params::Builder { - // A call that hasn't been sent yet. This class extends a Builder for the call's "Params" - // structure with a method send() that actually sends it. - // - // Given a Cap'n Proto method `foo(a :A, b :B): C`, the generated client interface will have - // a method `Request fooRequest()` (as well as a convenience method - // `RemotePromise foo(A::Reader a, B::Reader b)`). - -public: - inline Request(typename Params::Builder builder, kj::Own&& hook) - : Params::Builder(builder), hook(kj::mv(hook)) {} - inline Request(decltype(nullptr)): Params::Builder(nullptr) {} - - RemotePromise send() KJ_WARN_UNUSED_RESULT; - // Send the call and return a promise for the results. - -private: - kj::Own hook; - - friend class Capability::Client; - friend struct DynamicCapability; - template - friend class CallContext; - friend class RequestHook; -}; - -template -class Response: public Results::Reader { - // A completed call. This class extends a Reader for the call's answer structure. The Response - // is move-only -- once it goes out-of-scope, the underlying message will be freed. - -public: - inline Response(typename Results::Reader reader, kj::Own&& hook) - : Results::Reader(reader), hook(kj::mv(hook)) {} - -private: - kj::Own hook; - - template - friend class Request; - friend class ResponseHook; -}; - -class Capability::Client { - // Base type for capability clients. - -public: - typedef Capability Reads; - typedef Capability Calls; - - Client(decltype(nullptr)); - // If you need to declare a Client before you have anything to assign to it (perhaps because - // the assignment is going to occur in an if/else scope), you can start by initializing it to - // `nullptr`. The resulting client is not meant to be called and throws exceptions from all - // methods. - - template ()>> - Client(kj::Own&& server); - // Make a client capability that wraps the given server capability. The server's methods will - // only be executed in the given EventLoop, regardless of what thread calls the client's methods. - - template ()>> - Client(kj::Promise&& promise); - // Make a client from a promise for a future client. The resulting client queues calls until the - // promise resolves. - - Client(kj::Exception&& exception); - // Make a broken client that throws the given exception from all calls. - - Client(Client& other); - Client& operator=(Client& other); - // Copies by reference counting. Warning: This refcounting is not thread-safe. All copies of - // the client must remain in one thread. - - Client(Client&&) = default; - Client& operator=(Client&&) = default; - // Move constructor avoids reference counting. - - explicit Client(kj::Own&& hook); - // For use by the RPC implementation: Wrap a ClientHook. - - template - typename T::Client castAs(); - // Reinterpret the capability as implementing the given interface. Note that no error will occur - // here if the capability does not actually implement this interface, but later method calls will - // fail. It's up to the application to decide how indicate that additional interfaces are - // supported. - // - // TODO(perf): GCC 4.8 / Clang 3.3: rvalue-qualified version for better performance. - - template - typename T::Client castAs(InterfaceSchema schema); - // Dynamic version. `T` must be `DynamicCapability`, and you must `#include `. - - kj::Promise whenResolved(); - // If the capability is actually only a promise, the returned promise resolves once the - // capability itself has resolved to its final destination (or propagates the exception if - // the capability promise is rejected). This is mainly useful for error-checking in the case - // where no calls are being made. There is no reason to wait for this before making calls; if - // the capability does not resolve, the call results will propagate the error. - - Request typelessRequest( - uint64_t interfaceId, uint16_t methodId, - kj::Maybe sizeHint); - // Make a request without knowing the types of the params or results. You specify the type ID - // and method number manually. - - // TODO(someday): method(s) for Join - -protected: - Client() = default; - - template - Request newCall(uint64_t interfaceId, uint16_t methodId, - kj::Maybe sizeHint); - -private: - kj::Own hook; - - static kj::Own makeLocalClient(kj::Own&& server); - - template - friend struct _::PointerHelpers; - friend struct DynamicCapability; - friend class Orphanage; - friend struct DynamicStruct; - friend struct DynamicList; - template - friend struct List; - friend class _::CapabilityServerSetBase; - friend class ClientHook; -}; - -// ======================================================================================= -// Capability servers - -class CallContextHook; - -template -class CallContext: public kj::DisallowConstCopy { - // Wrapper around CallContextHook with a specific return type. - // - // Methods of this class may only be called from within the server's event loop, not from other - // threads. - // - // The CallContext becomes invalid as soon as the call reports completion. - -public: - explicit CallContext(CallContextHook& hook); - - typename Params::Reader getParams(); - // Get the params payload. - - void releaseParams(); - // Release the params payload. getParams() will throw an exception after this is called. - // Releasing the params may allow the RPC system to free up buffer space to handle other - // requests. Long-running asynchronous methods should try to call this as early as is - // convenient. - - typename Results::Builder getResults(kj::Maybe sizeHint = nullptr); - typename Results::Builder initResults(kj::Maybe sizeHint = nullptr); - void setResults(typename Results::Reader value); - void adoptResults(Orphan&& value); - Orphanage getResultsOrphanage(kj::Maybe sizeHint = nullptr); - // Manipulate the results payload. The "Return" message (part of the RPC protocol) will - // typically be allocated the first time one of these is called. Some RPC systems may - // allocate these messages in a limited space (such as a shared memory segment), therefore the - // application should delay calling these as long as is convenient to do so (but don't delay - // if doing so would require extra copies later). - // - // `sizeHint` indicates a guess at the message size. This will usually be used to decide how - // much space to allocate for the first message segment (don't worry: only space that is actually - // used will be sent on the wire). If omitted, the system decides. The message root pointer - // should not be included in the size. So, if you are simply going to copy some existing message - // directly into the results, just call `.totalSize()` and pass that in. - - template - kj::Promise tailCall(Request&& tailRequest); - // Resolve the call by making a tail call. `tailRequest` is a request that has been filled in - // but not yet sent. The context will send the call, then fill in the results with the result - // of the call. If tailCall() is used, {get,init,set,adopt}Results (above) *must not* be called. - // - // The RPC implementation may be able to optimize a tail call to another machine such that the - // results never actually pass through this machine. Even if no such optimization is possible, - // `tailCall()` may allow pipelined calls to be forwarded optimistically to the new call site. - // - // In general, this should be the last thing a method implementation calls, and the promise - // returned from `tailCall()` should then be returned by the method implementation. - - void allowCancellation(); - // Indicate that it is OK for the RPC system to discard its Promise for this call's result if - // the caller cancels the call, thereby transitively canceling any asynchronous operations the - // call implementation was performing. This is not done by default because it could represent a - // security risk: applications must be carefully written to ensure that they do not end up in - // a bad state if an operation is canceled at an arbitrary point. However, for long-running - // method calls that hold significant resources, prompt cancellation is often useful. - // - // Keep in mind that asynchronous cancellation cannot occur while the method is synchronously - // executing on a local thread. The method must perform an asynchronous operation or call - // `EventLoop::current().evalLater()` to yield control. - // - // Note: You might think that we should offer `onCancel()` and/or `isCanceled()` methods that - // provide notification when the caller cancels the request without forcefully killing off the - // promise chain. Unfortunately, this composes poorly with promise forking: the canceled - // path may be just one branch of a fork of the result promise. The other branches still want - // the call to continue. Promise forking is used within the Cap'n Proto implementation -- in - // particular each pipelined call forks the result promise. So, if a caller made a pipelined - // call and then dropped the original object, the call should not be canceled, but it would be - // excessively complicated for the framework to avoid notififying of cancellation as long as - // pipelined calls still exist. - -private: - CallContextHook* hook; - - friend class Capability::Server; - friend struct DynamicCapability; -}; - -class Capability::Server { - // Objects implementing a Cap'n Proto interface must subclass this. Typically, such objects - // will instead subclass a typed Server interface which will take care of implementing - // dispatchCall(). - -public: - typedef Capability Serves; - - virtual kj::Promise dispatchCall(uint64_t interfaceId, uint16_t methodId, - CallContext context) = 0; - // Call the given method. `params` is the input struct, and should be released as soon as it - // is no longer needed. `context` may be used to allocate the output struct and deal with - // cancellation. - - // TODO(someday): Method which can optionally be overridden to implement Join when the object is - // a proxy. - -protected: - inline Capability::Client thisCap(); - // Get a capability pointing to this object, much like the `this` keyword. - // - // The effect of this method is undefined if: - // - No capability client has been created pointing to this object. (This is always the case in - // the server's constructor.) - // - The capability client pointing at this object has been destroyed. (This is always the case - // in the server's destructor.) - // - Multiple capability clients have been created around the same server (possible if the server - // is refcounted, which is not recommended since the client itself provides refcounting). - - template - CallContext internalGetTypedContext( - CallContext typeless); - kj::Promise internalUnimplemented(const char* actualInterfaceName, - uint64_t requestedTypeId); - kj::Promise internalUnimplemented(const char* interfaceName, - uint64_t typeId, uint16_t methodId); - kj::Promise internalUnimplemented(const char* interfaceName, const char* methodName, - uint64_t typeId, uint16_t methodId); - -private: - ClientHook* thisHook = nullptr; - friend class LocalClient; -}; - -// ======================================================================================= - -class ReaderCapabilityTable: private _::CapTableReader { - // Class which imbues Readers with the ability to read capabilities. - // - // In Cap'n Proto format, the encoding of a capability pointer is simply an integer index into - // an external table. Since these pointers fundamentally point outside the message, a - // MessageReader by default has no idea what they point at, and therefore reading capabilities - // from such a reader will throw exceptions. - // - // In order to be able to read capabilities, you must first attach a capability table, using - // this class. By "imbuing" a Reader, you get a new Reader which will interpret capability - // pointers by treating them as indexes into the ReaderCapabilityTable. - // - // Note that when using Cap'n Proto's RPC system, this is handled automatically. - -public: - explicit ReaderCapabilityTable(kj::Array>> table); - KJ_DISALLOW_COPY(ReaderCapabilityTable); - - template - T imbue(T reader); - // Return a reader equivalent to `reader` except that when reading capability-valued fields, - // the capabilities are looked up in this table. - -private: - kj::Array>> table; - - kj::Maybe> extractCap(uint index) override; -}; - -class BuilderCapabilityTable: private _::CapTableBuilder { - // Class which imbues Builders with the ability to read and write capabilities. - // - // This is much like ReaderCapabilityTable, except for builders. The table starts out empty, - // but capabilities can be added to it over time. - -public: - BuilderCapabilityTable(); - KJ_DISALLOW_COPY(BuilderCapabilityTable); - - inline kj::ArrayPtr>> getTable() { return table; } - - template - T imbue(T builder); - // Return a builder equivalent to `builder` except that when reading capability-valued fields, - // the capabilities are looked up in this table. - -private: - kj::Vector>> table; - - kj::Maybe> extractCap(uint index) override; - uint injectCap(kj::Own&& cap) override; - void dropCap(uint index) override; -}; - -// ======================================================================================= - -namespace _ { // private - -class CapabilityServerSetBase { -public: - Capability::Client addInternal(kj::Own&& server, void* ptr); - kj::Promise getLocalServerInternal(Capability::Client& client); -}; - -} // namespace _ (private) - -template -class CapabilityServerSet: private _::CapabilityServerSetBase { - // Allows a server to recognize its own capabilities when passed back to it, and obtain the - // underlying Server objects associated with them. - // - // All objects in the set must have the same interface type T. The objects may implement various - // interfaces derived from T (and in fact T can be `capnp::Capability` to accept all objects), - // but note that if you compile with RTTI disabled then you will not be able to down-cast through - // virtual inheritance, and all inheritance between server interfaces is virtual. So, with RTTI - // disabled, you will likely need to set T to be the most-derived Cap'n Proto interface type, - // and you server class will need to be directly derived from that, so that you can use - // static_cast (or kj::downcast) to cast to it after calling getLocalServer(). (If you compile - // with RTTI, then you can freely dynamic_cast and ignore this issue!) - -public: - CapabilityServerSet() = default; - KJ_DISALLOW_COPY(CapabilityServerSet); - - typename T::Client add(kj::Own&& server); - // Create a new capability Client for the given Server and also add this server to the set. - - kj::Promise> getLocalServer(typename T::Client& client); - // Given a Client pointing to a server previously passed to add(), return the corresponding - // Server. This returns a promise because if the input client is itself a promise, this must - // wait for it to resolve. Keep in mind that the server will be deleted when all clients are - // gone, so the caller should make sure to keep the client alive (hence why this method only - // accepts an lvalue input). -}; - -// ======================================================================================= -// Hook interfaces which must be implemented by the RPC system. Applications never call these -// directly; the RPC system implements them and the types defined earlier in this file wrap them. - -class RequestHook { - // Hook interface implemented by RPC system representing a request being built. - -public: - virtual RemotePromise send() = 0; - // Send the call and return a promise for the result. - - virtual const void* getBrand() = 0; - // Returns a void* that identifies who made this request. This can be used by an RPC adapter to - // discover when tail call is going to be sent over its own connection and therefore can be - // optimized into a remote tail call. - - template - inline static kj::Own from(Request&& request) { - return kj::mv(request.hook); - } -}; - -class ResponseHook { - // Hook interface implemented by RPC system representing a response. - // - // At present this class has no methods. It exists only for garbage collection -- when the - // ResponseHook is destroyed, the results can be freed. - -public: - virtual ~ResponseHook() noexcept(false); - // Just here to make sure the type is dynamic. - - template - inline static kj::Own from(Response&& response) { - return kj::mv(response.hook); - } -}; - -// class PipelineHook is declared in any.h because it is needed there. - -class ClientHook { -public: - ClientHook(); - - virtual Request newCall( - uint64_t interfaceId, uint16_t methodId, kj::Maybe sizeHint) = 0; - // Start a new call, allowing the client to allocate request/response objects as it sees fit. - // This version is used when calls are made from application code in the local process. - - struct VoidPromiseAndPipeline { - kj::Promise promise; - kj::Own pipeline; - }; - - virtual VoidPromiseAndPipeline call(uint64_t interfaceId, uint16_t methodId, - kj::Own&& context) = 0; - // Call the object, but the caller controls allocation of the request/response objects. If the - // callee insists on allocating these objects itself, it must make a copy. This version is used - // when calls come in over the network via an RPC system. Note that even if the returned - // `Promise` is discarded, the call may continue executing if any pipelined calls are - // waiting for it. - // - // Since the caller of this method chooses the CallContext implementation, it is the caller's - // responsibility to ensure that the returned promise is not canceled unless allowed via - // the context's `allowCancellation()`. - // - // The call must not begin synchronously; the callee must arrange for the call to begin in a - // later turn of the event loop. Otherwise, application code may call back and affect the - // callee's state in an unexpected way. - - virtual kj::Maybe getResolved() = 0; - // If this ClientHook is a promise that has already resolved, returns the inner, resolved version - // of the capability. The caller may permanently replace this client with the resolved one if - // desired. Returns null if the client isn't a promise or hasn't resolved yet -- use - // `whenMoreResolved()` to distinguish between them. - - virtual kj::Maybe>> whenMoreResolved() = 0; - // If this client is a settled reference (not a promise), return nullptr. Otherwise, return a - // promise that eventually resolves to a new client that is closer to being the final, settled - // client (i.e. the value eventually returned by `getResolved()`). Calling this repeatedly - // should eventually produce a settled client. - - kj::Promise whenResolved(); - // Repeatedly calls whenMoreResolved() until it returns nullptr. - - virtual kj::Own addRef() = 0; - // Return a new reference to the same capability. - - virtual const void* getBrand() = 0; - // Returns a void* that identifies who made this client. This can be used by an RPC adapter to - // discover when a capability it needs to marshal is one that it created in the first place, and - // therefore it can transfer the capability without proxying. - - static const uint NULL_CAPABILITY_BRAND; - // Value is irrelevant; used for pointer. - - inline bool isNull() { return getBrand() == &NULL_CAPABILITY_BRAND; } - // Returns true if the capability was created as a result of assigning a Client to null or by - // reading a null pointer out of a Cap'n Proto message. - - virtual void* getLocalServer(_::CapabilityServerSetBase& capServerSet); - // If this is a local capability created through `capServerSet`, return the underlying Server. - // Otherwise, return nullptr. Default implementation (which everyone except LocalClient should - // use) always returns nullptr. - - static kj::Own from(Capability::Client client) { return kj::mv(client.hook); } -}; - -class CallContextHook { - // Hook interface implemented by RPC system to manage a call on the server side. See - // CallContext. - -public: - virtual AnyPointer::Reader getParams() = 0; - virtual void releaseParams() = 0; - virtual AnyPointer::Builder getResults(kj::Maybe sizeHint) = 0; - virtual kj::Promise tailCall(kj::Own&& request) = 0; - virtual void allowCancellation() = 0; - - virtual kj::Promise onTailCall() = 0; - // If `tailCall()` is called, resolves to the PipelineHook from the tail call. An - // implementation of `ClientHook::call()` is allowed to call this at most once. - - virtual ClientHook::VoidPromiseAndPipeline directTailCall(kj::Own&& request) = 0; - // Call this when you would otherwise call onTailCall() immediately followed by tailCall(). - // Implementations of tailCall() should typically call directTailCall() and then fulfill the - // promise fulfiller for onTailCall() with the returned pipeline. - - virtual kj::Own addRef() = 0; -}; - -kj::Own newLocalPromiseClient(kj::Promise>&& promise); -// Returns a ClientHook that queues up calls until `promise` resolves, then forwards them to -// the new client. This hook's `getResolved()` and `whenMoreResolved()` methods will reflect the -// redirection to the eventual replacement client. - -kj::Own newLocalPromisePipeline(kj::Promise>&& promise); -// Returns a PipelineHook that queues up calls until `promise` resolves, then forwards them to -// the new pipeline. - -kj::Own newBrokenCap(kj::StringPtr reason); -kj::Own newBrokenCap(kj::Exception&& reason); -// Helper function that creates a capability which simply throws exceptions when called. - -kj::Own newBrokenPipeline(kj::Exception&& reason); -// Helper function that creates a pipeline which simply throws exceptions when called. - -Request newBrokenRequest( - kj::Exception&& reason, kj::Maybe sizeHint); -// Helper function that creates a Request object that simply throws exceptions when sent. - -// ======================================================================================= -// Extend PointerHelpers for interfaces - -namespace _ { // private - -template -struct PointerHelpers { - static inline typename T::Client get(PointerReader reader) { - return typename T::Client(reader.getCapability()); - } - static inline typename T::Client get(PointerBuilder builder) { - return typename T::Client(builder.getCapability()); - } - static inline void set(PointerBuilder builder, typename T::Client&& value) { - builder.setCapability(kj::mv(value.Capability::Client::hook)); - } - static inline void set(PointerBuilder builder, typename T::Client& value) { - builder.setCapability(value.Capability::Client::hook->addRef()); - } - static inline void adopt(PointerBuilder builder, Orphan&& value) { - builder.adopt(kj::mv(value.builder)); - } - static inline Orphan disown(PointerBuilder builder) { - return Orphan(builder.disown()); - } -}; - -} // namespace _ (private) - -// ======================================================================================= -// Extend List for interfaces - -template -struct List { - List() = delete; - - class Reader { - public: - typedef List Reads; - - Reader() = default; - inline explicit Reader(_::ListReader reader): reader(reader) {} - - inline uint size() const { return unbound(reader.size() / ELEMENTS); } - inline typename T::Client operator[](uint index) const { - KJ_IREQUIRE(index < size()); - return typename T::Client(reader.getPointerElement( - bounded(index) * ELEMENTS).getCapability()); - } - - typedef _::IndexingIterator Iterator; - inline Iterator begin() const { return Iterator(this, 0); } - inline Iterator end() const { return Iterator(this, size()); } - - private: - _::ListReader reader; - template - friend struct _::PointerHelpers; - template - friend struct List; - friend class Orphanage; - template - friend struct ToDynamic_; - }; - - class Builder { - public: - typedef List Builds; - - Builder() = delete; - inline Builder(decltype(nullptr)) {} - inline explicit Builder(_::ListBuilder builder): builder(builder) {} - - inline operator Reader() const { return Reader(builder.asReader()); } - inline Reader asReader() const { return Reader(builder.asReader()); } - - inline uint size() const { return unbound(builder.size() / ELEMENTS); } - inline typename T::Client operator[](uint index) { - KJ_IREQUIRE(index < size()); - return typename T::Client(builder.getPointerElement( - bounded(index) * ELEMENTS).getCapability()); - } - inline void set(uint index, typename T::Client value) { - KJ_IREQUIRE(index < size()); - builder.getPointerElement(bounded(index) * ELEMENTS).setCapability(kj::mv(value.hook)); - } - inline void adopt(uint index, Orphan&& value) { - KJ_IREQUIRE(index < size()); - builder.getPointerElement(bounded(index) * ELEMENTS).adopt(kj::mv(value)); - } - inline Orphan disown(uint index) { - KJ_IREQUIRE(index < size()); - return Orphan(builder.getPointerElement(bounded(index) * ELEMENTS).disown()); - } - - typedef _::IndexingIterator Iterator; - inline Iterator begin() { return Iterator(this, 0); } - inline Iterator end() { return Iterator(this, size()); } - - private: - _::ListBuilder builder; - friend class Orphanage; - template - friend struct ToDynamic_; - }; - -private: - inline static _::ListBuilder initPointer(_::PointerBuilder builder, uint size) { - return builder.initList(ElementSize::POINTER, bounded(size) * ELEMENTS); - } - inline static _::ListBuilder getFromPointer(_::PointerBuilder builder, const word* defaultValue) { - return builder.getList(ElementSize::POINTER, defaultValue); - } - inline static _::ListReader getFromPointer( - const _::PointerReader& reader, const word* defaultValue) { - return reader.getList(ElementSize::POINTER, defaultValue); - } - - template - friend struct List; - template - friend struct _::PointerHelpers; -}; - -// ======================================================================================= -// Inline implementation details - -template -RemotePromise Request::send() { - auto typelessPromise = hook->send(); - hook = nullptr; // prevent reuse - - // Convert the Promise to return the correct response type. - // Explicitly upcast to kj::Promise to make clear that calling .then() doesn't invalidate the - // Pipeline part of the RemotePromise. - auto typedPromise = kj::implicitCast>&>(typelessPromise) - .then([](Response&& response) -> Response { - return Response(response.getAs(), kj::mv(response.hook)); - }); - - // Wrap the typeless pipeline in a typed wrapper. - typename Results::Pipeline typedPipeline( - kj::mv(kj::implicitCast(typelessPromise))); - - return RemotePromise(kj::mv(typedPromise), kj::mv(typedPipeline)); -} - -inline Capability::Client::Client(kj::Own&& hook): hook(kj::mv(hook)) {} -template -inline Capability::Client::Client(kj::Own&& server) - : hook(makeLocalClient(kj::mv(server))) {} -template -inline Capability::Client::Client(kj::Promise&& promise) - : hook(newLocalPromiseClient(promise.then([](T&& t) { return kj::mv(t.hook); }))) {} -inline Capability::Client::Client(Client& other): hook(other.hook->addRef()) {} -inline Capability::Client& Capability::Client::operator=(Client& other) { - hook = other.hook->addRef(); - return *this; -} -template -inline typename T::Client Capability::Client::castAs() { - return typename T::Client(hook->addRef()); -} -inline kj::Promise Capability::Client::whenResolved() { - return hook->whenResolved(); -} -inline Request Capability::Client::typelessRequest( - uint64_t interfaceId, uint16_t methodId, - kj::Maybe sizeHint) { - return newCall(interfaceId, methodId, sizeHint); -} -template -inline Request Capability::Client::newCall( - uint64_t interfaceId, uint16_t methodId, kj::Maybe sizeHint) { - auto typeless = hook->newCall(interfaceId, methodId, sizeHint); - return Request(typeless.template getAs(), kj::mv(typeless.hook)); -} - -template -inline CallContext::CallContext(CallContextHook& hook): hook(&hook) {} -template -inline typename Params::Reader CallContext::getParams() { - return hook->getParams().template getAs(); -} -template -inline void CallContext::releaseParams() { - hook->releaseParams(); -} -template -inline typename Results::Builder CallContext::getResults( - kj::Maybe sizeHint) { - // `template` keyword needed due to: http://llvm.org/bugs/show_bug.cgi?id=17401 - return hook->getResults(sizeHint).template getAs(); -} -template -inline typename Results::Builder CallContext::initResults( - kj::Maybe sizeHint) { - // `template` keyword needed due to: http://llvm.org/bugs/show_bug.cgi?id=17401 - return hook->getResults(sizeHint).template initAs(); -} -template -inline void CallContext::setResults(typename Results::Reader value) { - hook->getResults(value.totalSize()).template setAs(value); -} -template -inline void CallContext::adoptResults(Orphan&& value) { - hook->getResults(nullptr).adopt(kj::mv(value)); -} -template -inline Orphanage CallContext::getResultsOrphanage( - kj::Maybe sizeHint) { - return Orphanage::getForMessageContaining(hook->getResults(sizeHint)); -} -template -template -inline kj::Promise CallContext::tailCall( - Request&& tailRequest) { - return hook->tailCall(kj::mv(tailRequest.hook)); -} -template -inline void CallContext::allowCancellation() { - hook->allowCancellation(); -} - -template -CallContext Capability::Server::internalGetTypedContext( - CallContext typeless) { - return CallContext(*typeless.hook); -} - -Capability::Client Capability::Server::thisCap() { - return Client(thisHook->addRef()); -} - -template -T ReaderCapabilityTable::imbue(T reader) { - return T(_::PointerHelpers>::getInternalReader(reader).imbue(this)); -} - -template -T BuilderCapabilityTable::imbue(T builder) { - return T(_::PointerHelpers>::getInternalBuilder(kj::mv(builder)).imbue(this)); -} - -template -typename T::Client CapabilityServerSet::add(kj::Own&& server) { - void* ptr = reinterpret_cast(server.get()); - // Clang insists that `castAs` is a template-dependent member and therefore we need the - // `template` keyword here, but AFAICT this is wrong: addImpl() is not a template. - return addInternal(kj::mv(server), ptr).template castAs(); -} - -template -kj::Promise> CapabilityServerSet::getLocalServer( - typename T::Client& client) { - return getLocalServerInternal(client) - .then([](void* server) -> kj::Maybe { - if (server == nullptr) { - return nullptr; - } else { - return *reinterpret_cast(server); - } - }); -} - -template -struct Orphanage::GetInnerReader { - static inline kj::Own apply(typename T::Client t) { - return ClientHook::from(kj::mv(t)); - } -}; - -} // namespace capnp - -#endif // CAPNP_CAPABILITY_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/common.h b/phonelibs/capnp-cpp/include/capnp/common.h deleted file mode 100644 index 3fc7a42112..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/common.h +++ /dev/null @@ -1,723 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// This file contains types which are intended to help detect incorrect usage at compile -// time, but should then be optimized down to basic primitives (usually, integers) by the -// compiler. - -#ifndef CAPNP_COMMON_H_ -#define CAPNP_COMMON_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include -#include -#include - -#if CAPNP_DEBUG_TYPES -#include -#endif - -namespace capnp { - -#define CAPNP_VERSION_MAJOR 0 -#define CAPNP_VERSION_MINOR 6 -#define CAPNP_VERSION_MICRO 1 - -#define CAPNP_VERSION \ - (CAPNP_VERSION_MAJOR * 1000000 + CAPNP_VERSION_MINOR * 1000 + CAPNP_VERSION_MICRO) - -#ifndef CAPNP_LITE -#define CAPNP_LITE 0 -#endif - -typedef unsigned int uint; - -struct Void { - // Type used for Void fields. Using C++'s "void" type creates a bunch of issues since it behaves - // differently from other types. - - inline constexpr bool operator==(Void other) const { return true; } - inline constexpr bool operator!=(Void other) const { return false; } -}; - -static constexpr Void VOID = Void(); -// Constant value for `Void`, which is an empty struct. - -inline kj::StringPtr KJ_STRINGIFY(Void) { return "void"; } - -struct Text; -struct Data; - -enum class Kind: uint8_t { - PRIMITIVE, - BLOB, - ENUM, - STRUCT, - UNION, - INTERFACE, - LIST, - - OTHER - // Some other type which is often a type parameter to Cap'n Proto templates, but which needs - // special handling. This includes types like AnyPointer, Dynamic*, etc. -}; - -enum class Style: uint8_t { - PRIMITIVE, - POINTER, // other than struct - STRUCT, - CAPABILITY -}; - -enum class ElementSize: uint8_t { - // Size of a list element. - - VOID = 0, - BIT = 1, - BYTE = 2, - TWO_BYTES = 3, - FOUR_BYTES = 4, - EIGHT_BYTES = 5, - - POINTER = 6, - - INLINE_COMPOSITE = 7 -}; - -enum class PointerType { - // Various wire types a pointer field can take - - NULL_, - // Should be NULL, but that's #defined in stddef.h - - STRUCT, - LIST, - CAPABILITY -}; - -namespace schemas { - -template -struct EnumInfo; - -} // namespace schemas - -namespace _ { // private - -template struct Kind_; - -template <> struct Kind_ { static constexpr Kind kind = Kind::PRIMITIVE; }; -template <> struct Kind_ { static constexpr Kind kind = Kind::PRIMITIVE; }; -template <> struct Kind_ { static constexpr Kind kind = Kind::PRIMITIVE; }; -template <> struct Kind_ { static constexpr Kind kind = Kind::PRIMITIVE; }; -template <> struct Kind_ { static constexpr Kind kind = Kind::PRIMITIVE; }; -template <> struct Kind_ { static constexpr Kind kind = Kind::PRIMITIVE; }; -template <> struct Kind_ { static constexpr Kind kind = Kind::PRIMITIVE; }; -template <> struct Kind_ { static constexpr Kind kind = Kind::PRIMITIVE; }; -template <> struct Kind_ { static constexpr Kind kind = Kind::PRIMITIVE; }; -template <> struct Kind_ { static constexpr Kind kind = Kind::PRIMITIVE; }; -template <> struct Kind_ { static constexpr Kind kind = Kind::PRIMITIVE; }; -template <> struct Kind_ { static constexpr Kind kind = Kind::PRIMITIVE; }; -template <> struct Kind_ { static constexpr Kind kind = Kind::BLOB; }; -template <> struct Kind_ { static constexpr Kind kind = Kind::BLOB; }; - -template struct Kind_> { - static constexpr Kind kind = Kind::STRUCT; -}; -template struct Kind_> { - static constexpr Kind kind = Kind::INTERFACE; -}; -template struct Kind_::IsEnum>> { - static constexpr Kind kind = Kind::ENUM; -}; - -} // namespace _ (private) - -template ::kind> -inline constexpr Kind kind() { - // This overload of kind() matches types which have a Kind_ specialization. - - return k; -} - -#if _MSC_VER - -#define CAPNP_KIND(T) ::capnp::_::Kind_::kind -// Avoid constexpr methods in MSVC (it remains buggy in many situations). - -#else // _MSC_VER - -#define CAPNP_KIND(T) ::capnp::kind() -// Use this macro rather than kind() in any code which must work in MSVC. - -#endif // _MSC_VER, else - -#if !CAPNP_LITE - -template ()> -inline constexpr Style style() { - return k == Kind::PRIMITIVE || k == Kind::ENUM ? Style::PRIMITIVE - : k == Kind::STRUCT ? Style::STRUCT - : k == Kind::INTERFACE ? Style::CAPABILITY : Style::POINTER; -} - -#endif // !CAPNP_LITE - -template -struct List; - -#if _MSC_VER - -template -struct List {}; -// For some reason, without this declaration, MSVC will error out on some uses of List -// claiming that "T" -- as used in the default initializer for the second template param, "k" -- -// is not defined. I do not understand this error, but adding this empty default declaration fixes -// it. - -#endif - -template struct ListElementType_; -template struct ListElementType_> { typedef T Type; }; -template using ListElementType = typename ListElementType_::Type; - -namespace _ { // private -template struct Kind_> { - static constexpr Kind kind = Kind::LIST; -}; -} // namespace _ (private) - -template struct ReaderFor_ { typedef typename T::Reader Type; }; -template struct ReaderFor_ { typedef T Type; }; -template struct ReaderFor_ { typedef T Type; }; -template struct ReaderFor_ { typedef typename T::Client Type; }; -template using ReaderFor = typename ReaderFor_::Type; -// The type returned by List::Reader::operator[]. - -template struct BuilderFor_ { typedef typename T::Builder Type; }; -template struct BuilderFor_ { typedef T Type; }; -template struct BuilderFor_ { typedef T Type; }; -template struct BuilderFor_ { typedef typename T::Client Type; }; -template using BuilderFor = typename BuilderFor_::Type; -// The type returned by List::Builder::operator[]. - -template struct PipelineFor_ { typedef typename T::Pipeline Type;}; -template struct PipelineFor_ { typedef typename T::Client Type; }; -template using PipelineFor = typename PipelineFor_::Type; - -template struct TypeIfEnum_; -template struct TypeIfEnum_ { typedef T Type; }; - -template -using TypeIfEnum = typename TypeIfEnum_>::Type; - -template -using FromReader = typename kj::Decay::Reads; -// FromReader = MyType (for any Cap'n Proto type). - -template -using FromBuilder = typename kj::Decay::Builds; -// FromBuilder = MyType (for any Cap'n Proto type). - -template -using FromPipeline = typename kj::Decay::Pipelines; -// FromBuilder = MyType (for any Cap'n Proto type). - -template -using FromClient = typename kj::Decay::Calls; -// FromReader = MyType (for any Cap'n Proto interface type). - -template -using FromServer = typename kj::Decay::Serves; -// FromBuilder = MyType (for any Cap'n Proto interface type). - -template -struct FromAny_; - -template -struct FromAny_>> { - using Type = FromReader; -}; - -template -struct FromAny_>> { - using Type = FromBuilder; -}; - -template -struct FromAny_>> { - using Type = FromPipeline; -}; - -// Note that T::Client is covered by FromReader - -template -struct FromAny_, kj::VoidSfinae>> { - using Type = FromServer; -}; - -template -struct FromAny_::kind == Kind::PRIMITIVE || _::Kind_::kind == Kind::ENUM>> { - // TODO(msvc): Ideally the EnableIf condition would be `style() == Style::PRIMITIVE`, but MSVC - // cannot yet use style() in this constexpr context. - - using Type = kj::Decay; -}; - -template -using FromAny = typename FromAny_::Type; -// Given any Cap'n Proto value type as an input, return the Cap'n Proto base type. That is: -// -// Foo::Reader -> Foo -// Foo::Builder -> Foo -// Foo::Pipeline -> Foo -// Foo::Client -> Foo -// Own -> Foo -// uint32_t -> uint32_t - -namespace _ { // private - -template -struct PointerHelpers; - -#if _MSC_VER - -template -struct PointerHelpers {}; -// For some reason, without this declaration, MSVC will error out on some uses of PointerHelpers -// claiming that "T" -- as used in the default initializer for the second template param, "k" -- -// is not defined. I do not understand this error, but adding this empty default declaration fixes -// it. - -#endif - -} // namespace _ (private) - -struct MessageSize { - // Size of a message. Every struct type has a method `.totalSize()` that returns this. - uint64_t wordCount; - uint capCount; -}; - -// ======================================================================================= -// Raw memory types and measures - -using kj::byte; - -class word { uint64_t content KJ_UNUSED_MEMBER; KJ_DISALLOW_COPY(word); public: word() = default; }; -// word is an opaque type with size of 64 bits. This type is useful only to make pointer -// arithmetic clearer. Since the contents are private, the only way to access them is to first -// reinterpret_cast to some other pointer type. -// -// Copying is disallowed because you should always use memcpy(). Otherwise, you may run afoul of -// aliasing rules. -// -// A pointer of type word* should always be word-aligned even if won't actually be dereferenced as -// that type. - -static_assert(sizeof(byte) == 1, "uint8_t is not one byte?"); -static_assert(sizeof(word) == 8, "uint64_t is not 8 bytes?"); - -#if CAPNP_DEBUG_TYPES -// Set CAPNP_DEBUG_TYPES to 1 to use kj::Quantity for "count" types. Otherwise, plain integers are -// used. All the code should still operate exactly the same, we just lose compile-time checking. -// Note that this will also change symbol names, so it's important that the library and any clients -// be compiled with the same setting here. -// -// We disable this by default to reduce symbol name size and avoid any possibility of the compiler -// failing to fully-optimize the types, but anyone modifying Cap'n Proto itself should enable this -// during development and testing. - -namespace _ { class BitLabel; class ElementLabel; struct WirePointer; } - -template -using BitCountN = kj::Quantity(), T>, _::BitLabel>; -template -using ByteCountN = kj::Quantity(), T>, byte>; -template -using WordCountN = kj::Quantity(), T>, word>; -template -using ElementCountN = kj::Quantity(), T>, _::ElementLabel>; -template -using WirePointerCountN = kj::Quantity(), T>, _::WirePointer>; - -typedef BitCountN<8, uint8_t> BitCount8; -typedef BitCountN<16, uint16_t> BitCount16; -typedef BitCountN<32, uint32_t> BitCount32; -typedef BitCountN<64, uint64_t> BitCount64; -typedef BitCountN BitCount; - -typedef ByteCountN<8, uint8_t> ByteCount8; -typedef ByteCountN<16, uint16_t> ByteCount16; -typedef ByteCountN<32, uint32_t> ByteCount32; -typedef ByteCountN<64, uint64_t> ByteCount64; -typedef ByteCountN ByteCount; - -typedef WordCountN<8, uint8_t> WordCount8; -typedef WordCountN<16, uint16_t> WordCount16; -typedef WordCountN<32, uint32_t> WordCount32; -typedef WordCountN<64, uint64_t> WordCount64; -typedef WordCountN WordCount; - -typedef ElementCountN<8, uint8_t> ElementCount8; -typedef ElementCountN<16, uint16_t> ElementCount16; -typedef ElementCountN<32, uint32_t> ElementCount32; -typedef ElementCountN<64, uint64_t> ElementCount64; -typedef ElementCountN ElementCount; - -typedef WirePointerCountN<8, uint8_t> WirePointerCount8; -typedef WirePointerCountN<16, uint16_t> WirePointerCount16; -typedef WirePointerCountN<32, uint32_t> WirePointerCount32; -typedef WirePointerCountN<64, uint64_t> WirePointerCount64; -typedef WirePointerCountN WirePointerCount; - -template -using BitsPerElementN = decltype(BitCountN() / ElementCountN()); -template -using BytesPerElementN = decltype(ByteCountN() / ElementCountN()); -template -using WordsPerElementN = decltype(WordCountN() / ElementCountN()); -template -using PointersPerElementN = decltype(WirePointerCountN() / ElementCountN()); - -using kj::bounded; -using kj::unbound; -using kj::unboundAs; -using kj::unboundMax; -using kj::unboundMaxBits; -using kj::assertMax; -using kj::assertMaxBits; -using kj::upgradeBound; -using kj::ThrowOverflow; -using kj::assumeBits; -using kj::assumeMax; -using kj::subtractChecked; -using kj::trySubtract; - -template -inline constexpr U* operator+(U* ptr, kj::Quantity offset) { - return ptr + unbound(offset / kj::unit>()); -} -template -inline constexpr const U* operator+(const U* ptr, kj::Quantity offset) { - return ptr + unbound(offset / kj::unit>()); -} -template -inline constexpr U* operator+=(U*& ptr, kj::Quantity offset) { - return ptr = ptr + unbound(offset / kj::unit>()); -} -template -inline constexpr const U* operator+=(const U*& ptr, kj::Quantity offset) { - return ptr = ptr + unbound(offset / kj::unit>()); -} - -template -inline constexpr U* operator-(U* ptr, kj::Quantity offset) { - return ptr - unbound(offset / kj::unit>()); -} -template -inline constexpr const U* operator-(const U* ptr, kj::Quantity offset) { - return ptr - unbound(offset / kj::unit>()); -} -template -inline constexpr U* operator-=(U*& ptr, kj::Quantity offset) { - return ptr = ptr - unbound(offset / kj::unit>()); -} -template -inline constexpr const U* operator-=(const U*& ptr, kj::Quantity offset) { - return ptr = ptr - unbound(offset / kj::unit>()); -} - -constexpr auto BITS = kj::unit>(); -constexpr auto BYTES = kj::unit>(); -constexpr auto WORDS = kj::unit>(); -constexpr auto ELEMENTS = kj::unit>(); -constexpr auto POINTERS = kj::unit>(); - -constexpr auto ZERO = kj::bounded<0>(); -constexpr auto ONE = kj::bounded<1>(); - -// GCC 4.7 actually gives unused warnings on these constants in opt mode... -constexpr auto BITS_PER_BYTE KJ_UNUSED = bounded<8>() * BITS / BYTES; -constexpr auto BITS_PER_WORD KJ_UNUSED = bounded<64>() * BITS / WORDS; -constexpr auto BYTES_PER_WORD KJ_UNUSED = bounded<8>() * BYTES / WORDS; - -constexpr auto BITS_PER_POINTER KJ_UNUSED = bounded<64>() * BITS / POINTERS; -constexpr auto BYTES_PER_POINTER KJ_UNUSED = bounded<8>() * BYTES / POINTERS; -constexpr auto WORDS_PER_POINTER KJ_UNUSED = ONE * WORDS / POINTERS; - -constexpr auto POINTER_SIZE_IN_WORDS = ONE * POINTERS * WORDS_PER_POINTER; - -constexpr uint SEGMENT_WORD_COUNT_BITS = 29; // Number of words in a segment. -constexpr uint LIST_ELEMENT_COUNT_BITS = 29; // Number of elements in a list. -constexpr uint STRUCT_DATA_WORD_COUNT_BITS = 16; // Number of words in a Struct data section. -constexpr uint STRUCT_POINTER_COUNT_BITS = 16; // Number of pointers in a Struct pointer section. -constexpr uint BLOB_SIZE_BITS = 29; // Number of bytes in a blob. - -typedef WordCountN SegmentWordCount; -typedef ElementCountN ListElementCount; -typedef WordCountN StructDataWordCount; -typedef WirePointerCountN StructPointerCount; -typedef ByteCountN BlobSize; - -constexpr auto MAX_SEGMENT_WORDS = - bounded()>() * WORDS; -constexpr auto MAX_LIST_ELEMENTS = - bounded()>() * ELEMENTS; -constexpr auto MAX_STUCT_DATA_WORDS = - bounded()>() * WORDS; -constexpr auto MAX_STRUCT_POINTER_COUNT = - bounded()>() * POINTERS; - -using StructDataBitCount = decltype(WordCountN() * BITS_PER_WORD); -// Number of bits in a Struct data segment (should come out to BitCountN<22>). - -using StructDataOffset = decltype(StructDataBitCount() * (ONE * ELEMENTS / BITS)); -using StructPointerOffset = StructPointerCount; -// Type of a field offset. - -inline StructDataOffset assumeDataOffset(uint32_t offset) { - return assumeMax(MAX_STUCT_DATA_WORDS * BITS_PER_WORD * (ONE * ELEMENTS / BITS), - bounded(offset) * ELEMENTS); -} - -inline StructPointerOffset assumePointerOffset(uint32_t offset) { - return assumeMax(MAX_STRUCT_POINTER_COUNT, bounded(offset) * POINTERS); -} - -constexpr uint MAX_TEXT_SIZE = kj::maxValueForBits() - 1; -typedef kj::Quantity, byte> TextSize; -// Not including NUL terminator. - -template -inline KJ_CONSTEXPR() decltype(bounded() * BYTES / ELEMENTS) bytesPerElement() { - return bounded() * BYTES / ELEMENTS; -} - -template -inline KJ_CONSTEXPR() decltype(bounded() * BITS / ELEMENTS) bitsPerElement() { - return bounded() * BITS / ELEMENTS; -} - -template -inline constexpr kj::Quantity, T> -intervalLength(const T* a, const T* b, kj::Quantity, T>) { - return kj::assumeMax(b - a) * kj::unit, T>>(); -} - -template -inline constexpr kj::ArrayPtr arrayPtr(const U* ptr, kj::Quantity size) { - return kj::ArrayPtr(ptr, unbound(size / kj::unit>())); -} -template -inline constexpr kj::ArrayPtr arrayPtr(U* ptr, kj::Quantity size) { - return kj::ArrayPtr(ptr, unbound(size / kj::unit>())); -} - -#else - -template -using BitCountN = T; -template -using ByteCountN = T; -template -using WordCountN = T; -template -using ElementCountN = T; -template -using WirePointerCountN = T; - - -// XXX -typedef BitCountN<8, uint8_t> BitCount8; -typedef BitCountN<16, uint16_t> BitCount16; -typedef BitCountN<32, uint32_t> BitCount32; -typedef BitCountN<64, uint64_t> BitCount64; -typedef BitCountN BitCount; - -typedef ByteCountN<8, uint8_t> ByteCount8; -typedef ByteCountN<16, uint16_t> ByteCount16; -typedef ByteCountN<32, uint32_t> ByteCount32; -typedef ByteCountN<64, uint64_t> ByteCount64; -typedef ByteCountN ByteCount; - -typedef WordCountN<8, uint8_t> WordCount8; -typedef WordCountN<16, uint16_t> WordCount16; -typedef WordCountN<32, uint32_t> WordCount32; -typedef WordCountN<64, uint64_t> WordCount64; -typedef WordCountN WordCount; - -typedef ElementCountN<8, uint8_t> ElementCount8; -typedef ElementCountN<16, uint16_t> ElementCount16; -typedef ElementCountN<32, uint32_t> ElementCount32; -typedef ElementCountN<64, uint64_t> ElementCount64; -typedef ElementCountN ElementCount; - -typedef WirePointerCountN<8, uint8_t> WirePointerCount8; -typedef WirePointerCountN<16, uint16_t> WirePointerCount16; -typedef WirePointerCountN<32, uint32_t> WirePointerCount32; -typedef WirePointerCountN<64, uint64_t> WirePointerCount64; -typedef WirePointerCountN WirePointerCount; - -template -using BitsPerElementN = decltype(BitCountN() / ElementCountN()); -template -using BytesPerElementN = decltype(ByteCountN() / ElementCountN()); -template -using WordsPerElementN = decltype(WordCountN() / ElementCountN()); -template -using PointersPerElementN = decltype(WirePointerCountN() / ElementCountN()); - -using kj::ThrowOverflow; -// YYY - -template inline constexpr uint bounded() { return i; } -template inline constexpr T bounded(T i) { return i; } -template inline constexpr T unbound(T i) { return i; } - -template inline constexpr T unboundAs(U i) { return i; } - -template inline constexpr uint unboundMax(T i) { return i; } -template inline constexpr uint unboundMaxBits(T i) { return i; } - -template -inline T assertMax(T value, ErrorFunc&& func) { - if (KJ_UNLIKELY(value > newMax)) func(); - return value; -} - -template -inline T assertMax(uint newMax, T value, ErrorFunc&& func) { - if (KJ_UNLIKELY(value > newMax)) func(); - return value; -} - -template -inline T assertMaxBits(T value, ErrorFunc&& func = ErrorFunc()) { - if (KJ_UNLIKELY(value > kj::maxValueForBits())) func(); - return value; -} - -template -inline T assertMaxBits(uint bits, T value, ErrorFunc&& func = ErrorFunc()) { - if (KJ_UNLIKELY(value > (1ull << bits) - 1)) func(); - return value; -} - -template inline constexpr T upgradeBound(U i) { return i; } - -template inline constexpr T assumeBits(T i) { return i; } -template inline constexpr T assumeMax(T i) { return i; } - -template -inline auto subtractChecked(T a, U b, ErrorFunc&& errorFunc = ErrorFunc()) - -> decltype(a - b) { - if (b > a) errorFunc(); - return a - b; -} - -template -inline auto trySubtract(T a, U b) -> kj::Maybe { - if (b > a) { - return nullptr; - } else { - return a - b; - } -} - -constexpr uint BITS = 1; -constexpr uint BYTES = 1; -constexpr uint WORDS = 1; -constexpr uint ELEMENTS = 1; -constexpr uint POINTERS = 1; - -constexpr uint ZERO = 0; -constexpr uint ONE = 1; - -// GCC 4.7 actually gives unused warnings on these constants in opt mode... -constexpr uint BITS_PER_BYTE KJ_UNUSED = 8; -constexpr uint BITS_PER_WORD KJ_UNUSED = 64; -constexpr uint BYTES_PER_WORD KJ_UNUSED = 8; - -constexpr uint BITS_PER_POINTER KJ_UNUSED = 64; -constexpr uint BYTES_PER_POINTER KJ_UNUSED = 8; -constexpr uint WORDS_PER_POINTER KJ_UNUSED = 1; - -// XXX -constexpr uint POINTER_SIZE_IN_WORDS = ONE * POINTERS * WORDS_PER_POINTER; - -constexpr uint SEGMENT_WORD_COUNT_BITS = 29; // Number of words in a segment. -constexpr uint LIST_ELEMENT_COUNT_BITS = 29; // Number of elements in a list. -constexpr uint STRUCT_DATA_WORD_COUNT_BITS = 16; // Number of words in a Struct data section. -constexpr uint STRUCT_POINTER_COUNT_BITS = 16; // Number of pointers in a Struct pointer section. -constexpr uint BLOB_SIZE_BITS = 29; // Number of bytes in a blob. - -typedef WordCountN SegmentWordCount; -typedef ElementCountN ListElementCount; -typedef WordCountN StructDataWordCount; -typedef WirePointerCountN StructPointerCount; -typedef ByteCountN BlobSize; -// YYY - -constexpr auto MAX_SEGMENT_WORDS = kj::maxValueForBits(); -constexpr auto MAX_LIST_ELEMENTS = kj::maxValueForBits(); -constexpr auto MAX_STUCT_DATA_WORDS = kj::maxValueForBits(); -constexpr auto MAX_STRUCT_POINTER_COUNT = kj::maxValueForBits(); - -typedef uint StructDataBitCount; -typedef uint StructDataOffset; -typedef uint StructPointerOffset; - -inline StructDataOffset assumeDataOffset(uint32_t offset) { return offset; } -inline StructPointerOffset assumePointerOffset(uint32_t offset) { return offset; } - -constexpr uint MAX_TEXT_SIZE = kj::maxValueForBits() - 1; -typedef uint TextSize; - -template -inline KJ_CONSTEXPR() size_t bytesPerElement() { return sizeof(T); } - -template -inline KJ_CONSTEXPR() size_t bitsPerElement() { return sizeof(T) * 8; } - -template -inline constexpr ptrdiff_t intervalLength(const T* a, const T* b, uint) { - return b - a; -} - -template -inline constexpr kj::ArrayPtr arrayPtr(const U* ptr, T size) { - return kj::arrayPtr(ptr, size); -} -template -inline constexpr kj::ArrayPtr arrayPtr(U* ptr, T size) { - return kj::arrayPtr(ptr, size); -} - -#endif - -} // namespace capnp - -#endif // CAPNP_COMMON_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/compat/json.capnp.h b/phonelibs/capnp-cpp/include/capnp/compat/json.capnp.h deleted file mode 100644 index a8877e540b..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/compat/json.capnp.h +++ /dev/null @@ -1,860 +0,0 @@ -// Generated by Cap'n Proto compiler, DO NOT EDIT -// source: json.capnp - -#ifndef CAPNP_INCLUDED_8ef99297a43a5e34_ -#define CAPNP_INCLUDED_8ef99297a43a5e34_ - -#include -#if !CAPNP_LITE -#include -#endif // !CAPNP_LITE - -#if CAPNP_VERSION != 6001 -#error "Version mismatch between generated code and library headers. You must use the same version of the Cap'n Proto compiler and library." -#endif - - -namespace capnp { -namespace schemas { - -CAPNP_DECLARE_SCHEMA(8825ffaa852cda72); -CAPNP_DECLARE_SCHEMA(c27855d853a937cc); -CAPNP_DECLARE_SCHEMA(9bbf84153dd4bb60); - -} // namespace schemas -} // namespace capnp - -namespace capnp { - -struct JsonValue { - JsonValue() = delete; - - class Reader; - class Builder; - class Pipeline; - enum Which: uint16_t { - NULL_, - BOOLEAN, - NUMBER, - STRING, - ARRAY, - OBJECT, - CALL, - }; - struct Field; - struct Call; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(8825ffaa852cda72, 2, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct JsonValue::Field { - Field() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(c27855d853a937cc, 0, 2) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct JsonValue::Call { - Call() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(9bbf84153dd4bb60, 0, 2) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -// ======================================================================================= - -class JsonValue::Reader { -public: - typedef JsonValue Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline Which which() const; - inline bool isNull() const; - inline ::capnp::Void getNull() const; - - inline bool isBoolean() const; - inline bool getBoolean() const; - - inline bool isNumber() const; - inline double getNumber() const; - - inline bool isString() const; - inline bool hasString() const; - inline ::capnp::Text::Reader getString() const; - - inline bool isArray() const; - inline bool hasArray() const; - inline ::capnp::List< ::capnp::JsonValue>::Reader getArray() const; - - inline bool isObject() const; - inline bool hasObject() const; - inline ::capnp::List< ::capnp::JsonValue::Field>::Reader getObject() const; - - inline bool isCall() const; - inline bool hasCall() const; - inline ::capnp::JsonValue::Call::Reader getCall() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class JsonValue::Builder { -public: - typedef JsonValue Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline Which which(); - inline bool isNull(); - inline ::capnp::Void getNull(); - inline void setNull( ::capnp::Void value = ::capnp::VOID); - - inline bool isBoolean(); - inline bool getBoolean(); - inline void setBoolean(bool value); - - inline bool isNumber(); - inline double getNumber(); - inline void setNumber(double value); - - inline bool isString(); - inline bool hasString(); - inline ::capnp::Text::Builder getString(); - inline void setString( ::capnp::Text::Reader value); - inline ::capnp::Text::Builder initString(unsigned int size); - inline void adoptString(::capnp::Orphan< ::capnp::Text>&& value); - inline ::capnp::Orphan< ::capnp::Text> disownString(); - - inline bool isArray(); - inline bool hasArray(); - inline ::capnp::List< ::capnp::JsonValue>::Builder getArray(); - inline void setArray( ::capnp::List< ::capnp::JsonValue>::Reader value); - inline ::capnp::List< ::capnp::JsonValue>::Builder initArray(unsigned int size); - inline void adoptArray(::capnp::Orphan< ::capnp::List< ::capnp::JsonValue>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::JsonValue>> disownArray(); - - inline bool isObject(); - inline bool hasObject(); - inline ::capnp::List< ::capnp::JsonValue::Field>::Builder getObject(); - inline void setObject( ::capnp::List< ::capnp::JsonValue::Field>::Reader value); - inline ::capnp::List< ::capnp::JsonValue::Field>::Builder initObject(unsigned int size); - inline void adoptObject(::capnp::Orphan< ::capnp::List< ::capnp::JsonValue::Field>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::JsonValue::Field>> disownObject(); - - inline bool isCall(); - inline bool hasCall(); - inline ::capnp::JsonValue::Call::Builder getCall(); - inline void setCall( ::capnp::JsonValue::Call::Reader value); - inline ::capnp::JsonValue::Call::Builder initCall(); - inline void adoptCall(::capnp::Orphan< ::capnp::JsonValue::Call>&& value); - inline ::capnp::Orphan< ::capnp::JsonValue::Call> disownCall(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class JsonValue::Pipeline { -public: - typedef JsonValue Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class JsonValue::Field::Reader { -public: - typedef Field Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline bool hasName() const; - inline ::capnp::Text::Reader getName() const; - - inline bool hasValue() const; - inline ::capnp::JsonValue::Reader getValue() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class JsonValue::Field::Builder { -public: - typedef Field Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline bool hasName(); - inline ::capnp::Text::Builder getName(); - inline void setName( ::capnp::Text::Reader value); - inline ::capnp::Text::Builder initName(unsigned int size); - inline void adoptName(::capnp::Orphan< ::capnp::Text>&& value); - inline ::capnp::Orphan< ::capnp::Text> disownName(); - - inline bool hasValue(); - inline ::capnp::JsonValue::Builder getValue(); - inline void setValue( ::capnp::JsonValue::Reader value); - inline ::capnp::JsonValue::Builder initValue(); - inline void adoptValue(::capnp::Orphan< ::capnp::JsonValue>&& value); - inline ::capnp::Orphan< ::capnp::JsonValue> disownValue(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class JsonValue::Field::Pipeline { -public: - typedef Field Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline ::capnp::JsonValue::Pipeline getValue(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class JsonValue::Call::Reader { -public: - typedef Call Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline bool hasFunction() const; - inline ::capnp::Text::Reader getFunction() const; - - inline bool hasParams() const; - inline ::capnp::List< ::capnp::JsonValue>::Reader getParams() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class JsonValue::Call::Builder { -public: - typedef Call Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline bool hasFunction(); - inline ::capnp::Text::Builder getFunction(); - inline void setFunction( ::capnp::Text::Reader value); - inline ::capnp::Text::Builder initFunction(unsigned int size); - inline void adoptFunction(::capnp::Orphan< ::capnp::Text>&& value); - inline ::capnp::Orphan< ::capnp::Text> disownFunction(); - - inline bool hasParams(); - inline ::capnp::List< ::capnp::JsonValue>::Builder getParams(); - inline void setParams( ::capnp::List< ::capnp::JsonValue>::Reader value); - inline ::capnp::List< ::capnp::JsonValue>::Builder initParams(unsigned int size); - inline void adoptParams(::capnp::Orphan< ::capnp::List< ::capnp::JsonValue>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::JsonValue>> disownParams(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class JsonValue::Call::Pipeline { -public: - typedef Call Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -// ======================================================================================= - -inline ::capnp::JsonValue::Which JsonValue::Reader::which() const { - return _reader.getDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline ::capnp::JsonValue::Which JsonValue::Builder::which() { - return _builder.getDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline bool JsonValue::Reader::isNull() const { - return which() == JsonValue::NULL_; -} -inline bool JsonValue::Builder::isNull() { - return which() == JsonValue::NULL_; -} -inline ::capnp::Void JsonValue::Reader::getNull() const { - KJ_IREQUIRE((which() == JsonValue::NULL_), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void JsonValue::Builder::getNull() { - KJ_IREQUIRE((which() == JsonValue::NULL_), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void JsonValue::Builder::setNull( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, JsonValue::NULL_); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool JsonValue::Reader::isBoolean() const { - return which() == JsonValue::BOOLEAN; -} -inline bool JsonValue::Builder::isBoolean() { - return which() == JsonValue::BOOLEAN; -} -inline bool JsonValue::Reader::getBoolean() const { - KJ_IREQUIRE((which() == JsonValue::BOOLEAN), - "Must check which() before get()ing a union member."); - return _reader.getDataField( - ::capnp::bounded<16>() * ::capnp::ELEMENTS); -} - -inline bool JsonValue::Builder::getBoolean() { - KJ_IREQUIRE((which() == JsonValue::BOOLEAN), - "Must check which() before get()ing a union member."); - return _builder.getDataField( - ::capnp::bounded<16>() * ::capnp::ELEMENTS); -} -inline void JsonValue::Builder::setBoolean(bool value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, JsonValue::BOOLEAN); - _builder.setDataField( - ::capnp::bounded<16>() * ::capnp::ELEMENTS, value); -} - -inline bool JsonValue::Reader::isNumber() const { - return which() == JsonValue::NUMBER; -} -inline bool JsonValue::Builder::isNumber() { - return which() == JsonValue::NUMBER; -} -inline double JsonValue::Reader::getNumber() const { - KJ_IREQUIRE((which() == JsonValue::NUMBER), - "Must check which() before get()ing a union member."); - return _reader.getDataField( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline double JsonValue::Builder::getNumber() { - KJ_IREQUIRE((which() == JsonValue::NUMBER), - "Must check which() before get()ing a union member."); - return _builder.getDataField( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void JsonValue::Builder::setNumber(double value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, JsonValue::NUMBER); - _builder.setDataField( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline bool JsonValue::Reader::isString() const { - return which() == JsonValue::STRING; -} -inline bool JsonValue::Builder::isString() { - return which() == JsonValue::STRING; -} -inline bool JsonValue::Reader::hasString() const { - if (which() != JsonValue::STRING) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool JsonValue::Builder::hasString() { - if (which() != JsonValue::STRING) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::Text::Reader JsonValue::Reader::getString() const { - KJ_IREQUIRE((which() == JsonValue::STRING), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::Text::Builder JsonValue::Builder::getString() { - KJ_IREQUIRE((which() == JsonValue::STRING), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void JsonValue::Builder::setString( ::capnp::Text::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, JsonValue::STRING); - ::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::Text::Builder JsonValue::Builder::initString(unsigned int size) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, JsonValue::STRING); - return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void JsonValue::Builder::adoptString( - ::capnp::Orphan< ::capnp::Text>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, JsonValue::STRING); - ::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::Text> JsonValue::Builder::disownString() { - KJ_IREQUIRE((which() == JsonValue::STRING), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool JsonValue::Reader::isArray() const { - return which() == JsonValue::ARRAY; -} -inline bool JsonValue::Builder::isArray() { - return which() == JsonValue::ARRAY; -} -inline bool JsonValue::Reader::hasArray() const { - if (which() != JsonValue::ARRAY) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool JsonValue::Builder::hasArray() { - if (which() != JsonValue::ARRAY) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::JsonValue>::Reader JsonValue::Reader::getArray() const { - KJ_IREQUIRE((which() == JsonValue::ARRAY), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::JsonValue>>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::JsonValue>::Builder JsonValue::Builder::getArray() { - KJ_IREQUIRE((which() == JsonValue::ARRAY), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::JsonValue>>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void JsonValue::Builder::setArray( ::capnp::List< ::capnp::JsonValue>::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, JsonValue::ARRAY); - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::JsonValue>>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::JsonValue>::Builder JsonValue::Builder::initArray(unsigned int size) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, JsonValue::ARRAY); - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::JsonValue>>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void JsonValue::Builder::adoptArray( - ::capnp::Orphan< ::capnp::List< ::capnp::JsonValue>>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, JsonValue::ARRAY); - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::JsonValue>>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::JsonValue>> JsonValue::Builder::disownArray() { - KJ_IREQUIRE((which() == JsonValue::ARRAY), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::JsonValue>>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool JsonValue::Reader::isObject() const { - return which() == JsonValue::OBJECT; -} -inline bool JsonValue::Builder::isObject() { - return which() == JsonValue::OBJECT; -} -inline bool JsonValue::Reader::hasObject() const { - if (which() != JsonValue::OBJECT) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool JsonValue::Builder::hasObject() { - if (which() != JsonValue::OBJECT) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::JsonValue::Field>::Reader JsonValue::Reader::getObject() const { - KJ_IREQUIRE((which() == JsonValue::OBJECT), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::JsonValue::Field>>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::JsonValue::Field>::Builder JsonValue::Builder::getObject() { - KJ_IREQUIRE((which() == JsonValue::OBJECT), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::JsonValue::Field>>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void JsonValue::Builder::setObject( ::capnp::List< ::capnp::JsonValue::Field>::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, JsonValue::OBJECT); - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::JsonValue::Field>>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::JsonValue::Field>::Builder JsonValue::Builder::initObject(unsigned int size) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, JsonValue::OBJECT); - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::JsonValue::Field>>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void JsonValue::Builder::adoptObject( - ::capnp::Orphan< ::capnp::List< ::capnp::JsonValue::Field>>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, JsonValue::OBJECT); - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::JsonValue::Field>>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::JsonValue::Field>> JsonValue::Builder::disownObject() { - KJ_IREQUIRE((which() == JsonValue::OBJECT), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::JsonValue::Field>>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool JsonValue::Reader::isCall() const { - return which() == JsonValue::CALL; -} -inline bool JsonValue::Builder::isCall() { - return which() == JsonValue::CALL; -} -inline bool JsonValue::Reader::hasCall() const { - if (which() != JsonValue::CALL) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool JsonValue::Builder::hasCall() { - if (which() != JsonValue::CALL) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::JsonValue::Call::Reader JsonValue::Reader::getCall() const { - KJ_IREQUIRE((which() == JsonValue::CALL), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::JsonValue::Call>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::JsonValue::Call::Builder JsonValue::Builder::getCall() { - KJ_IREQUIRE((which() == JsonValue::CALL), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::JsonValue::Call>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void JsonValue::Builder::setCall( ::capnp::JsonValue::Call::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, JsonValue::CALL); - ::capnp::_::PointerHelpers< ::capnp::JsonValue::Call>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::JsonValue::Call::Builder JsonValue::Builder::initCall() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, JsonValue::CALL); - return ::capnp::_::PointerHelpers< ::capnp::JsonValue::Call>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void JsonValue::Builder::adoptCall( - ::capnp::Orphan< ::capnp::JsonValue::Call>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, JsonValue::CALL); - ::capnp::_::PointerHelpers< ::capnp::JsonValue::Call>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::JsonValue::Call> JsonValue::Builder::disownCall() { - KJ_IREQUIRE((which() == JsonValue::CALL), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::JsonValue::Call>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool JsonValue::Field::Reader::hasName() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool JsonValue::Field::Builder::hasName() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::Text::Reader JsonValue::Field::Reader::getName() const { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::Text::Builder JsonValue::Field::Builder::getName() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void JsonValue::Field::Builder::setName( ::capnp::Text::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::Text::Builder JsonValue::Field::Builder::initName(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void JsonValue::Field::Builder::adoptName( - ::capnp::Orphan< ::capnp::Text>&& value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::Text> JsonValue::Field::Builder::disownName() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool JsonValue::Field::Reader::hasValue() const { - return !_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline bool JsonValue::Field::Builder::hasValue() { - return !_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::JsonValue::Reader JsonValue::Field::Reader::getValue() const { - return ::capnp::_::PointerHelpers< ::capnp::JsonValue>::get(_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline ::capnp::JsonValue::Builder JsonValue::Field::Builder::getValue() { - return ::capnp::_::PointerHelpers< ::capnp::JsonValue>::get(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::JsonValue::Pipeline JsonValue::Field::Pipeline::getValue() { - return ::capnp::JsonValue::Pipeline(_typeless.getPointerField(1)); -} -#endif // !CAPNP_LITE -inline void JsonValue::Field::Builder::setValue( ::capnp::JsonValue::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::JsonValue>::set(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), value); -} -inline ::capnp::JsonValue::Builder JsonValue::Field::Builder::initValue() { - return ::capnp::_::PointerHelpers< ::capnp::JsonValue>::init(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline void JsonValue::Field::Builder::adoptValue( - ::capnp::Orphan< ::capnp::JsonValue>&& value) { - ::capnp::_::PointerHelpers< ::capnp::JsonValue>::adopt(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::JsonValue> JsonValue::Field::Builder::disownValue() { - return ::capnp::_::PointerHelpers< ::capnp::JsonValue>::disown(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} - -inline bool JsonValue::Call::Reader::hasFunction() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool JsonValue::Call::Builder::hasFunction() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::Text::Reader JsonValue::Call::Reader::getFunction() const { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::Text::Builder JsonValue::Call::Builder::getFunction() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void JsonValue::Call::Builder::setFunction( ::capnp::Text::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::Text::Builder JsonValue::Call::Builder::initFunction(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void JsonValue::Call::Builder::adoptFunction( - ::capnp::Orphan< ::capnp::Text>&& value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::Text> JsonValue::Call::Builder::disownFunction() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool JsonValue::Call::Reader::hasParams() const { - return !_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline bool JsonValue::Call::Builder::hasParams() { - return !_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::JsonValue>::Reader JsonValue::Call::Reader::getParams() const { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::JsonValue>>::get(_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::JsonValue>::Builder JsonValue::Call::Builder::getParams() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::JsonValue>>::get(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline void JsonValue::Call::Builder::setParams( ::capnp::List< ::capnp::JsonValue>::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::JsonValue>>::set(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::JsonValue>::Builder JsonValue::Call::Builder::initParams(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::JsonValue>>::init(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), size); -} -inline void JsonValue::Call::Builder::adoptParams( - ::capnp::Orphan< ::capnp::List< ::capnp::JsonValue>>&& value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::JsonValue>>::adopt(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::JsonValue>> JsonValue::Call::Builder::disownParams() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::JsonValue>>::disown(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} - -} // namespace - -#endif // CAPNP_INCLUDED_8ef99297a43a5e34_ diff --git a/phonelibs/capnp-cpp/include/capnp/compat/json.h b/phonelibs/capnp-cpp/include/capnp/compat/json.h deleted file mode 100644 index 7fa815e099..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/compat/json.h +++ /dev/null @@ -1,462 +0,0 @@ -// Copyright (c) 2015 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_COMPAT_JSON_H_ -#define CAPNP_COMPAT_JSON_H_ - -#include -#include -#include - -namespace capnp { - -class JsonCodec { - // Flexible class for encoding Cap'n Proto types as JSON, and decoding JSON back to Cap'n Proto. - // - // Typical usage: - // - // JsonCodec json; - // - // // encode - // kj::String encoded = json.encode(someStructReader); - // - // // decode - // json.decode(encoded, someStructBuilder); - // - // Advanced users can do fancy things like override the way certain types or fields are - // represented in JSON by registering handlers. See the unit test for an example. - // - // Notes: - // - When encoding, all primitive fields are always encoded, even if default-valued. Pointer - // fields are only encoded if they are non-null. - // - 64-bit integers are encoded as strings, since JSON "numbers" are double-precision floating - // points which cannot store a 64-bit integer without losing data. - // - NaNs and infinite floating point numbers are not allowed by the JSON spec, and so are encoded - // as null. This matches the behavior of `JSON.stringify` in at least Firefox and Chrome. - // - Data is encoded as an array of numbers in the range [0,255]. You probably want to register - // a handler that does something better, like maybe base64 encoding, but there are a zillion - // different ways people do this. - // - Encoding/decoding capabilities and AnyPointers requires registering a Handler, since there's - // no obvious default behavior. - // - When decoding, unrecognized field names are ignored. Note: This means that JSON is NOT a - // good format for receiving input from a human. Consider `capnp eval` or the SchemaParser - // library for human input. - -public: - JsonCodec(); - ~JsonCodec() noexcept(false); - - // --------------------------------------------------------------------------- - // standard API - - void setPrettyPrint(bool enabled); - // Enable to insert newlines, indentation, and other extra spacing into the output. The default - // is to use minimal whitespace. - - void setMaxNestingDepth(size_t maxNestingDepth); - // Set maximum nesting depth when decoding JSON to prevent highly nested input from overflowing - // the call stack. The default is 64. - - template - kj::String encode(T&& value); - // Encode any Cap'n Proto value to JSON, including primitives and - // Dynamic{Enum,Struct,List,Capability}, but not DynamicValue (see below). - - kj::String encode(DynamicValue::Reader value, Type type) const; - // Encode a DynamicValue to JSON. `type` is needed because `DynamicValue` itself does - // not distinguish between e.g. int32 and int64, which in JSON are handled differently. Most - // of the time, though, you can use the single-argument templated version of `encode()` instead. - - void decode(kj::ArrayPtr input, DynamicStruct::Builder output) const; - // Decode JSON text directly into a struct builder. This only works for structs since lists - // need to be allocated with the correct size in advance. - // - // (Remember that any Cap'n Proto struct reader type can be implicitly cast to - // DynamicStruct::Reader.) - - template - Orphan decode(kj::ArrayPtr input, Orphanage orphanage) const; - // Decode JSON text to any Cap'n Proto object (pointer value), allocated using the given - // orphanage. T must be specified explicitly and cannot be dynamic, e.g.: - // - // Orphan orphan = json.decode(text, orphanage); - - template - ReaderFor decode(kj::ArrayPtr input) const; - // Decode JSON text into a primitive or capability value. T must be specified explicitly and - // cannot be dynamic, e.g.: - // - // uint32_t n = json.decode(text); - - Orphan decode(kj::ArrayPtr input, Type type, Orphanage orphanage) const; - Orphan decode( - kj::ArrayPtr input, ListSchema type, Orphanage orphanage) const; - Orphan decode( - kj::ArrayPtr input, StructSchema type, Orphanage orphanage) const; - DynamicCapability::Client decode(kj::ArrayPtr input, InterfaceSchema type) const; - DynamicEnum decode(kj::ArrayPtr input, EnumSchema type) const; - // Decode to a dynamic value, specifying the type schema. - - // --------------------------------------------------------------------------- - // layered API - // - // You can separate text <-> JsonValue from JsonValue <-> T. These are particularly useful - // for calling from Handler implementations. - - kj::String encodeRaw(JsonValue::Reader value) const; - void decodeRaw(kj::ArrayPtr input, JsonValue::Builder output) const; - // Translate JsonValue <-> text. - - template - void encode(T&& value, JsonValue::Builder output); - void encode(DynamicValue::Reader input, Type type, JsonValue::Builder output) const; - void decode(JsonValue::Reader input, DynamicStruct::Builder output) const; - template - Orphan decode(JsonValue::Reader input, Orphanage orphanage) const; - template - ReaderFor decode(JsonValue::Reader input) const; - - Orphan decode(JsonValue::Reader input, Type type, Orphanage orphanage) const; - Orphan decode(JsonValue::Reader input, ListSchema type, Orphanage orphanage) const; - Orphan decode( - JsonValue::Reader input, StructSchema type, Orphanage orphanage) const; - DynamicCapability::Client decode(JsonValue::Reader input, InterfaceSchema type) const; - DynamicEnum decode(JsonValue::Reader input, EnumSchema type) const; - - // --------------------------------------------------------------------------- - // specializing particular types - - template ()> - class Handler; - // Implement this interface to specify a special encoding for a particular type or field. - // - // The templates are a bit ugly, but subclasses of this type essentially implement two methods, - // one to encode values of this type and one to decode values of this type. `encode()` is simple: - // - // void encode(const JsonCodec& codec, ReaderFor input, JsonValue::Builder output) const; - // - // `decode()` is a bit trickier. When T is a struct (including DynamicStruct), it is: - // - // void decode(const JsonCodec& codec, JsonValue::Reader input, BuilderFor output) const; - // - // However, when T is a primitive, decode() is: - // - // T decode(const JsonCodec& codec, JsonValue::Reader input) const; - // - // Or when T is any non-struct object (list, blob), decode() is: - // - // Orphan decode(const JsonCodec& codec, JsonValue::Reader input, Orphanage orphanage) const; - // - // Or when T is an interface: - // - // T::Client decode(const JsonCodec& codec, JsonValue::Reader input) const; - // - // Additionally, when T is a struct you can *optionally* also implement the orphan-returning form - // of decode(), but it will only be called when the struct would be allocated as an individual - // object, not as part of a list. This allows you to return "nullptr" in these cases to say that - // the pointer value should be null. This does not apply to list elements because struct list - // elements cannot ever be null (since Cap'n Proto encodes struct lists as a flat list rather - // than list-of-pointers). - - template - void addTypeHandler(Handler& handler); - void addTypeHandler(Type type, Handler& handler); - void addTypeHandler(EnumSchema type, Handler& handler); - void addTypeHandler(StructSchema type, Handler& handler); - void addTypeHandler(ListSchema type, Handler& handler); - void addTypeHandler(InterfaceSchema type, Handler& handler); - // Arrange that whenever the type T appears in the message, your handler will be used to - // encode/decode it. - // - // Note that if you register a handler for a capability type, it will also apply to subtypes. - // Thus Handler handles all capabilities. - - template - void addFieldHandler(StructSchema::Field field, Handler& handler); - // Matches only the specific field. T can be a dynamic type. T must match the field's type. - -private: - class HandlerBase; - struct Impl; - - kj::Own impl; - - void encodeField(StructSchema::Field field, DynamicValue::Reader input, - JsonValue::Builder output) const; - void decodeArray(List::Reader input, DynamicList::Builder output) const; - void decodeObject(List::Reader input, DynamicStruct::Builder output) const; - void addTypeHandlerImpl(Type type, HandlerBase& handler); - void addFieldHandlerImpl(StructSchema::Field field, Type type, HandlerBase& handler); -}; - -// ======================================================================================= -// inline implementation details - -template -kj::String JsonCodec::encode(T&& value) { - typedef FromAny> Base; - return encode(DynamicValue::Reader(ReaderFor(kj::fwd(value))), Type::from()); -} - -template -inline Orphan JsonCodec::decode(kj::ArrayPtr input, Orphanage orphanage) const { - return decode(input, Type::from(), orphanage).template releaseAs(); -} - -template -inline ReaderFor JsonCodec::decode(kj::ArrayPtr input) const { - static_assert(style() == Style::PRIMITIVE || style() == Style::CAPABILITY, - "must specify an orphanage to decode an object type"); - return decode(input, Type::from(), Orphanage()).getReader().template as(); -} - -inline Orphan JsonCodec::decode( - kj::ArrayPtr input, ListSchema type, Orphanage orphanage) const { - return decode(input, Type(type), orphanage).releaseAs(); -} -inline Orphan JsonCodec::decode( - kj::ArrayPtr input, StructSchema type, Orphanage orphanage) const { - return decode(input, Type(type), orphanage).releaseAs(); -} -inline DynamicCapability::Client JsonCodec::decode( - kj::ArrayPtr input, InterfaceSchema type) const { - return decode(input, Type(type), Orphanage()).getReader().as(); -} -inline DynamicEnum JsonCodec::decode(kj::ArrayPtr input, EnumSchema type) const { - return decode(input, Type(type), Orphanage()).getReader().as(); -} - -// ----------------------------------------------------------------------------- - -template -void JsonCodec::encode(T&& value, JsonValue::Builder output) { - typedef FromAny> Base; - encode(DynamicValue::Reader(ReaderFor(kj::fwd(value))), Type::from(), output); -} - -template -inline Orphan JsonCodec::decode(JsonValue::Reader input, Orphanage orphanage) const { - return decode(input, Type::from(), orphanage).template releaseAs(); -} - -template -inline ReaderFor JsonCodec::decode(JsonValue::Reader input) const { - static_assert(style() == Style::PRIMITIVE || style() == Style::CAPABILITY, - "must specify an orphanage to decode an object type"); - return decode(input, Type::from(), Orphanage()).getReader().template as(); -} - -inline Orphan JsonCodec::decode( - JsonValue::Reader input, ListSchema type, Orphanage orphanage) const { - return decode(input, Type(type), orphanage).releaseAs(); -} -inline Orphan JsonCodec::decode( - JsonValue::Reader input, StructSchema type, Orphanage orphanage) const { - return decode(input, Type(type), orphanage).releaseAs(); -} -inline DynamicCapability::Client JsonCodec::decode( - JsonValue::Reader input, InterfaceSchema type) const { - return decode(input, Type(type), Orphanage()).getReader().as(); -} -inline DynamicEnum JsonCodec::decode(JsonValue::Reader input, EnumSchema type) const { - return decode(input, Type(type), Orphanage()).getReader().as(); -} - -// ----------------------------------------------------------------------------- - -class JsonCodec::HandlerBase { - // Internal helper; ignore. -public: - virtual void encodeBase(const JsonCodec& codec, DynamicValue::Reader input, - JsonValue::Builder output) const = 0; - virtual Orphan decodeBase(const JsonCodec& codec, JsonValue::Reader input, - Type type, Orphanage orphanage) const; - virtual void decodeStructBase(const JsonCodec& codec, JsonValue::Reader input, - DynamicStruct::Builder output) const; -}; - -template -class JsonCodec::Handler: private JsonCodec::HandlerBase { -public: - virtual void encode(const JsonCodec& codec, ReaderFor input, - JsonValue::Builder output) const = 0; - virtual Orphan decode(const JsonCodec& codec, JsonValue::Reader input, - Orphanage orphanage) const = 0; - -private: - void encodeBase(const JsonCodec& codec, DynamicValue::Reader input, - JsonValue::Builder output) const override final { - encode(codec, input.as(), output); - } - Orphan decodeBase(const JsonCodec& codec, JsonValue::Reader input, - Type type, Orphanage orphanage) const override final { - return decode(codec, input, orphanage); - } - friend class JsonCodec; -}; - -template -class JsonCodec::Handler: private JsonCodec::HandlerBase { -public: - virtual void encode(const JsonCodec& codec, ReaderFor input, - JsonValue::Builder output) const = 0; - virtual void decode(const JsonCodec& codec, JsonValue::Reader input, - BuilderFor output) const = 0; - virtual Orphan decode(const JsonCodec& codec, JsonValue::Reader input, - Orphanage orphanage) const { - // If subclass does not override, fall back to regular version. - auto result = orphanage.newOrphan(); - decode(codec, input, result.get()); - return result; - } - -private: - void encodeBase(const JsonCodec& codec, DynamicValue::Reader input, - JsonValue::Builder output) const override final { - encode(codec, input.as(), output); - } - Orphan decodeBase(const JsonCodec& codec, JsonValue::Reader input, - Type type, Orphanage orphanage) const override final { - return decode(codec, input, orphanage); - } - void decodeStructBase(const JsonCodec& codec, JsonValue::Reader input, - DynamicStruct::Builder output) const override final { - decode(codec, input, output.as()); - } - friend class JsonCodec; -}; - -template <> -class JsonCodec::Handler: private JsonCodec::HandlerBase { - // Almost identical to Style::STRUCT except that we pass the struct type to decode(). - -public: - virtual void encode(const JsonCodec& codec, DynamicStruct::Reader input, - JsonValue::Builder output) const = 0; - virtual void decode(const JsonCodec& codec, JsonValue::Reader input, - DynamicStruct::Builder output) const = 0; - virtual Orphan decode(const JsonCodec& codec, JsonValue::Reader input, - StructSchema type, Orphanage orphanage) const { - // If subclass does not override, fall back to regular version. - auto result = orphanage.newOrphan(type); - decode(codec, input, result.get()); - return result; - } - -private: - void encodeBase(const JsonCodec& codec, DynamicValue::Reader input, - JsonValue::Builder output) const override final { - encode(codec, input.as(), output); - } - Orphan decodeBase(const JsonCodec& codec, JsonValue::Reader input, - Type type, Orphanage orphanage) const override final { - return decode(codec, input, type.asStruct(), orphanage); - } - void decodeStructBase(const JsonCodec& codec, JsonValue::Reader input, - DynamicStruct::Builder output) const override final { - decode(codec, input, output.as()); - } - friend class JsonCodec; -}; - -template -class JsonCodec::Handler: private JsonCodec::HandlerBase { -public: - virtual void encode(const JsonCodec& codec, T input, JsonValue::Builder output) const = 0; - virtual T decode(const JsonCodec& codec, JsonValue::Reader input) const = 0; - -private: - void encodeBase(const JsonCodec& codec, DynamicValue::Reader input, - JsonValue::Builder output) const override final { - encode(codec, input.as(), output); - } - Orphan decodeBase(const JsonCodec& codec, JsonValue::Reader input, - Type type, Orphanage orphanage) const override final { - return decode(codec, input); - } - friend class JsonCodec; -}; - -template -class JsonCodec::Handler: private JsonCodec::HandlerBase { -public: - virtual void encode(const JsonCodec& codec, typename T::Client input, - JsonValue::Builder output) const = 0; - virtual typename T::Client decode(const JsonCodec& codec, JsonValue::Reader input) const = 0; - -private: - void encodeBase(const JsonCodec& codec, DynamicValue::Reader input, - JsonValue::Builder output) const override final { - encode(codec, input.as(), output); - } - Orphan decodeBase(const JsonCodec& codec, JsonValue::Reader input, - Type type, Orphanage orphanage) const override final { - return orphanage.newOrphanCopy(decode(codec, input)); - } - friend class JsonCodec; -}; - -template -inline void JsonCodec::addTypeHandler(Handler& handler) { - addTypeHandlerImpl(Type::from(), handler); -} -inline void JsonCodec::addTypeHandler(Type type, Handler& handler) { - addTypeHandlerImpl(type, handler); -} -inline void JsonCodec::addTypeHandler(EnumSchema type, Handler& handler) { - addTypeHandlerImpl(type, handler); -} -inline void JsonCodec::addTypeHandler(StructSchema type, Handler& handler) { - addTypeHandlerImpl(type, handler); -} -inline void JsonCodec::addTypeHandler(ListSchema type, Handler& handler) { - addTypeHandlerImpl(type, handler); -} -inline void JsonCodec::addTypeHandler(InterfaceSchema type, Handler& handler) { - addTypeHandlerImpl(type, handler); -} - -template -inline void JsonCodec::addFieldHandler(StructSchema::Field field, Handler& handler) { - addFieldHandlerImpl(field, Type::from(), handler); -} - -template <> void JsonCodec::addTypeHandler(Handler& handler) - KJ_UNAVAILABLE("JSON handlers for type sets (e.g. all structs, all lists) not implemented; " - "try specifying a specific type schema as the first parameter"); -template <> void JsonCodec::addTypeHandler(Handler& handler) - KJ_UNAVAILABLE("JSON handlers for type sets (e.g. all structs, all lists) not implemented; " - "try specifying a specific type schema as the first parameter"); -template <> void JsonCodec::addTypeHandler(Handler& handler) - KJ_UNAVAILABLE("JSON handlers for type sets (e.g. all structs, all lists) not implemented; " - "try specifying a specific type schema as the first parameter"); -template <> void JsonCodec::addTypeHandler(Handler& handler) - KJ_UNAVAILABLE("JSON handlers for type sets (e.g. all structs, all lists) not implemented; " - "try specifying a specific type schema as the first parameter"); -template <> void JsonCodec::addTypeHandler(Handler& handler) - KJ_UNAVAILABLE("JSON handlers for type sets (e.g. all structs, all lists) not implemented; " - "try specifying a specific type schema as the first parameter"); -// TODO(someday): Implement support for registering handlers that cover thinsg like "all structs" -// or "all lists". Currently you can only target a specific struct or list type. - -} // namespace capnp - -#endif // CAPNP_COMPAT_JSON_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/dynamic.h b/phonelibs/capnp-cpp/include/capnp/dynamic.h deleted file mode 100644 index fcefcc3bf2..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/dynamic.h +++ /dev/null @@ -1,1643 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// This file defines classes that can be used to manipulate messages based on schemas that are not -// known until runtime. This is also useful for writing generic code that uses schemas to handle -// arbitrary types in a generic way. -// -// Each of the classes defined here has a to() template method which converts an instance back to a -// native type. This method will throw an exception if the requested type does not match the -// schema. To convert native types to dynamic, use DynamicFactory. -// -// As always, underlying data is validated lazily, so you have to actually traverse the whole -// message if you want to validate all content. - -#ifndef CAPNP_DYNAMIC_H_ -#define CAPNP_DYNAMIC_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include "schema.h" -#include "layout.h" -#include "message.h" -#include "any.h" -#include "capability.h" - -namespace capnp { - -class MessageReader; -class MessageBuilder; - -struct DynamicValue { - DynamicValue() = delete; - - enum Type { - UNKNOWN, - // Means that the value has unknown type and content because it comes from a newer version of - // the schema, or from a newer version of Cap'n Proto that has new features that this version - // doesn't understand. - - VOID, - BOOL, - INT, - UINT, - FLOAT, - TEXT, - DATA, - LIST, - ENUM, - STRUCT, - CAPABILITY, - ANY_POINTER - }; - - class Reader; - class Builder; - class Pipeline; -}; -class DynamicEnum; -struct DynamicStruct { - DynamicStruct() = delete; - class Reader; - class Builder; - class Pipeline; -}; -struct DynamicList { - DynamicList() = delete; - class Reader; - class Builder; -}; -struct DynamicCapability { - DynamicCapability() = delete; - class Client; - class Server; -}; -template <> class Orphan; - -template struct DynamicTypeFor_; -template <> struct DynamicTypeFor_ { typedef DynamicEnum Type; }; -template <> struct DynamicTypeFor_ { typedef DynamicStruct Type; }; -template <> struct DynamicTypeFor_ { typedef DynamicList Type; }; -template <> struct DynamicTypeFor_ { typedef DynamicCapability Type; }; - -template -using DynamicTypeFor = typename DynamicTypeFor_()>::Type; - -template -ReaderFor>> toDynamic(T&& value); -template -BuilderFor>> toDynamic(T&& value); -template -DynamicTypeFor> toDynamic(T&& value); -template -typename DynamicTypeFor>::Client toDynamic(kj::Own&& value); - -namespace _ { // private - -template <> struct Kind_ { static constexpr Kind kind = Kind::OTHER; }; -template <> struct Kind_ { static constexpr Kind kind = Kind::OTHER; }; -template <> struct Kind_ { static constexpr Kind kind = Kind::OTHER; }; -template <> struct Kind_ { static constexpr Kind kind = Kind::OTHER; }; -template <> struct Kind_ { static constexpr Kind kind = Kind::OTHER; }; - -} // namespace _ (private) - -template <> inline constexpr Style style() { return Style::POINTER; } -template <> inline constexpr Style style() { return Style::PRIMITIVE; } -template <> inline constexpr Style style() { return Style::STRUCT; } -template <> inline constexpr Style style() { return Style::POINTER; } -template <> inline constexpr Style style() { return Style::CAPABILITY; } - -// ------------------------------------------------------------------- - -class DynamicEnum { -public: - DynamicEnum() = default; - inline DynamicEnum(EnumSchema::Enumerant enumerant) - : schema(enumerant.getContainingEnum()), value(enumerant.getOrdinal()) {} - inline DynamicEnum(EnumSchema schema, uint16_t value) - : schema(schema), value(value) {} - - template () == Kind::ENUM>> - inline DynamicEnum(T&& value): DynamicEnum(toDynamic(value)) {} - - template - inline T as() const { return static_cast(asImpl(typeId())); } - // Cast to a native enum type. - - inline EnumSchema getSchema() const { return schema; } - - kj::Maybe getEnumerant() const; - // Get which enumerant this enum value represents. Returns nullptr if the numeric value does not - // correspond to any enumerant in the schema -- this can happen if the data was built using a - // newer schema that has more values defined. - - inline uint16_t getRaw() const { return value; } - // Returns the raw underlying enum value. - -private: - EnumSchema schema; - uint16_t value; - - uint16_t asImpl(uint64_t requestedTypeId) const; - - friend struct DynamicStruct; - friend struct DynamicList; - friend struct DynamicValue; - template - friend DynamicTypeFor> toDynamic(T&& value); -}; - -// ------------------------------------------------------------------- - -class DynamicStruct::Reader { -public: - typedef DynamicStruct Reads; - - Reader() = default; - - template >() == Kind::STRUCT>> - inline Reader(T&& value): Reader(toDynamic(value)) {} - - inline MessageSize totalSize() const { return reader.totalSize().asPublic(); } - - template - typename T::Reader as() const; - // Convert the dynamic struct to its compiled-in type. - - inline StructSchema getSchema() const { return schema; } - - DynamicValue::Reader get(StructSchema::Field field) const; - // Read the given field value. - - bool has(StructSchema::Field field) const; - // Tests whether the given field is set to its default value. For pointer values, this does - // not actually traverse the value comparing it with the default, but simply returns true if the - // pointer is non-null. For members of unions, has() returns false if the union member is not - // active, but does not necessarily return true if the member is active (depends on the field's - // value). - - kj::Maybe which() const; - // If the struct contains an (unnamed) union, and the currently-active field within that union - // is known, this returns that field. Otherwise, it returns null. In other words, this returns - // null if there is no union present _or_ if the union's discriminant is set to an unrecognized - // value. This could happen in particular when receiving a message from a sender who has a - // newer version of the protocol and is using a field of the union that you don't know about yet. - - DynamicValue::Reader get(kj::StringPtr name) const; - bool has(kj::StringPtr name) const; - // Shortcuts to access fields by name. These throw exceptions if no such field exists. - -private: - StructSchema schema; - _::StructReader reader; - - inline Reader(StructSchema schema, _::StructReader reader) - : schema(schema), reader(reader) {} - Reader(StructSchema schema, const _::OrphanBuilder& orphan); - - bool isSetInUnion(StructSchema::Field field) const; - void verifySetInUnion(StructSchema::Field field) const; - static DynamicValue::Reader getImpl(_::StructReader reader, StructSchema::Field field); - - template - friend struct _::PointerHelpers; - friend class DynamicStruct::Builder; - friend struct DynamicList; - friend class MessageReader; - friend class MessageBuilder; - template - friend struct ::capnp::ToDynamic_; - friend kj::StringTree _::structString( - _::StructReader reader, const _::RawBrandedSchema& schema); - friend class Orphanage; - friend class Orphan; - friend class Orphan; - friend class Orphan; -}; - -class DynamicStruct::Builder { -public: - typedef DynamicStruct Builds; - - Builder() = default; - inline Builder(decltype(nullptr)) {} - - template >() == Kind::STRUCT>> - inline Builder(T&& value): Builder(toDynamic(value)) {} - - inline MessageSize totalSize() const { return asReader().totalSize(); } - - template - typename T::Builder as(); - // Cast to a particular struct type. - - inline StructSchema getSchema() const { return schema; } - - DynamicValue::Builder get(StructSchema::Field field); - // Read the given field value. - - inline bool has(StructSchema::Field field) { return asReader().has(field); } - // Tests whether the given field is set to its default value. For pointer values, this does - // not actually traverse the value comparing it with the default, but simply returns true if the - // pointer is non-null. For members of unions, has() returns whether the field is currently - // active and the union as a whole is non-default -- so, the only time has() will return false - // for an active union field is if it is the default active field and it has its default value. - - kj::Maybe which(); - // If the struct contains an (unnamed) union, and the currently-active field within that union - // is known, this returns that field. Otherwise, it returns null. In other words, this returns - // null if there is no union present _or_ if the union's discriminant is set to an unrecognized - // value. This could happen in particular when receiving a message from a sender who has a - // newer version of the protocol and is using a field of the union that you don't know about yet. - - void set(StructSchema::Field field, const DynamicValue::Reader& value); - // Set the given field value. - - DynamicValue::Builder init(StructSchema::Field field); - DynamicValue::Builder init(StructSchema::Field field, uint size); - // Init a struct, list, or blob field. - - void adopt(StructSchema::Field field, Orphan&& orphan); - Orphan disown(StructSchema::Field field); - // Adopt/disown. This works even for non-pointer fields: adopt() becomes equivalent to set() - // and disown() becomes like get() followed by clear(). - - void clear(StructSchema::Field field); - // Clear a field, setting it to its default value. For pointer fields, this actually makes the - // field null. - - DynamicValue::Builder get(kj::StringPtr name); - bool has(kj::StringPtr name); - void set(kj::StringPtr name, const DynamicValue::Reader& value); - void set(kj::StringPtr name, std::initializer_list value); - DynamicValue::Builder init(kj::StringPtr name); - DynamicValue::Builder init(kj::StringPtr name, uint size); - void adopt(kj::StringPtr name, Orphan&& orphan); - Orphan disown(kj::StringPtr name); - void clear(kj::StringPtr name); - // Shortcuts to access fields by name. These throw exceptions if no such field exists. - - Reader asReader() const; - -private: - StructSchema schema; - _::StructBuilder builder; - - inline Builder(StructSchema schema, _::StructBuilder builder) - : schema(schema), builder(builder) {} - Builder(StructSchema schema, _::OrphanBuilder& orphan); - - bool isSetInUnion(StructSchema::Field field); - void verifySetInUnion(StructSchema::Field field); - void setInUnion(StructSchema::Field field); - - template - friend struct _::PointerHelpers; - friend struct DynamicList; - friend class MessageReader; - friend class MessageBuilder; - template - friend struct ::capnp::ToDynamic_; - friend class Orphanage; - friend class Orphan; - friend class Orphan; - friend class Orphan; -}; - -class DynamicStruct::Pipeline { -public: - typedef DynamicStruct Pipelines; - - inline Pipeline(decltype(nullptr)): typeless(nullptr) {} - - template - typename T::Pipeline releaseAs(); - // Convert the dynamic pipeline to its compiled-in type. - - inline StructSchema getSchema() { return schema; } - - DynamicValue::Pipeline get(StructSchema::Field field); - // Read the given field value. - - DynamicValue::Pipeline get(kj::StringPtr name); - // Get by string name. - -private: - StructSchema schema; - AnyPointer::Pipeline typeless; - - inline explicit Pipeline(StructSchema schema, AnyPointer::Pipeline&& typeless) - : schema(schema), typeless(kj::mv(typeless)) {} - - friend class Request; -}; - -// ------------------------------------------------------------------- - -class DynamicList::Reader { -public: - typedef DynamicList Reads; - - inline Reader(): reader(ElementSize::VOID) {} - - template >() == Kind::LIST>> - inline Reader(T&& value): Reader(toDynamic(value)) {} - - template - typename T::Reader as() const; - // Try to convert to any List, Data, or Text. Throws an exception if the underlying data - // can't possibly represent the requested type. - - inline ListSchema getSchema() const { return schema; } - - inline uint size() const { return unbound(reader.size() / ELEMENTS); } - DynamicValue::Reader operator[](uint index) const; - - typedef _::IndexingIterator Iterator; - inline Iterator begin() const { return Iterator(this, 0); } - inline Iterator end() const { return Iterator(this, size()); } - -private: - ListSchema schema; - _::ListReader reader; - - Reader(ListSchema schema, _::ListReader reader): schema(schema), reader(reader) {} - Reader(ListSchema schema, const _::OrphanBuilder& orphan); - - template - friend struct _::PointerHelpers; - friend struct DynamicStruct; - friend class DynamicList::Builder; - template - friend struct ::capnp::ToDynamic_; - friend class Orphanage; - friend class Orphan; - friend class Orphan; - friend class Orphan; -}; - -class DynamicList::Builder { -public: - typedef DynamicList Builds; - - inline Builder(): builder(ElementSize::VOID) {} - inline Builder(decltype(nullptr)): builder(ElementSize::VOID) {} - - template >() == Kind::LIST>> - inline Builder(T&& value): Builder(toDynamic(value)) {} - - template - typename T::Builder as(); - // Try to convert to any List, Data, or Text. Throws an exception if the underlying data - // can't possibly represent the requested type. - - inline ListSchema getSchema() const { return schema; } - - inline uint size() const { return unbound(builder.size() / ELEMENTS); } - DynamicValue::Builder operator[](uint index); - void set(uint index, const DynamicValue::Reader& value); - DynamicValue::Builder init(uint index, uint size); - void adopt(uint index, Orphan&& orphan); - Orphan disown(uint index); - - typedef _::IndexingIterator Iterator; - inline Iterator begin() { return Iterator(this, 0); } - inline Iterator end() { return Iterator(this, size()); } - - void copyFrom(std::initializer_list value); - - Reader asReader() const; - -private: - ListSchema schema; - _::ListBuilder builder; - - Builder(ListSchema schema, _::ListBuilder builder): schema(schema), builder(builder) {} - Builder(ListSchema schema, _::OrphanBuilder& orphan); - - template - friend struct _::PointerHelpers; - friend struct DynamicStruct; - template - friend struct ::capnp::ToDynamic_; - friend class Orphanage; - template - friend struct _::OrphanGetImpl; - friend class Orphan; - friend class Orphan; - friend class Orphan; -}; - -// ------------------------------------------------------------------- - -class DynamicCapability::Client: public Capability::Client { -public: - typedef DynamicCapability Calls; - typedef DynamicCapability Reads; - - Client() = default; - - template >() == Kind::INTERFACE>> - inline Client(T&& client); - - template ()>> - inline Client(kj::Own&& server); - - template () == Kind::INTERFACE>> - typename T::Client as(); - template () == Kind::INTERFACE>> - typename T::Client releaseAs(); - // Convert to any client type. - - Client upcast(InterfaceSchema requestedSchema); - // Upcast to a superclass. Throws an exception if `schema` is not a superclass. - - inline InterfaceSchema getSchema() { return schema; } - - Request newRequest( - InterfaceSchema::Method method, kj::Maybe sizeHint = nullptr); - Request newRequest( - kj::StringPtr methodName, kj::Maybe sizeHint = nullptr); - -private: - InterfaceSchema schema; - - Client(InterfaceSchema schema, kj::Own&& hook) - : Capability::Client(kj::mv(hook)), schema(schema) {} - - template - inline Client(InterfaceSchema schema, kj::Own&& server); - - friend struct Capability; - friend struct DynamicStruct; - friend struct DynamicList; - friend struct DynamicValue; - friend class Orphan; - friend class Orphan; - friend class Orphan; - template - friend struct _::PointerHelpers; -}; - -class DynamicCapability::Server: public Capability::Server { -public: - typedef DynamicCapability Serves; - - Server(InterfaceSchema schema): schema(schema) {} - - virtual kj::Promise call(InterfaceSchema::Method method, - CallContext context) = 0; - - kj::Promise dispatchCall(uint64_t interfaceId, uint16_t methodId, - CallContext context) override final; - - inline InterfaceSchema getSchema() const { return schema; } - -private: - InterfaceSchema schema; -}; - -template <> -class Request: public DynamicStruct::Builder { - // Specialization of `Request` for DynamicStruct. - -public: - inline Request(DynamicStruct::Builder builder, kj::Own&& hook, - StructSchema resultSchema) - : DynamicStruct::Builder(builder), hook(kj::mv(hook)), resultSchema(resultSchema) {} - - RemotePromise send(); - // Send the call and return a promise for the results. - -private: - kj::Own hook; - StructSchema resultSchema; - - friend class Capability::Client; - friend struct DynamicCapability; - template - friend class CallContext; - friend class RequestHook; -}; - -template <> -class CallContext: public kj::DisallowConstCopy { - // Wrapper around CallContextHook with a specific return type. - // - // Methods of this class may only be called from within the server's event loop, not from other - // threads. - -public: - explicit CallContext(CallContextHook& hook, StructSchema paramType, StructSchema resultType); - - DynamicStruct::Reader getParams(); - void releaseParams(); - DynamicStruct::Builder getResults(kj::Maybe sizeHint = nullptr); - DynamicStruct::Builder initResults(kj::Maybe sizeHint = nullptr); - void setResults(DynamicStruct::Reader value); - void adoptResults(Orphan&& value); - Orphanage getResultsOrphanage(kj::Maybe sizeHint = nullptr); - template - kj::Promise tailCall(Request&& tailRequest); - void allowCancellation(); - -private: - CallContextHook* hook; - StructSchema paramType; - StructSchema resultType; - - friend class DynamicCapability::Server; -}; - -// ------------------------------------------------------------------- - -// Make sure ReaderFor and BuilderFor work for DynamicEnum, DynamicStruct, and -// DynamicList, so that we can define DynamicValue::as(). - -template <> struct ReaderFor_ { typedef DynamicEnum Type; }; -template <> struct BuilderFor_ { typedef DynamicEnum Type; }; -template <> struct ReaderFor_ { typedef DynamicStruct::Reader Type; }; -template <> struct BuilderFor_ { typedef DynamicStruct::Builder Type; }; -template <> struct ReaderFor_ { typedef DynamicList::Reader Type; }; -template <> struct BuilderFor_ { typedef DynamicList::Builder Type; }; -template <> struct ReaderFor_ { typedef DynamicCapability::Client Type; }; -template <> struct BuilderFor_ { typedef DynamicCapability::Client Type; }; -template <> struct PipelineFor_ { typedef DynamicCapability::Client Type; }; - -class DynamicValue::Reader { -public: - typedef DynamicValue Reads; - - inline Reader(decltype(nullptr) n = nullptr); // UNKNOWN - inline Reader(Void value); - inline Reader(bool value); - inline Reader(char value); - inline Reader(signed char value); - inline Reader(short value); - inline Reader(int value); - inline Reader(long value); - inline Reader(long long value); - inline Reader(unsigned char value); - inline Reader(unsigned short value); - inline Reader(unsigned int value); - inline Reader(unsigned long value); - inline Reader(unsigned long long value); - inline Reader(float value); - inline Reader(double value); - inline Reader(const char* value); // Text - inline Reader(const Text::Reader& value); - inline Reader(const Data::Reader& value); - inline Reader(const DynamicList::Reader& value); - inline Reader(DynamicEnum value); - inline Reader(const DynamicStruct::Reader& value); - inline Reader(const AnyPointer::Reader& value); - inline Reader(DynamicCapability::Client& value); - inline Reader(DynamicCapability::Client&& value); - template ()>> - inline Reader(kj::Own&& value); - Reader(ConstSchema constant); - - template ()))> - inline Reader(T&& value): Reader(toDynamic(kj::mv(value))) {} - - Reader(const Reader& other); - Reader(Reader&& other) noexcept; - ~Reader() noexcept(false); - Reader& operator=(const Reader& other); - Reader& operator=(Reader&& other); - // Unfortunately, we cannot use the implicit definitions of these since DynamicCapability is not - // trivially copyable. - - template - inline ReaderFor as() const { return AsImpl::apply(*this); } - // Use to interpret the value as some Cap'n Proto type. Allowed types are: - // - Void, bool, [u]int{8,16,32,64}_t, float, double, any enum: Returns the raw value. - // - Text, Data, AnyPointer, any struct type: Returns the corresponding Reader. - // - List for any T listed above: Returns List::Reader. - // - DynamicEnum: Returns the corresponding type. - // - DynamicStruct, DynamicList: Returns the corresponding Reader. - // - Any capability type, including DynamicCapability: Returns the corresponding Client. - // - DynamicValue: Returns an identical Reader. Useful to avoid special-casing in generic code. - // (TODO(perf): On GCC 4.8 / Clang 3.3, provide rvalue-qualified version that avoids - // refcounting.) - // - // DynamicValue allows various implicit conversions, mostly just to make the interface friendlier. - // - Any integer can be converted to any other integer type so long as the actual value is within - // the new type's range. - // - Floating-point types can be converted to integers as long as no information would be lost - // in the conversion. - // - Integers can be converted to floating points. This may lose information, but won't throw. - // - Float32/Float64 can be converted between each other. Converting Float64 -> Float32 may lose - // information, but won't throw. - // - Text can be converted to an enum, if the Text matches one of the enumerant names (but not - // vice-versa). - // - Capabilities can be upcast (cast to a supertype), but not downcast. - // - // Any other conversion attempt will throw an exception. - - inline Type getType() const { return type; } - // Get the type of this value. - -private: - Type type; - - union { - Void voidValue; - bool boolValue; - int64_t intValue; - uint64_t uintValue; - double floatValue; - Text::Reader textValue; - Data::Reader dataValue; - DynamicList::Reader listValue; - DynamicEnum enumValue; - DynamicStruct::Reader structValue; - AnyPointer::Reader anyPointerValue; - - mutable DynamicCapability::Client capabilityValue; - // Declared mutable because `Client`s normally cannot be const. - - // Warning: Copy/move constructors assume all these types are trivially copyable except - // Capability. - }; - - template ()> struct AsImpl; - // Implementation backing the as() method. Needs to be a struct to allow partial - // specialization. Has a method apply() which does the work. - - friend class Orphanage; // to speed up newOrphanCopy(DynamicValue::Reader) -}; - -class DynamicValue::Builder { -public: - typedef DynamicValue Builds; - - inline Builder(decltype(nullptr) n = nullptr); // UNKNOWN - inline Builder(Void value); - inline Builder(bool value); - inline Builder(char value); - inline Builder(signed char value); - inline Builder(short value); - inline Builder(int value); - inline Builder(long value); - inline Builder(long long value); - inline Builder(unsigned char value); - inline Builder(unsigned short value); - inline Builder(unsigned int value); - inline Builder(unsigned long value); - inline Builder(unsigned long long value); - inline Builder(float value); - inline Builder(double value); - inline Builder(Text::Builder value); - inline Builder(Data::Builder value); - inline Builder(DynamicList::Builder value); - inline Builder(DynamicEnum value); - inline Builder(DynamicStruct::Builder value); - inline Builder(AnyPointer::Builder value); - inline Builder(DynamicCapability::Client& value); - inline Builder(DynamicCapability::Client&& value); - - template ()))> - inline Builder(T value): Builder(toDynamic(value)) {} - - Builder(Builder& other); - Builder(Builder&& other) noexcept; - ~Builder() noexcept(false); - Builder& operator=(Builder& other); - Builder& operator=(Builder&& other); - // Unfortunately, we cannot use the implicit definitions of these since DynamicCapability is not - // trivially copyable. - - template - inline BuilderFor as() { return AsImpl::apply(*this); } - // See DynamicValue::Reader::as(). - - inline Type getType() { return type; } - // Get the type of this value. - - Reader asReader() const; - -private: - Type type; - - union { - Void voidValue; - bool boolValue; - int64_t intValue; - uint64_t uintValue; - double floatValue; - Text::Builder textValue; - Data::Builder dataValue; - DynamicList::Builder listValue; - DynamicEnum enumValue; - DynamicStruct::Builder structValue; - AnyPointer::Builder anyPointerValue; - - mutable DynamicCapability::Client capabilityValue; - // Declared mutable because `Client`s normally cannot be const. - }; - - template ()> struct AsImpl; - // Implementation backing the as() method. Needs to be a struct to allow partial - // specialization. Has a method apply() which does the work. - - friend class Orphan; -}; - -class DynamicValue::Pipeline { -public: - typedef DynamicValue Pipelines; - - inline Pipeline(decltype(nullptr) n = nullptr); - inline Pipeline(DynamicStruct::Pipeline&& value); - inline Pipeline(DynamicCapability::Client&& value); - - Pipeline(Pipeline&& other) noexcept; - Pipeline& operator=(Pipeline&& other); - ~Pipeline() noexcept(false); - - template - inline PipelineFor releaseAs() { return AsImpl::apply(*this); } - - inline Type getType() { return type; } - // Get the type of this value. - -private: - Type type; - union { - DynamicStruct::Pipeline structValue; - DynamicCapability::Client capabilityValue; - }; - - template ()> struct AsImpl; - // Implementation backing the releaseAs() method. Needs to be a struct to allow partial - // specialization. Has a method apply() which does the work. -}; - -kj::StringTree KJ_STRINGIFY(const DynamicValue::Reader& value); -kj::StringTree KJ_STRINGIFY(const DynamicValue::Builder& value); -kj::StringTree KJ_STRINGIFY(DynamicEnum value); -kj::StringTree KJ_STRINGIFY(const DynamicStruct::Reader& value); -kj::StringTree KJ_STRINGIFY(const DynamicStruct::Builder& value); -kj::StringTree KJ_STRINGIFY(const DynamicList::Reader& value); -kj::StringTree KJ_STRINGIFY(const DynamicList::Builder& value); - -// ------------------------------------------------------------------- -// Orphan <-> Dynamic glue - -template <> -class Orphan { -public: - Orphan() = default; - KJ_DISALLOW_COPY(Orphan); - Orphan(Orphan&&) = default; - Orphan& operator=(Orphan&&) = default; - - template () == Kind::STRUCT>> - inline Orphan(Orphan&& other): schema(Schema::from()), builder(kj::mv(other.builder)) {} - - DynamicStruct::Builder get(); - DynamicStruct::Reader getReader() const; - - template - Orphan releaseAs(); - // Like DynamicStruct::Builder::as(), but coerces the Orphan type. Since Orphans are move-only, - // the original Orphan is no longer valid after this call; ownership is - // transferred to the returned Orphan. - - inline bool operator==(decltype(nullptr)) const { return builder == nullptr; } - inline bool operator!=(decltype(nullptr)) const { return builder != nullptr; } - -private: - StructSchema schema; - _::OrphanBuilder builder; - - inline Orphan(StructSchema schema, _::OrphanBuilder&& builder) - : schema(schema), builder(kj::mv(builder)) {} - - template - friend struct _::PointerHelpers; - friend struct DynamicList; - friend class Orphanage; - friend class Orphan; - friend class Orphan; - friend class MessageBuilder; -}; - -template <> -class Orphan { -public: - Orphan() = default; - KJ_DISALLOW_COPY(Orphan); - Orphan(Orphan&&) = default; - Orphan& operator=(Orphan&&) = default; - - template () == Kind::LIST>> - inline Orphan(Orphan&& other): schema(Schema::from()), builder(kj::mv(other.builder)) {} - - DynamicList::Builder get(); - DynamicList::Reader getReader() const; - - template - Orphan releaseAs(); - // Like DynamicList::Builder::as(), but coerces the Orphan type. Since Orphans are move-only, - // the original Orphan is no longer valid after this call; ownership is - // transferred to the returned Orphan. - - // TODO(someday): Support truncate(). - - inline bool operator==(decltype(nullptr)) const { return builder == nullptr; } - inline bool operator!=(decltype(nullptr)) const { return builder != nullptr; } - -private: - ListSchema schema; - _::OrphanBuilder builder; - - inline Orphan(ListSchema schema, _::OrphanBuilder&& builder) - : schema(schema), builder(kj::mv(builder)) {} - - template - friend struct _::PointerHelpers; - friend struct DynamicList; - friend class Orphanage; - friend class Orphan; - friend class Orphan; -}; - -template <> -class Orphan { -public: - Orphan() = default; - KJ_DISALLOW_COPY(Orphan); - Orphan(Orphan&&) = default; - Orphan& operator=(Orphan&&) = default; - - template () == Kind::INTERFACE>> - inline Orphan(Orphan&& other): schema(Schema::from()), builder(kj::mv(other.builder)) {} - - DynamicCapability::Client get(); - DynamicCapability::Client getReader() const; - - template - Orphan releaseAs(); - // Like DynamicCapability::Client::as(), but coerces the Orphan type. Since Orphans are move-only, - // the original Orphan is no longer valid after this call; ownership is - // transferred to the returned Orphan. - - inline bool operator==(decltype(nullptr)) const { return builder == nullptr; } - inline bool operator!=(decltype(nullptr)) const { return builder != nullptr; } - -private: - InterfaceSchema schema; - _::OrphanBuilder builder; - - inline Orphan(InterfaceSchema schema, _::OrphanBuilder&& builder) - : schema(schema), builder(kj::mv(builder)) {} - - template - friend struct _::PointerHelpers; - friend struct DynamicList; - friend class Orphanage; - friend class Orphan; - friend class Orphan; -}; - -template <> -class Orphan { -public: - inline Orphan(decltype(nullptr) n = nullptr): type(DynamicValue::UNKNOWN) {} - inline Orphan(Void value); - inline Orphan(bool value); - inline Orphan(char value); - inline Orphan(signed char value); - inline Orphan(short value); - inline Orphan(int value); - inline Orphan(long value); - inline Orphan(long long value); - inline Orphan(unsigned char value); - inline Orphan(unsigned short value); - inline Orphan(unsigned int value); - inline Orphan(unsigned long value); - inline Orphan(unsigned long long value); - inline Orphan(float value); - inline Orphan(double value); - inline Orphan(DynamicEnum value); - Orphan(Orphan&&) = default; - template - Orphan(Orphan&&); - Orphan(Orphan&&); - Orphan(void*) = delete; // So Orphan(bool) doesn't accept pointers. - KJ_DISALLOW_COPY(Orphan); - - Orphan& operator=(Orphan&&) = default; - - inline DynamicValue::Type getType() { return type; } - - DynamicValue::Builder get(); - DynamicValue::Reader getReader() const; - - template - Orphan releaseAs(); - // Like DynamicValue::Builder::as(), but coerces the Orphan type. Since Orphans are move-only, - // the original Orphan is no longer valid after this call; ownership is - // transferred to the returned Orphan. - -private: - DynamicValue::Type type; - union { - Void voidValue; - bool boolValue; - int64_t intValue; - uint64_t uintValue; - double floatValue; - DynamicEnum enumValue; - StructSchema structSchema; - ListSchema listSchema; - InterfaceSchema interfaceSchema; - }; - - _::OrphanBuilder builder; - // Only used if `type` is a pointer type. - - Orphan(DynamicValue::Builder value, _::OrphanBuilder&& builder); - Orphan(DynamicValue::Type type, _::OrphanBuilder&& builder) - : type(type), builder(kj::mv(builder)) {} - Orphan(StructSchema structSchema, _::OrphanBuilder&& builder) - : type(DynamicValue::STRUCT), structSchema(structSchema), builder(kj::mv(builder)) {} - Orphan(ListSchema listSchema, _::OrphanBuilder&& builder) - : type(DynamicValue::LIST), listSchema(listSchema), builder(kj::mv(builder)) {} - - template - friend struct _::PointerHelpers; - friend struct DynamicStruct; - friend struct DynamicList; - friend struct AnyPointer; - friend class Orphanage; -}; - -template -inline Orphan::Orphan(Orphan&& other) - : Orphan(other.get(), kj::mv(other.builder)) {} - -inline Orphan::Orphan(Orphan&& other) - : type(DynamicValue::ANY_POINTER), builder(kj::mv(other.builder)) {} - -template -Orphan Orphan::releaseAs() { - get().as(); // type check - return Orphan(kj::mv(builder)); -} - -template -Orphan Orphan::releaseAs() { - get().as(); // type check - return Orphan(kj::mv(builder)); -} - -template -Orphan Orphan::releaseAs() { - get().as(); // type check - return Orphan(kj::mv(builder)); -} - -template -Orphan Orphan::releaseAs() { - get().as(); // type check - type = DynamicValue::UNKNOWN; - return Orphan(kj::mv(builder)); -} - -template <> -Orphan Orphan::releaseAs(); -template <> -Orphan Orphan::releaseAs(); -template <> -Orphan Orphan::releaseAs(); -template <> -Orphan Orphan::releaseAs(); - -template <> -struct Orphanage::GetInnerBuilder { - static inline _::StructBuilder apply(DynamicStruct::Builder& t) { - return t.builder; - } -}; - -template <> -struct Orphanage::GetInnerBuilder { - static inline _::ListBuilder apply(DynamicList::Builder& t) { - return t.builder; - } -}; - -template <> -inline Orphan Orphanage::newOrphanCopy( - DynamicStruct::Reader copyFrom) const { - return Orphan( - copyFrom.getSchema(), _::OrphanBuilder::copy(arena, capTable, copyFrom.reader)); -} - -template <> -inline Orphan Orphanage::newOrphanCopy( - DynamicList::Reader copyFrom) const { - return Orphan(copyFrom.getSchema(), - _::OrphanBuilder::copy(arena, capTable, copyFrom.reader)); -} - -template <> -inline Orphan Orphanage::newOrphanCopy( - DynamicCapability::Client copyFrom) const { - return Orphan( - copyFrom.getSchema(), _::OrphanBuilder::copy(arena, capTable, copyFrom.hook->addRef())); -} - -template <> -Orphan Orphanage::newOrphanCopy( - DynamicValue::Reader copyFrom) const; - -namespace _ { // private - -template <> -struct PointerHelpers { - // getDynamic() is used when an AnyPointer's get() accessor is passed arguments, because for - // non-dynamic types PointerHelpers::get() takes a default value as the third argument, and we - // don't want people to accidentally be able to provide their own default value. - static DynamicStruct::Reader getDynamic(PointerReader reader, StructSchema schema); - static DynamicStruct::Builder getDynamic(PointerBuilder builder, StructSchema schema); - static void set(PointerBuilder builder, const DynamicStruct::Reader& value); - static DynamicStruct::Builder init(PointerBuilder builder, StructSchema schema); - static inline void adopt(PointerBuilder builder, Orphan&& value) { - builder.adopt(kj::mv(value.builder)); - } - static inline Orphan disown(PointerBuilder builder, StructSchema schema) { - return Orphan(schema, builder.disown()); - } -}; - -template <> -struct PointerHelpers { - // getDynamic() is used when an AnyPointer's get() accessor is passed arguments, because for - // non-dynamic types PointerHelpers::get() takes a default value as the third argument, and we - // don't want people to accidentally be able to provide their own default value. - static DynamicList::Reader getDynamic(PointerReader reader, ListSchema schema); - static DynamicList::Builder getDynamic(PointerBuilder builder, ListSchema schema); - static void set(PointerBuilder builder, const DynamicList::Reader& value); - static DynamicList::Builder init(PointerBuilder builder, ListSchema schema, uint size); - static inline void adopt(PointerBuilder builder, Orphan&& value) { - builder.adopt(kj::mv(value.builder)); - } - static inline Orphan disown(PointerBuilder builder, ListSchema schema) { - return Orphan(schema, builder.disown()); - } -}; - -template <> -struct PointerHelpers { - // getDynamic() is used when an AnyPointer's get() accessor is passed arguments, because for - // non-dynamic types PointerHelpers::get() takes a default value as the third argument, and we - // don't want people to accidentally be able to provide their own default value. - static DynamicCapability::Client getDynamic(PointerReader reader, InterfaceSchema schema); - static DynamicCapability::Client getDynamic(PointerBuilder builder, InterfaceSchema schema); - static void set(PointerBuilder builder, DynamicCapability::Client& value); - static void set(PointerBuilder builder, DynamicCapability::Client&& value); - static inline void adopt(PointerBuilder builder, Orphan&& value) { - builder.adopt(kj::mv(value.builder)); - } - static inline Orphan disown(PointerBuilder builder, InterfaceSchema schema) { - return Orphan(schema, builder.disown()); - } -}; - -} // namespace _ (private) - -template -inline ReaderFor AnyPointer::Reader::getAs(StructSchema schema) const { - return _::PointerHelpers::getDynamic(reader, schema); -} -template -inline ReaderFor AnyPointer::Reader::getAs(ListSchema schema) const { - return _::PointerHelpers::getDynamic(reader, schema); -} -template -inline ReaderFor AnyPointer::Reader::getAs(InterfaceSchema schema) const { - return _::PointerHelpers::getDynamic(reader, schema); -} -template -inline BuilderFor AnyPointer::Builder::getAs(StructSchema schema) { - return _::PointerHelpers::getDynamic(builder, schema); -} -template -inline BuilderFor AnyPointer::Builder::getAs(ListSchema schema) { - return _::PointerHelpers::getDynamic(builder, schema); -} -template -inline BuilderFor AnyPointer::Builder::getAs(InterfaceSchema schema) { - return _::PointerHelpers::getDynamic(builder, schema); -} -template -inline BuilderFor AnyPointer::Builder::initAs(StructSchema schema) { - return _::PointerHelpers::init(builder, schema); -} -template -inline BuilderFor AnyPointer::Builder::initAs(ListSchema schema, uint elementCount) { - return _::PointerHelpers::init(builder, schema, elementCount); -} -template <> -inline void AnyPointer::Builder::setAs(DynamicStruct::Reader value) { - return _::PointerHelpers::set(builder, value); -} -template <> -inline void AnyPointer::Builder::setAs(DynamicList::Reader value) { - return _::PointerHelpers::set(builder, value); -} -template <> -inline void AnyPointer::Builder::setAs(DynamicCapability::Client value) { - return _::PointerHelpers::set(builder, kj::mv(value)); -} -template <> -void AnyPointer::Builder::adopt(Orphan&& orphan); -template -inline Orphan AnyPointer::Builder::disownAs(StructSchema schema) { - return _::PointerHelpers::disown(builder, schema); -} -template -inline Orphan AnyPointer::Builder::disownAs(ListSchema schema) { - return _::PointerHelpers::disown(builder, schema); -} -template -inline Orphan AnyPointer::Builder::disownAs(InterfaceSchema schema) { - return _::PointerHelpers::disown(builder, schema); -} - -// We have to declare the methods below inline because Clang and GCC disagree about how to mangle -// their symbol names. -template <> -inline DynamicStruct::Builder Orphan::getAs(StructSchema schema) { - return DynamicStruct::Builder(schema, builder); -} -template <> -inline DynamicStruct::Reader Orphan::getAsReader( - StructSchema schema) const { - return DynamicStruct::Reader(schema, builder); -} -template <> -inline Orphan Orphan::releaseAs(StructSchema schema) { - return Orphan(schema, kj::mv(builder)); -} -template <> -inline DynamicList::Builder Orphan::getAs(ListSchema schema) { - return DynamicList::Builder(schema, builder); -} -template <> -inline DynamicList::Reader Orphan::getAsReader(ListSchema schema) const { - return DynamicList::Reader(schema, builder); -} -template <> -inline Orphan Orphan::releaseAs(ListSchema schema) { - return Orphan(schema, kj::mv(builder)); -} -template <> -inline DynamicCapability::Client Orphan::getAs( - InterfaceSchema schema) { - return DynamicCapability::Client(schema, builder.asCapability()); -} -template <> -inline DynamicCapability::Client Orphan::getAsReader( - InterfaceSchema schema) const { - return DynamicCapability::Client(schema, builder.asCapability()); -} -template <> -inline Orphan Orphan::releaseAs( - InterfaceSchema schema) { - return Orphan(schema, kj::mv(builder)); -} - -// ======================================================================================= -// Inline implementation details. - -template -struct ToDynamic_ { - static inline DynamicStruct::Reader apply(const typename T::Reader& value) { - return DynamicStruct::Reader(Schema::from(), value._reader); - } - static inline DynamicStruct::Builder apply(typename T::Builder& value) { - return DynamicStruct::Builder(Schema::from(), value._builder); - } -}; - -template -struct ToDynamic_ { - static inline DynamicList::Reader apply(const typename T::Reader& value) { - return DynamicList::Reader(Schema::from(), value.reader); - } - static inline DynamicList::Builder apply(typename T::Builder& value) { - return DynamicList::Builder(Schema::from(), value.builder); - } -}; - -template -struct ToDynamic_ { - static inline DynamicCapability::Client apply(typename T::Client value) { - return DynamicCapability::Client(kj::mv(value)); - } - static inline DynamicCapability::Client apply(typename T::Client&& value) { - return DynamicCapability::Client(kj::mv(value)); - } -}; - -template -ReaderFor>> toDynamic(T&& value) { - return ToDynamic_>::apply(value); -} -template -BuilderFor>> toDynamic(T&& value) { - return ToDynamic_>::apply(value); -} -template -DynamicTypeFor> toDynamic(T&& value) { - return DynamicEnum(Schema::from>(), static_cast(value)); -} -template -typename DynamicTypeFor>::Client toDynamic(kj::Own&& value) { - return typename FromServer::Client(kj::mv(value)); -} - -inline DynamicValue::Reader::Reader(std::nullptr_t n): type(UNKNOWN) {} -inline DynamicValue::Builder::Builder(std::nullptr_t n): type(UNKNOWN) {} - -#define CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(cppType, typeTag, fieldName) \ -inline DynamicValue::Reader::Reader(cppType value) \ - : type(typeTag), fieldName##Value(value) {} \ -inline DynamicValue::Builder::Builder(cppType value) \ - : type(typeTag), fieldName##Value(value) {} \ -inline Orphan::Orphan(cppType value) \ - : type(DynamicValue::typeTag), fieldName##Value(value) {} - -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(Void, VOID, void); -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(bool, BOOL, bool); -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(char, INT, int); -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(signed char, INT, int); -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(short, INT, int); -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(int, INT, int); -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(long, INT, int); -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(long long, INT, int); -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(unsigned char, UINT, uint); -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(unsigned short, UINT, uint); -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(unsigned int, UINT, uint); -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(unsigned long, UINT, uint); -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(unsigned long long, UINT, uint); -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(float, FLOAT, float); -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(double, FLOAT, float); -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(DynamicEnum, ENUM, enum); -#undef CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR - -#define CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(cppType, typeTag, fieldName) \ -inline DynamicValue::Reader::Reader(const cppType::Reader& value) \ - : type(typeTag), fieldName##Value(value) {} \ -inline DynamicValue::Builder::Builder(cppType::Builder value) \ - : type(typeTag), fieldName##Value(value) {} - -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(Text, TEXT, text); -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(Data, DATA, data); -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(DynamicList, LIST, list); -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(DynamicStruct, STRUCT, struct); -CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR(AnyPointer, ANY_POINTER, anyPointer); - -#undef CAPNP_DECLARE_DYNAMIC_VALUE_CONSTRUCTOR - -inline DynamicValue::Reader::Reader(DynamicCapability::Client& value) - : type(CAPABILITY), capabilityValue(value) {} -inline DynamicValue::Reader::Reader(DynamicCapability::Client&& value) - : type(CAPABILITY), capabilityValue(kj::mv(value)) {} -template -inline DynamicValue::Reader::Reader(kj::Own&& value) - : type(CAPABILITY), capabilityValue(kj::mv(value)) {} -inline DynamicValue::Builder::Builder(DynamicCapability::Client& value) - : type(CAPABILITY), capabilityValue(value) {} -inline DynamicValue::Builder::Builder(DynamicCapability::Client&& value) - : type(CAPABILITY), capabilityValue(kj::mv(value)) {} - -inline DynamicValue::Reader::Reader(const char* value): Reader(Text::Reader(value)) {} - -#define CAPNP_DECLARE_TYPE(discrim, typeName) \ -template <> \ -struct DynamicValue::Reader::AsImpl { \ - static ReaderFor apply(const Reader& reader); \ -}; \ -template <> \ -struct DynamicValue::Builder::AsImpl { \ - static BuilderFor apply(Builder& builder); \ -}; - -//CAPNP_DECLARE_TYPE(VOID, Void) -CAPNP_DECLARE_TYPE(BOOL, bool) -CAPNP_DECLARE_TYPE(INT8, int8_t) -CAPNP_DECLARE_TYPE(INT16, int16_t) -CAPNP_DECLARE_TYPE(INT32, int32_t) -CAPNP_DECLARE_TYPE(INT64, int64_t) -CAPNP_DECLARE_TYPE(UINT8, uint8_t) -CAPNP_DECLARE_TYPE(UINT16, uint16_t) -CAPNP_DECLARE_TYPE(UINT32, uint32_t) -CAPNP_DECLARE_TYPE(UINT64, uint64_t) -CAPNP_DECLARE_TYPE(FLOAT32, float) -CAPNP_DECLARE_TYPE(FLOAT64, double) - -CAPNP_DECLARE_TYPE(TEXT, Text) -CAPNP_DECLARE_TYPE(DATA, Data) -CAPNP_DECLARE_TYPE(LIST, DynamicList) -CAPNP_DECLARE_TYPE(STRUCT, DynamicStruct) -CAPNP_DECLARE_TYPE(INTERFACE, DynamicCapability) -CAPNP_DECLARE_TYPE(ENUM, DynamicEnum) -CAPNP_DECLARE_TYPE(ANY_POINTER, AnyPointer) -#undef CAPNP_DECLARE_TYPE - -// CAPNP_DECLARE_TYPE(Void) causes gcc 4.7 to segfault. If I do it manually and remove the -// ReaderFor<> and BuilderFor<> wrappers, it works. -template <> -struct DynamicValue::Reader::AsImpl { - static Void apply(const Reader& reader); -}; -template <> -struct DynamicValue::Builder::AsImpl { - static Void apply(Builder& builder); -}; - -template -struct DynamicValue::Reader::AsImpl { - static T apply(const Reader& reader) { - return reader.as().as(); - } -}; -template -struct DynamicValue::Builder::AsImpl { - static T apply(Builder& builder) { - return builder.as().as(); - } -}; - -template -struct DynamicValue::Reader::AsImpl { - static typename T::Reader apply(const Reader& reader) { - return reader.as().as(); - } -}; -template -struct DynamicValue::Builder::AsImpl { - static typename T::Builder apply(Builder& builder) { - return builder.as().as(); - } -}; - -template -struct DynamicValue::Reader::AsImpl { - static typename T::Reader apply(const Reader& reader) { - return reader.as().as(); - } -}; -template -struct DynamicValue::Builder::AsImpl { - static typename T::Builder apply(Builder& builder) { - return builder.as().as(); - } -}; - -template -struct DynamicValue::Reader::AsImpl { - static typename T::Client apply(const Reader& reader) { - return reader.as().as(); - } -}; -template -struct DynamicValue::Builder::AsImpl { - static typename T::Client apply(Builder& builder) { - return builder.as().as(); - } -}; - -template <> -struct DynamicValue::Reader::AsImpl { - static DynamicValue::Reader apply(const Reader& reader) { - return reader; - } -}; -template <> -struct DynamicValue::Builder::AsImpl { - static DynamicValue::Builder apply(Builder& builder) { - return builder; - } -}; - -inline DynamicValue::Pipeline::Pipeline(std::nullptr_t n): type(UNKNOWN) {} -inline DynamicValue::Pipeline::Pipeline(DynamicStruct::Pipeline&& value) - : type(STRUCT), structValue(kj::mv(value)) {} -inline DynamicValue::Pipeline::Pipeline(DynamicCapability::Client&& value) - : type(CAPABILITY), capabilityValue(kj::mv(value)) {} - -template -struct DynamicValue::Pipeline::AsImpl { - static typename T::Pipeline apply(Pipeline& pipeline) { - return pipeline.releaseAs().releaseAs(); - } -}; -template -struct DynamicValue::Pipeline::AsImpl { - static typename T::Client apply(Pipeline& pipeline) { - return pipeline.releaseAs().releaseAs(); - } -}; -template <> -struct DynamicValue::Pipeline::AsImpl { - static PipelineFor apply(Pipeline& pipeline); -}; -template <> -struct DynamicValue::Pipeline::AsImpl { - static PipelineFor apply(Pipeline& pipeline); -}; - -// ------------------------------------------------------------------- - -template -typename T::Reader DynamicStruct::Reader::as() const { - static_assert(kind() == Kind::STRUCT, - "DynamicStruct::Reader::as() can only convert to struct types."); - schema.requireUsableAs(); - return typename T::Reader(reader); -} - -template -typename T::Builder DynamicStruct::Builder::as() { - static_assert(kind() == Kind::STRUCT, - "DynamicStruct::Builder::as() can only convert to struct types."); - schema.requireUsableAs(); - return typename T::Builder(builder); -} - -template <> -inline DynamicStruct::Reader DynamicStruct::Reader::as() const { - return *this; -} -template <> -inline DynamicStruct::Builder DynamicStruct::Builder::as() { - return *this; -} - -inline DynamicStruct::Reader DynamicStruct::Builder::asReader() const { - return DynamicStruct::Reader(schema, builder.asReader()); -} - -template <> -inline AnyStruct::Reader DynamicStruct::Reader::as() const { - return AnyStruct::Reader(reader); -} - -template <> -inline AnyStruct::Builder DynamicStruct::Builder::as() { - return AnyStruct::Builder(builder); -} - -template -typename T::Pipeline DynamicStruct::Pipeline::releaseAs() { - static_assert(kind() == Kind::STRUCT, - "DynamicStruct::Pipeline::releaseAs() can only convert to struct types."); - schema.requireUsableAs(); - return typename T::Pipeline(kj::mv(typeless)); -} - -// ------------------------------------------------------------------- - -template -typename T::Reader DynamicList::Reader::as() const { - static_assert(kind() == Kind::LIST, - "DynamicStruct::Reader::as() can only convert to list types."); - schema.requireUsableAs(); - return typename T::Reader(reader); -} -template -typename T::Builder DynamicList::Builder::as() { - static_assert(kind() == Kind::LIST, - "DynamicStruct::Builder::as() can only convert to list types."); - schema.requireUsableAs(); - return typename T::Builder(builder); -} - -template <> -inline DynamicList::Reader DynamicList::Reader::as() const { - return *this; -} -template <> -inline DynamicList::Builder DynamicList::Builder::as() { - return *this; -} - -template <> -inline AnyList::Reader DynamicList::Reader::as() const { - return AnyList::Reader(reader); -} - -template <> -inline AnyList::Builder DynamicList::Builder::as() { - return AnyList::Builder(builder); -} - -// ------------------------------------------------------------------- - -template -inline DynamicCapability::Client::Client(T&& client) - : Capability::Client(kj::mv(client)), schema(Schema::from>()) {} - -template -inline DynamicCapability::Client::Client(kj::Own&& server) - : Client(server->getSchema(), kj::mv(server)) {} -template -inline DynamicCapability::Client::Client(InterfaceSchema schema, kj::Own&& server) - : Capability::Client(kj::mv(server)), schema(schema) {} - -template -typename T::Client DynamicCapability::Client::as() { - static_assert(kind() == Kind::INTERFACE, - "DynamicCapability::Client::as() can only convert to interface types."); - schema.requireUsableAs(); - return typename T::Client(hook->addRef()); -} - -template -typename T::Client DynamicCapability::Client::releaseAs() { - static_assert(kind() == Kind::INTERFACE, - "DynamicCapability::Client::as() can only convert to interface types."); - schema.requireUsableAs(); - return typename T::Client(kj::mv(hook)); -} - -inline CallContext::CallContext( - CallContextHook& hook, StructSchema paramType, StructSchema resultType) - : hook(&hook), paramType(paramType), resultType(resultType) {} -inline DynamicStruct::Reader CallContext::getParams() { - return hook->getParams().getAs(paramType); -} -inline void CallContext::releaseParams() { - hook->releaseParams(); -} -inline DynamicStruct::Builder CallContext::getResults( - kj::Maybe sizeHint) { - return hook->getResults(sizeHint).getAs(resultType); -} -inline DynamicStruct::Builder CallContext::initResults( - kj::Maybe sizeHint) { - return hook->getResults(sizeHint).initAs(resultType); -} -inline void CallContext::setResults(DynamicStruct::Reader value) { - hook->getResults(value.totalSize()).setAs(value); -} -inline void CallContext::adoptResults(Orphan&& value) { - hook->getResults(MessageSize { 0, 0 }).adopt(kj::mv(value)); -} -inline Orphanage CallContext::getResultsOrphanage( - kj::Maybe sizeHint) { - return Orphanage::getForMessageContaining(hook->getResults(sizeHint)); -} -template -inline kj::Promise CallContext::tailCall( - Request&& tailRequest) { - return hook->tailCall(kj::mv(tailRequest.hook)); -} -inline void CallContext::allowCancellation() { - hook->allowCancellation(); -} - -template <> -inline DynamicCapability::Client Capability::Client::castAs( - InterfaceSchema schema) { - return DynamicCapability::Client(schema, hook->addRef()); -} - -// ------------------------------------------------------------------- - -template -ReaderFor ConstSchema::as() const { - return DynamicValue::Reader(*this).as(); -} - -} // namespace capnp - -#endif // CAPNP_DYNAMIC_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/endian.h b/phonelibs/capnp-cpp/include/capnp/endian.h deleted file mode 100644 index c5a6e63c5a..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/endian.h +++ /dev/null @@ -1,309 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_ENDIAN_H_ -#define CAPNP_ENDIAN_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include "common.h" -#include -#include // memcpy - -namespace capnp { -namespace _ { // private - -// WireValue -// -// Wraps a primitive value as it appears on the wire. Namely, values are little-endian on the -// wire, because little-endian is the most common endianness in modern CPUs. -// -// Note: In general, code that depends cares about byte ordering is bad. See: -// http://commandcenter.blogspot.com/2012/04/byte-order-fallacy.html -// Cap'n Proto is special because it is essentially doing compiler-like things, fussing over -// allocation and layout of memory, in order to squeeze out every last drop of performance. - -#if _MSC_VER -// Assume Windows is little-endian. -// -// TODO(msvc): This is ugly. Maybe refactor later checks to be based on CAPNP_BYTE_ORDER or -// CAPNP_SWAP_BYTES or something, and define that in turn based on _MSC_VER or the GCC -// intrinsics. - -#ifndef __ORDER_BIG_ENDIAN__ -#define __ORDER_BIG_ENDIAN__ 4321 -#endif -#ifndef __ORDER_LITTLE_ENDIAN__ -#define __ORDER_LITTLE_ENDIAN__ 1234 -#endif -#ifndef __BYTE_ORDER__ -#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__ -#endif -#endif - -#if CAPNP_REVERSE_ENDIAN -#define CAPNP_WIRE_BYTE_ORDER __ORDER_BIG_ENDIAN__ -#define CAPNP_OPPOSITE_OF_WIRE_BYTE_ORDER __ORDER_LITTLE_ENDIAN__ -#else -#define CAPNP_WIRE_BYTE_ORDER __ORDER_LITTLE_ENDIAN__ -#define CAPNP_OPPOSITE_OF_WIRE_BYTE_ORDER __ORDER_BIG_ENDIAN__ -#endif - -#if defined(__BYTE_ORDER__) && \ - __BYTE_ORDER__ == CAPNP_WIRE_BYTE_ORDER && \ - !CAPNP_DISABLE_ENDIAN_DETECTION -// CPU is little-endian. We can just read/write the memory directly. - -template -class DirectWireValue { -public: - KJ_ALWAYS_INLINE(T get() const) { return value; } - KJ_ALWAYS_INLINE(void set(T newValue)) { value = newValue; } - -private: - T value; -}; - -template -using WireValue = DirectWireValue; -// To prevent ODR problems when endian-test, endian-reverse-test, and endian-fallback-test are -// linked together, we define each implementation with a different name and define an alias to the -// one we want to use. - -#elif defined(__BYTE_ORDER__) && \ - __BYTE_ORDER__ == CAPNP_OPPOSITE_OF_WIRE_BYTE_ORDER && \ - defined(__GNUC__) && !CAPNP_DISABLE_ENDIAN_DETECTION -// Big-endian, but GCC's __builtin_bswap() is available. - -// TODO(perf): Use dedicated instructions to read little-endian data on big-endian CPUs that have -// them. - -// TODO(perf): Verify that this code optimizes reasonably. In particular, ensure that the -// compiler optimizes away the memcpy()s and keeps everything in registers. - -template -class SwappingWireValue; - -template -class SwappingWireValue { -public: - KJ_ALWAYS_INLINE(T get() const) { return value; } - KJ_ALWAYS_INLINE(void set(T newValue)) { value = newValue; } - -private: - T value; -}; - -template -class SwappingWireValue { -public: - KJ_ALWAYS_INLINE(T get() const) { - // Not all platforms have __builtin_bswap16() for some reason. In particular, it is missing - // on gcc-4.7.3-cygwin32 (but present on gcc-4.8.1-cygwin64). - uint16_t swapped = (value << 8) | (value >> 8); - T result; - memcpy(&result, &swapped, sizeof(T)); - return result; - } - KJ_ALWAYS_INLINE(void set(T newValue)) { - uint16_t raw; - memcpy(&raw, &newValue, sizeof(T)); - // Not all platforms have __builtin_bswap16() for some reason. In particular, it is missing - // on gcc-4.7.3-cygwin32 (but present on gcc-4.8.1-cygwin64). - value = (raw << 8) | (raw >> 8); - } - -private: - uint16_t value; -}; - -template -class SwappingWireValue { -public: - KJ_ALWAYS_INLINE(T get() const) { - uint32_t swapped = __builtin_bswap32(value); - T result; - memcpy(&result, &swapped, sizeof(T)); - return result; - } - KJ_ALWAYS_INLINE(void set(T newValue)) { - uint32_t raw; - memcpy(&raw, &newValue, sizeof(T)); - value = __builtin_bswap32(raw); - } - -private: - uint32_t value; -}; - -template -class SwappingWireValue { -public: - KJ_ALWAYS_INLINE(T get() const) { - uint64_t swapped = __builtin_bswap64(value); - T result; - memcpy(&result, &swapped, sizeof(T)); - return result; - } - KJ_ALWAYS_INLINE(void set(T newValue)) { - uint64_t raw; - memcpy(&raw, &newValue, sizeof(T)); - value = __builtin_bswap64(raw); - } - -private: - uint64_t value; -}; - -template -using WireValue = SwappingWireValue; -// To prevent ODR problems when endian-test, endian-reverse-test, and endian-fallback-test are -// linked together, we define each implementation with a different name and define an alias to the -// one we want to use. - -#else -// Unknown endianness. Fall back to bit shifts. - -#if !CAPNP_DISABLE_ENDIAN_DETECTION -#if _MSC_VER -#pragma message("Couldn't detect endianness of your platform. Using unoptimized fallback implementation.") -#pragma message("Consider changing this code to detect your platform and send us a patch!") -#else -#warning "Couldn't detect endianness of your platform. Using unoptimized fallback implementation." -#warning "Consider changing this code to detect your platform and send us a patch!" -#endif -#endif // !CAPNP_DISABLE_ENDIAN_DETECTION - -template -class ShiftingWireValue; - -template -class ShiftingWireValue { -public: - KJ_ALWAYS_INLINE(T get() const) { return value; } - KJ_ALWAYS_INLINE(void set(T newValue)) { value = newValue; } - -private: - T value; -}; - -template -class ShiftingWireValue { -public: - KJ_ALWAYS_INLINE(T get() const) { - uint16_t raw = (static_cast(bytes[0]) ) | - (static_cast(bytes[1]) << 8); - T result; - memcpy(&result, &raw, sizeof(T)); - return result; - } - KJ_ALWAYS_INLINE(void set(T newValue)) { - uint16_t raw; - memcpy(&raw, &newValue, sizeof(T)); - bytes[0] = raw; - bytes[1] = raw >> 8; - } - -private: - union { - byte bytes[2]; - uint16_t align; - }; -}; - -template -class ShiftingWireValue { -public: - KJ_ALWAYS_INLINE(T get() const) { - uint32_t raw = (static_cast(bytes[0]) ) | - (static_cast(bytes[1]) << 8) | - (static_cast(bytes[2]) << 16) | - (static_cast(bytes[3]) << 24); - T result; - memcpy(&result, &raw, sizeof(T)); - return result; - } - KJ_ALWAYS_INLINE(void set(T newValue)) { - uint32_t raw; - memcpy(&raw, &newValue, sizeof(T)); - bytes[0] = raw; - bytes[1] = raw >> 8; - bytes[2] = raw >> 16; - bytes[3] = raw >> 24; - } - -private: - union { - byte bytes[4]; - uint32_t align; - }; -}; - -template -class ShiftingWireValue { -public: - KJ_ALWAYS_INLINE(T get() const) { - uint64_t raw = (static_cast(bytes[0]) ) | - (static_cast(bytes[1]) << 8) | - (static_cast(bytes[2]) << 16) | - (static_cast(bytes[3]) << 24) | - (static_cast(bytes[4]) << 32) | - (static_cast(bytes[5]) << 40) | - (static_cast(bytes[6]) << 48) | - (static_cast(bytes[7]) << 56); - T result; - memcpy(&result, &raw, sizeof(T)); - return result; - } - KJ_ALWAYS_INLINE(void set(T newValue)) { - uint64_t raw; - memcpy(&raw, &newValue, sizeof(T)); - bytes[0] = raw; - bytes[1] = raw >> 8; - bytes[2] = raw >> 16; - bytes[3] = raw >> 24; - bytes[4] = raw >> 32; - bytes[5] = raw >> 40; - bytes[6] = raw >> 48; - bytes[7] = raw >> 56; - } - -private: - union { - byte bytes[8]; - uint64_t align; - }; -}; - -template -using WireValue = ShiftingWireValue; -// To prevent ODR problems when endian-test, endian-reverse-test, and endian-fallback-test are -// linked together, we define each implementation with a different name and define an alias to the -// one we want to use. - -#endif - -} // namespace _ (private) -} // namespace capnp - -#endif // CAPNP_ENDIAN_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/ez-rpc.h b/phonelibs/capnp-cpp/include/capnp/ez-rpc.h deleted file mode 100644 index fba5ace582..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/ez-rpc.h +++ /dev/null @@ -1,254 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_EZ_RPC_H_ -#define CAPNP_EZ_RPC_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include "rpc.h" -#include "message.h" - -struct sockaddr; - -namespace kj { class AsyncIoProvider; class LowLevelAsyncIoProvider; } - -namespace capnp { - -class EzRpcContext; - -class EzRpcClient { - // Super-simple interface for setting up a Cap'n Proto RPC client. Example: - // - // # Cap'n Proto schema - // interface Adder { - // add @0 (left :Int32, right :Int32) -> (value :Int32); - // } - // - // // C++ client - // int main() { - // capnp::EzRpcClient client("localhost:3456"); - // Adder::Client adder = client.getMain(); - // auto request = adder.addRequest(); - // request.setLeft(12); - // request.setRight(34); - // auto response = request.send().wait(client.getWaitScope()); - // assert(response.getValue() == 46); - // return 0; - // } - // - // // C++ server - // class AdderImpl final: public Adder::Server { - // public: - // kj::Promise add(AddContext context) override { - // auto params = context.getParams(); - // context.getResults().setValue(params.getLeft() + params.getRight()); - // return kj::READY_NOW; - // } - // }; - // - // int main() { - // capnp::EzRpcServer server(kj::heap(), "*:3456"); - // kj::NEVER_DONE.wait(server.getWaitScope()); - // } - // - // This interface is easy, but it hides a lot of useful features available from the lower-level - // classes: - // - The server can only export a small set of public, singleton capabilities under well-known - // string names. This is fine for transient services where no state needs to be kept between - // connections, but hides the power of Cap'n Proto when it comes to long-lived resources. - // - EzRpcClient/EzRpcServer automatically set up a `kj::EventLoop` and make it current for the - // thread. Only one `kj::EventLoop` can exist per thread, so you cannot use these interfaces - // if you wish to set up your own event loop. (However, you can safely create multiple - // EzRpcClient / EzRpcServer objects in a single thread; they will make sure to make no more - // than one EventLoop.) - // - These classes only support simple two-party connections, not multilateral VatNetworks. - // - These classes only support communication over a raw, unencrypted socket. If you want to - // build on an abstract stream (perhaps one which supports encryption), you must use the - // lower-level interfaces. - // - // Some of these restrictions will probably be lifted in future versions, but some things will - // always require using the low-level interfaces directly. If you are interested in working - // at a lower level, start by looking at these interfaces: - // - `kj::setupAsyncIo()` in `kj/async-io.h`. - // - `RpcSystem` in `capnp/rpc.h`. - // - `TwoPartyVatNetwork` in `capnp/rpc-twoparty.h`. - -public: - explicit EzRpcClient(kj::StringPtr serverAddress, uint defaultPort = 0, - ReaderOptions readerOpts = ReaderOptions()); - // Construct a new EzRpcClient and connect to the given address. The connection is formed in - // the background -- if it fails, calls to capabilities returned by importCap() will fail with an - // appropriate exception. - // - // `defaultPort` is the IP port number to use if `serverAddress` does not include it explicitly. - // If unspecified, the port is required in `serverAddress`. - // - // The address is parsed by `kj::Network` in `kj/async-io.h`. See that interface for more info - // on the address format, but basically it's what you'd expect. - // - // `readerOpts` is the ReaderOptions structure used to read each incoming message on the - // connection. Setting this may be necessary if you need to receive very large individual - // messages or messages. However, it is recommended that you instead think about how to change - // your protocol to send large data blobs in multiple small chunks -- this is much better for - // both security and performance. See `ReaderOptions` in `message.h` for more details. - - EzRpcClient(const struct sockaddr* serverAddress, uint addrSize, - ReaderOptions readerOpts = ReaderOptions()); - // Like the above constructor, but connects to an already-resolved socket address. Any address - // format supported by `kj::Network` in `kj/async-io.h` is accepted. - - explicit EzRpcClient(int socketFd, ReaderOptions readerOpts = ReaderOptions()); - // Create a client on top of an already-connected socket. - // `readerOpts` acts as in the first constructor. - - ~EzRpcClient() noexcept(false); - - template - typename Type::Client getMain(); - Capability::Client getMain(); - // Get the server's main (aka "bootstrap") interface. - - template - typename Type::Client importCap(kj::StringPtr name) - KJ_DEPRECATED("Change your server to export a main interface, then use getMain() instead."); - Capability::Client importCap(kj::StringPtr name) - KJ_DEPRECATED("Change your server to export a main interface, then use getMain() instead."); - // ** DEPRECATED ** - // - // Ask the sever for the capability with the given name. You may specify a type to automatically - // down-cast to that type. It is up to you to specify the correct expected type. - // - // Named interfaces are deprecated. The new preferred usage pattern is for the server to export - // a "main" interface which itself has methods for getting any other interfaces. - - kj::WaitScope& getWaitScope(); - // Get the `WaitScope` for the client's `EventLoop`, which allows you to synchronously wait on - // promises. - - kj::AsyncIoProvider& getIoProvider(); - // Get the underlying AsyncIoProvider set up by the RPC system. This is useful if you want - // to do some non-RPC I/O in asynchronous fashion. - - kj::LowLevelAsyncIoProvider& getLowLevelIoProvider(); - // Get the underlying LowLevelAsyncIoProvider set up by the RPC system. This is useful if you - // want to do some non-RPC I/O in asynchronous fashion. - -private: - struct Impl; - kj::Own impl; -}; - -class EzRpcServer { - // The server counterpart to `EzRpcClient`. See `EzRpcClient` for an example. - -public: - explicit EzRpcServer(Capability::Client mainInterface, kj::StringPtr bindAddress, - uint defaultPort = 0, ReaderOptions readerOpts = ReaderOptions()); - // Construct a new `EzRpcServer` that binds to the given address. An address of "*" means to - // bind to all local addresses. - // - // `defaultPort` is the IP port number to use if `serverAddress` does not include it explicitly. - // If unspecified, a port is chosen automatically, and you must call getPort() to find out what - // it is. - // - // The address is parsed by `kj::Network` in `kj/async-io.h`. See that interface for more info - // on the address format, but basically it's what you'd expect. - // - // The server might not begin listening immediately, especially if `bindAddress` needs to be - // resolved. If you need to wait until the server is definitely up, wait on the promise returned - // by `getPort()`. - // - // `readerOpts` is the ReaderOptions structure used to read each incoming message on the - // connection. Setting this may be necessary if you need to receive very large individual - // messages or messages. However, it is recommended that you instead think about how to change - // your protocol to send large data blobs in multiple small chunks -- this is much better for - // both security and performance. See `ReaderOptions` in `message.h` for more details. - - EzRpcServer(Capability::Client mainInterface, struct sockaddr* bindAddress, uint addrSize, - ReaderOptions readerOpts = ReaderOptions()); - // Like the above constructor, but binds to an already-resolved socket address. Any address - // format supported by `kj::Network` in `kj/async-io.h` is accepted. - - EzRpcServer(Capability::Client mainInterface, int socketFd, uint port, - ReaderOptions readerOpts = ReaderOptions()); - // Create a server on top of an already-listening socket (i.e. one on which accept() may be - // called). `port` is returned by `getPort()` -- it serves no other purpose. - // `readerOpts` acts as in the other two above constructors. - - explicit EzRpcServer(kj::StringPtr bindAddress, uint defaultPort = 0, - ReaderOptions readerOpts = ReaderOptions()) - KJ_DEPRECATED("Please specify a main interface for your server."); - EzRpcServer(struct sockaddr* bindAddress, uint addrSize, - ReaderOptions readerOpts = ReaderOptions()) - KJ_DEPRECATED("Please specify a main interface for your server."); - EzRpcServer(int socketFd, uint port, ReaderOptions readerOpts = ReaderOptions()) - KJ_DEPRECATED("Please specify a main interface for your server."); - - ~EzRpcServer() noexcept(false); - - void exportCap(kj::StringPtr name, Capability::Client cap); - // Export a capability publicly under the given name, so that clients can import it. - // - // Keep in mind that you can implicitly convert `kj::Own&&` to - // `Capability::Client`, so it's typical to pass something like - // `kj::heap()` as the second parameter. - - kj::Promise getPort(); - // Get the IP port number on which this server is listening. This promise won't resolve until - // the server is actually listening. If the address was not an IP address (e.g. it was a Unix - // domain socket) then getPort() resolves to zero. - - kj::WaitScope& getWaitScope(); - // Get the `WaitScope` for the client's `EventLoop`, which allows you to synchronously wait on - // promises. - - kj::AsyncIoProvider& getIoProvider(); - // Get the underlying AsyncIoProvider set up by the RPC system. This is useful if you want - // to do some non-RPC I/O in asynchronous fashion. - - kj::LowLevelAsyncIoProvider& getLowLevelIoProvider(); - // Get the underlying LowLevelAsyncIoProvider set up by the RPC system. This is useful if you - // want to do some non-RPC I/O in asynchronous fashion. - -private: - struct Impl; - kj::Own impl; -}; - -// ======================================================================================= -// inline implementation details - -template -inline typename Type::Client EzRpcClient::getMain() { - return getMain().castAs(); -} - -template -inline typename Type::Client EzRpcClient::importCap(kj::StringPtr name) { - return importCap(name).castAs(); -} - -} // namespace capnp - -#endif // CAPNP_EZ_RPC_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/generated-header-support.h b/phonelibs/capnp-cpp/include/capnp/generated-header-support.h deleted file mode 100644 index 51b6dd7c11..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/generated-header-support.h +++ /dev/null @@ -1,407 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// This file is included from all generated headers. - -#ifndef CAPNP_GENERATED_HEADER_SUPPORT_H_ -#define CAPNP_GENERATED_HEADER_SUPPORT_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include "raw-schema.h" -#include "layout.h" -#include "list.h" -#include "orphan.h" -#include "pointer-helpers.h" -#include "any.h" -#include -#include - -namespace capnp { - -class MessageBuilder; // So that it can be declared a friend. - -template -struct ToDynamic_; // Defined in dynamic.h, needs to be declared as everyone's friend. - -struct DynamicStruct; // So that it can be declared a friend. - -struct Capability; // To declare brandBindingFor() - -namespace _ { // private - -#if !CAPNP_LITE - -template -inline const RawSchema& rawSchema() { - return *CapnpPrivate::schema; -} -template ::typeId> -inline const RawSchema& rawSchema() { - return *schemas::EnumInfo::schema; -} - -template -inline const RawBrandedSchema& rawBrandedSchema() { - return *CapnpPrivate::brand(); -} -template ::typeId> -inline const RawBrandedSchema& rawBrandedSchema() { - return schemas::EnumInfo::schema->defaultBrand; -} - -template -struct ChooseBrand; -// If all of `Params` are `AnyPointer`, return the type's default brand. Otherwise, return a -// specific brand instance. TypeTag is the _capnpPrivate struct for the type in question. - -template -struct ChooseBrand { - // All params were AnyPointer. No specific brand needed. - static constexpr _::RawBrandedSchema const* brand() { return &TypeTag::schema->defaultBrand; } -}; - -template -struct ChooseBrand: public ChooseBrand {}; -// The first parameter is AnyPointer, so recurse to check the rest. - -template -struct ChooseBrand { - // At least one parameter is not AnyPointer, so use the specificBrand constant. - static constexpr _::RawBrandedSchema const* brand() { return &TypeTag::specificBrand; } -}; - -template ()> -struct BrandBindingFor_; - -#define HANDLE_TYPE(Type, which) \ - template <> \ - struct BrandBindingFor_ { \ - static constexpr RawBrandedSchema::Binding get(uint16_t listDepth) { \ - return { which, listDepth, nullptr }; \ - } \ - } -HANDLE_TYPE(Void, 0); -HANDLE_TYPE(bool, 1); -HANDLE_TYPE(int8_t, 2); -HANDLE_TYPE(int16_t, 3); -HANDLE_TYPE(int32_t, 4); -HANDLE_TYPE(int64_t, 5); -HANDLE_TYPE(uint8_t, 6); -HANDLE_TYPE(uint16_t, 7); -HANDLE_TYPE(uint32_t, 8); -HANDLE_TYPE(uint64_t, 9); -HANDLE_TYPE(float, 10); -HANDLE_TYPE(double, 11); -#undef HANDLE_TYPE - -template <> -struct BrandBindingFor_ { - static constexpr RawBrandedSchema::Binding get(uint16_t listDepth) { - return { 12, listDepth, nullptr }; - } -}; - -template <> -struct BrandBindingFor_ { - static constexpr RawBrandedSchema::Binding get(uint16_t listDepth) { - return { 13, listDepth, nullptr }; - } -}; - -template -struct BrandBindingFor_, Kind::LIST> { - static constexpr RawBrandedSchema::Binding get(uint16_t listDepth) { - return BrandBindingFor_::get(listDepth + 1); - } -}; - -template -struct BrandBindingFor_ { - static constexpr RawBrandedSchema::Binding get(uint16_t listDepth) { - return { 15, listDepth, nullptr }; - } -}; - -template -struct BrandBindingFor_ { - static constexpr RawBrandedSchema::Binding get(uint16_t listDepth) { - return { 16, listDepth, T::_capnpPrivate::brand() }; - } -}; - -template -struct BrandBindingFor_ { - static constexpr RawBrandedSchema::Binding get(uint16_t listDepth) { - return { 17, listDepth, T::_capnpPrivate::brand() }; - } -}; - -template <> -struct BrandBindingFor_ { - static constexpr RawBrandedSchema::Binding get(uint16_t listDepth) { - return { 18, listDepth, 0, 0 }; - } -}; - -template <> -struct BrandBindingFor_ { - static constexpr RawBrandedSchema::Binding get(uint16_t listDepth) { - return { 18, listDepth, 0, 1 }; - } -}; - -template <> -struct BrandBindingFor_ { - static constexpr RawBrandedSchema::Binding get(uint16_t listDepth) { - return { 18, listDepth, 0, 2 }; - } -}; - -template <> -struct BrandBindingFor_ { - static constexpr RawBrandedSchema::Binding get(uint16_t listDepth) { - return { 18, listDepth, 0, 3 }; - } -}; - -template -constexpr RawBrandedSchema::Binding brandBindingFor() { - return BrandBindingFor_::get(0); -} - -kj::StringTree structString(StructReader reader, const RawBrandedSchema& schema); -kj::String enumString(uint16_t value, const RawBrandedSchema& schema); -// Declared here so that we can declare inline stringify methods on generated types. -// Defined in stringify.c++, which depends on dynamic.c++, which is allowed not to be linked in. - -template -inline kj::StringTree structString(StructReader reader) { - return structString(reader, rawBrandedSchema()); -} -template -inline kj::String enumString(T value) { - return enumString(static_cast(value), rawBrandedSchema()); -} - -#endif // !CAPNP_LITE - -// TODO(cleanup): Unify ConstStruct and ConstList. -template -class ConstStruct { -public: - ConstStruct() = delete; - KJ_DISALLOW_COPY(ConstStruct); - inline explicit constexpr ConstStruct(const word* ptr): ptr(ptr) {} - - inline typename T::Reader get() const { - return AnyPointer::Reader(PointerReader::getRootUnchecked(ptr)).getAs(); - } - - inline operator typename T::Reader() const { return get(); } - inline typename T::Reader operator*() const { return get(); } - inline TemporaryPointer operator->() const { return get(); } - -private: - const word* ptr; -}; - -template -class ConstList { -public: - ConstList() = delete; - KJ_DISALLOW_COPY(ConstList); - inline explicit constexpr ConstList(const word* ptr): ptr(ptr) {} - - inline typename List::Reader get() const { - return AnyPointer::Reader(PointerReader::getRootUnchecked(ptr)).getAs>(); - } - - inline operator typename List::Reader() const { return get(); } - inline typename List::Reader operator*() const { return get(); } - inline TemporaryPointer::Reader> operator->() const { return get(); } - -private: - const word* ptr; -}; - -template -class ConstText { -public: - ConstText() = delete; - KJ_DISALLOW_COPY(ConstText); - inline explicit constexpr ConstText(const word* ptr): ptr(ptr) {} - - inline Text::Reader get() const { - return Text::Reader(reinterpret_cast(ptr), size); - } - - inline operator Text::Reader() const { return get(); } - inline Text::Reader operator*() const { return get(); } - inline TemporaryPointer operator->() const { return get(); } - - inline kj::StringPtr toString() const { - return get(); - } - -private: - const word* ptr; -}; - -template -inline kj::StringPtr KJ_STRINGIFY(const ConstText& s) { - return s.get(); -} - -template -class ConstData { -public: - ConstData() = delete; - KJ_DISALLOW_COPY(ConstData); - inline explicit constexpr ConstData(const word* ptr): ptr(ptr) {} - - inline Data::Reader get() const { - return Data::Reader(reinterpret_cast(ptr), size); - } - - inline operator Data::Reader() const { return get(); } - inline Data::Reader operator*() const { return get(); } - inline TemporaryPointer operator->() const { return get(); } - -private: - const word* ptr; -}; - -template -inline auto KJ_STRINGIFY(const ConstData& s) -> decltype(kj::toCharSequence(s.get())) { - return kj::toCharSequence(s.get()); -} - -} // namespace _ (private) - -template -inline constexpr uint64_t typeId() { return CapnpPrivate::typeId; } -template ::typeId> -inline constexpr uint64_t typeId() { return id; } -// typeId() returns the type ID as defined in the schema. Works with structs, enums, and -// interfaces. - -template -inline constexpr uint sizeInWords() { - // Return the size, in words, of a Struct type, if allocated free-standing (not in a list). - // May be useful for pre-computing space needed in order to precisely allocate messages. - - return unbound((upgradeBound(_::structSize().data) + - _::structSize().pointers * WORDS_PER_POINTER) / WORDS); -} - -} // namespace capnp - -#if _MSC_VER -// MSVC doesn't understand floating-point constexpr yet. -// -// TODO(msvc): Remove this hack when MSVC is fixed. -#define CAPNP_NON_INT_CONSTEXPR_DECL_INIT(value) -#define CAPNP_NON_INT_CONSTEXPR_DEF_INIT(value) = value -#else -#define CAPNP_NON_INT_CONSTEXPR_DECL_INIT(value) = value -#define CAPNP_NON_INT_CONSTEXPR_DEF_INIT(value) -#endif - -#if _MSC_VER -// TODO(msvc): A little hack to allow MSVC to use C++14 return type deduction in cases where the -// explicit type exposes bugs in the compiler. -#define CAPNP_AUTO_IF_MSVC(...) auto -#else -#define CAPNP_AUTO_IF_MSVC(...) __VA_ARGS__ -#endif - -#if CAPNP_LITE - -#define CAPNP_DECLARE_SCHEMA(id) \ - extern ::capnp::word const* const bp_##id - -#define CAPNP_DECLARE_ENUM(type, id) \ - inline ::kj::String KJ_STRINGIFY(type##_##id value) { \ - return ::kj::str(static_cast(value)); \ - } \ - template <> struct EnumInfo { \ - struct IsEnum; \ - static constexpr uint64_t typeId = 0x##id; \ - static inline ::capnp::word const* encodedSchema() { return bp_##id; } \ - } - -#if _MSC_VER -// TODO(msvc): MSVC dosen't expect constexprs to have definitions. -#define CAPNP_DEFINE_ENUM(type, id) -#else -#define CAPNP_DEFINE_ENUM(type, id) \ - constexpr uint64_t EnumInfo::typeId -#endif - -#define CAPNP_DECLARE_STRUCT_HEADER(id, dataWordSize_, pointerCount_) \ - struct IsStruct; \ - static constexpr uint64_t typeId = 0x##id; \ - static constexpr uint16_t dataWordSize = dataWordSize_; \ - static constexpr uint16_t pointerCount = pointerCount_; \ - static inline ::capnp::word const* encodedSchema() { return ::capnp::schemas::bp_##id; } - -#else // CAPNP_LITE - -#define CAPNP_DECLARE_SCHEMA(id) \ - extern ::capnp::word const* const bp_##id; \ - extern const ::capnp::_::RawSchema s_##id - -#define CAPNP_DECLARE_ENUM(type, id) \ - inline ::kj::String KJ_STRINGIFY(type##_##id value) { \ - return ::capnp::_::enumString(value); \ - } \ - template <> struct EnumInfo { \ - struct IsEnum; \ - static constexpr uint64_t typeId = 0x##id; \ - static inline ::capnp::word const* encodedSchema() { return bp_##id; } \ - static constexpr ::capnp::_::RawSchema const* schema = &s_##id; \ - } -#define CAPNP_DEFINE_ENUM(type, id) \ - constexpr uint64_t EnumInfo::typeId; \ - constexpr ::capnp::_::RawSchema const* EnumInfo::schema - -#define CAPNP_DECLARE_STRUCT_HEADER(id, dataWordSize_, pointerCount_) \ - struct IsStruct; \ - static constexpr uint64_t typeId = 0x##id; \ - static constexpr ::capnp::Kind kind = ::capnp::Kind::STRUCT; \ - static constexpr uint16_t dataWordSize = dataWordSize_; \ - static constexpr uint16_t pointerCount = pointerCount_; \ - static inline ::capnp::word const* encodedSchema() { return ::capnp::schemas::bp_##id; } \ - static constexpr ::capnp::_::RawSchema const* schema = &::capnp::schemas::s_##id; - -#define CAPNP_DECLARE_INTERFACE_HEADER(id) \ - struct IsInterface; \ - static constexpr uint64_t typeId = 0x##id; \ - static constexpr ::capnp::Kind kind = ::capnp::Kind::INTERFACE; \ - static inline ::capnp::word const* encodedSchema() { return ::capnp::schemas::bp_##id; } \ - static constexpr ::capnp::_::RawSchema const* schema = &::capnp::schemas::s_##id; - -#endif // CAPNP_LITE, else - -#endif // CAPNP_GENERATED_HEADER_SUPPORT_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/json.capnp b/phonelibs/capnp-cpp/include/capnp/json.capnp deleted file mode 100644 index 55188736f8..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/json.capnp +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright (c) 2015 Sandstorm Development Group, Inc. and contributors -# Licensed under the MIT License: -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -@0x8ef99297a43a5e34; - -$import "/capnp/c++.capnp".namespace("capnp"); - -struct JsonValue { - union { - null @0 :Void; - boolean @1 :Bool; - number @2 :Float64; - string @3 :Text; - array @4 :List(JsonValue); - object @5 :List(Field); - # Standard JSON values. - - call @6 :Call; - # Non-standard: A "function call", applying a named function (named by a single identifier) - # to a parameter list. Examples: - # - # BinData(0, "Zm9vCg==") - # ISODate("2015-04-15T08:44:50.218Z") - # - # Mongo DB users will recognize the above as exactly the syntax Mongo uses to represent BSON - # "binary" and "date" types in text, since JSON has no analog of these. This is basically the - # reason this extension exists. We do NOT recommend using `call` unless you specifically need - # to be compatible with some silly format that uses this syntax. - } - - struct Field { - name @0 :Text; - value @1 :JsonValue; - } - - struct Call { - function @0 :Text; - params @1 :List(JsonValue); - } -} diff --git a/phonelibs/capnp-cpp/include/capnp/layout.h b/phonelibs/capnp-cpp/include/capnp/layout.h deleted file mode 100644 index 99dc533b2b..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/layout.h +++ /dev/null @@ -1,1274 +0,0 @@ -// Copyright (c) 2013-2016 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// This file is NOT intended for use by clients, except in generated code. -// -// This file defines low-level, non-type-safe classes for traversing the Cap'n Proto memory layout -// (which is also its wire format). Code generated by the Cap'n Proto compiler uses these classes, -// as does other parts of the Cap'n proto library which provide a higher-level interface for -// dynamic introspection. - -#ifndef CAPNP_LAYOUT_H_ -#define CAPNP_LAYOUT_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include -#include -#include "common.h" -#include "blob.h" -#include "endian.h" - -#if (defined(__mips__) || defined(__hppa__)) && !defined(CAPNP_CANONICALIZE_NAN) -#define CAPNP_CANONICALIZE_NAN 1 -// Explicitly detect NaNs and canonicalize them to the quiet NaN value as would be returned by -// __builtin_nan("") on systems implementing the IEEE-754 recommended (but not required) NaN -// signalling/quiet differentiation (such as x86). Unfortunately, some architectures -- in -// particular, MIPS -- represent quiet vs. signalling nans differently than the rest of the world. -// Canonicalizing them makes output consistent (which is important!), but hurts performance -// slightly. -// -// Note that trying to convert MIPS NaNs to standard NaNs without losing data doesn't work. -// Signaling vs. quiet is indicated by a bit, with the meaning being the opposite on MIPS vs. -// everyone else. It would be great if we could just flip that bit, but we can't, because if the -// significand is all-zero, then the value is infinity rather than NaN. This means that on most -// machines, where the bit indicates quietness, there is one more quiet NaN value than signalling -// NaN value, whereas on MIPS there is one more sNaN than qNaN, and thus there is no isomorphic -// mapping that properly preserves quietness. Instead of doing something hacky, we just give up -// and blow away NaN payloads, because no one uses them anyway. -#endif - -namespace capnp { - -#if !CAPNP_LITE -class ClientHook; -#endif // !CAPNP_LITE - -namespace _ { // private - -class PointerBuilder; -class PointerReader; -class StructBuilder; -class StructReader; -class ListBuilder; -class ListReader; -class OrphanBuilder; -struct WirePointer; -struct WireHelpers; -class SegmentReader; -class SegmentBuilder; -class Arena; -class BuilderArena; - -// ============================================================================= - -#if CAPNP_DEBUG_TYPES -typedef kj::UnitRatio, BitLabel, ElementLabel> BitsPerElementTableType; -#else -typedef uint BitsPerElementTableType; -#endif - -static constexpr BitsPerElementTableType BITS_PER_ELEMENT_TABLE[8] = { - bounded< 0>() * BITS / ELEMENTS, - bounded< 1>() * BITS / ELEMENTS, - bounded< 8>() * BITS / ELEMENTS, - bounded<16>() * BITS / ELEMENTS, - bounded<32>() * BITS / ELEMENTS, - bounded<64>() * BITS / ELEMENTS, - bounded< 0>() * BITS / ELEMENTS, - bounded< 0>() * BITS / ELEMENTS -}; - -inline KJ_CONSTEXPR() BitsPerElementTableType dataBitsPerElement(ElementSize size) { - return _::BITS_PER_ELEMENT_TABLE[static_cast(size)]; -} - -inline constexpr PointersPerElementN<1> pointersPerElement(ElementSize size) { - return size == ElementSize::POINTER - ? PointersPerElementN<1>(ONE * POINTERS / ELEMENTS) - : PointersPerElementN<1>(ZERO * POINTERS / ELEMENTS); -} - -static constexpr BitsPerElementTableType BITS_PER_ELEMENT_INCLUDING_PONITERS_TABLE[8] = { - bounded< 0>() * BITS / ELEMENTS, - bounded< 1>() * BITS / ELEMENTS, - bounded< 8>() * BITS / ELEMENTS, - bounded<16>() * BITS / ELEMENTS, - bounded<32>() * BITS / ELEMENTS, - bounded<64>() * BITS / ELEMENTS, - bounded<64>() * BITS / ELEMENTS, - bounded< 0>() * BITS / ELEMENTS -}; - -inline KJ_CONSTEXPR() BitsPerElementTableType bitsPerElementIncludingPointers(ElementSize size) { - return _::BITS_PER_ELEMENT_INCLUDING_PONITERS_TABLE[static_cast(size)]; -} - -template struct ElementSizeForByteSize; -template <> struct ElementSizeForByteSize<1> { static constexpr ElementSize value = ElementSize::BYTE; }; -template <> struct ElementSizeForByteSize<2> { static constexpr ElementSize value = ElementSize::TWO_BYTES; }; -template <> struct ElementSizeForByteSize<4> { static constexpr ElementSize value = ElementSize::FOUR_BYTES; }; -template <> struct ElementSizeForByteSize<8> { static constexpr ElementSize value = ElementSize::EIGHT_BYTES; }; - -template struct ElementSizeForType { - static constexpr ElementSize value = - // Primitive types that aren't special-cased below can be determined from sizeof(). - CAPNP_KIND(T) == Kind::PRIMITIVE ? ElementSizeForByteSize::value : - CAPNP_KIND(T) == Kind::ENUM ? ElementSize::TWO_BYTES : - CAPNP_KIND(T) == Kind::STRUCT ? ElementSize::INLINE_COMPOSITE : - - // Everything else is a pointer. - ElementSize::POINTER; -}; - -// Void and bool are special. -template <> struct ElementSizeForType { static constexpr ElementSize value = ElementSize::VOID; }; -template <> struct ElementSizeForType { static constexpr ElementSize value = ElementSize::BIT; }; - -// Lists and blobs are pointers, not structs. -template struct ElementSizeForType> { - static constexpr ElementSize value = ElementSize::POINTER; -}; -template <> struct ElementSizeForType { - static constexpr ElementSize value = ElementSize::POINTER; -}; -template <> struct ElementSizeForType { - static constexpr ElementSize value = ElementSize::POINTER; -}; - -template -inline constexpr ElementSize elementSizeForType() { - return ElementSizeForType::value; -} - -struct MessageSizeCounts { - WordCountN<61, uint64_t> wordCount; // 2^64 bytes - uint capCount; - - MessageSizeCounts& operator+=(const MessageSizeCounts& other) { - // OK to truncate unchecked because this class is used to count actual stuff in memory, and - // we couldn't possibly have anywhere near 2^61 words. - wordCount = assumeBits<61>(wordCount + other.wordCount); - capCount += other.capCount; - return *this; - } - - void addWords(WordCountN<61, uint64_t> other) { - wordCount = assumeBits<61>(wordCount + other); - } - - MessageSize asPublic() { - return MessageSize { unbound(wordCount / WORDS), capCount }; - } -}; - -// ============================================================================= - -template -union AlignedData { - // Useful for declaring static constant data blobs as an array of bytes, but forcing those - // bytes to be word-aligned. - - uint8_t bytes[wordCount * sizeof(word)]; - word words[wordCount]; -}; - -struct StructSize { - StructDataWordCount data; - StructPointerCount pointers; - - inline constexpr WordCountN<17> total() const { return data + pointers * WORDS_PER_POINTER; } - - StructSize() = default; - inline constexpr StructSize(StructDataWordCount data, StructPointerCount pointers) - : data(data), pointers(pointers) {} -}; - -template -inline constexpr StructSize structSize() { - return StructSize(bounded(CapnpPrivate::dataWordSize) * WORDS, - bounded(CapnpPrivate::pointerCount) * POINTERS); -} - -template > -inline constexpr StructSize minStructSizeForElement() { - // If T is a struct, return its struct size. Otherwise return the minimum struct size big enough - // to hold a T. - - return StructSize(bounded(CapnpPrivate::dataWordSize) * WORDS, - bounded(CapnpPrivate::pointerCount) * POINTERS); -} - -template > -inline constexpr StructSize minStructSizeForElement() { - // If T is a struct, return its struct size. Otherwise return the minimum struct size big enough - // to hold a T. - - return StructSize( - dataBitsPerElement(elementSizeForType()) * ELEMENTS > ZERO * BITS - ? StructDataWordCount(ONE * WORDS) : StructDataWordCount(ZERO * WORDS), - pointersPerElement(elementSizeForType()) * ELEMENTS); -} - -// ------------------------------------------------------------------- -// Masking of default values - -template struct Mask_; -template struct Mask_ { typedef T Type; }; -template struct Mask_ { typedef uint16_t Type; }; -template <> struct Mask_ { typedef uint32_t Type; }; -template <> struct Mask_ { typedef uint64_t Type; }; - -template struct Mask_ { - // Union discriminants end up here. - static_assert(sizeof(T) == 2, "Don't know how to mask this type."); - typedef uint16_t Type; -}; - -template -using Mask = typename Mask_::Type; - -template -KJ_ALWAYS_INLINE(Mask mask(T value, Mask mask)); -template -KJ_ALWAYS_INLINE(T unmask(Mask value, Mask mask)); - -template -inline Mask mask(T value, Mask mask) { - return static_cast >(value) ^ mask; -} - -template <> -inline uint32_t mask(float value, uint32_t mask) { -#if CAPNP_CANONICALIZE_NAN - if (value != value) { - return 0x7fc00000u ^ mask; - } -#endif - - uint32_t i; - static_assert(sizeof(i) == sizeof(value), "float is not 32 bits?"); - memcpy(&i, &value, sizeof(value)); - return i ^ mask; -} - -template <> -inline uint64_t mask(double value, uint64_t mask) { -#if CAPNP_CANONICALIZE_NAN - if (value != value) { - return 0x7ff8000000000000ull ^ mask; - } -#endif - - uint64_t i; - static_assert(sizeof(i) == sizeof(value), "double is not 64 bits?"); - memcpy(&i, &value, sizeof(value)); - return i ^ mask; -} - -template -inline T unmask(Mask value, Mask mask) { - return static_cast(value ^ mask); -} - -template <> -inline float unmask(uint32_t value, uint32_t mask) { - value ^= mask; - float result; - static_assert(sizeof(result) == sizeof(value), "float is not 32 bits?"); - memcpy(&result, &value, sizeof(value)); - return result; -} - -template <> -inline double unmask(uint64_t value, uint64_t mask) { - value ^= mask; - double result; - static_assert(sizeof(result) == sizeof(value), "double is not 64 bits?"); - memcpy(&result, &value, sizeof(value)); - return result; -} - -// ------------------------------------------------------------------- - -class CapTableReader { -public: -#if !CAPNP_LITE - virtual kj::Maybe> extractCap(uint index) = 0; - // Extract the capability at the given index. If the index is invalid, returns null. -#endif // !CAPNP_LITE -}; - -class CapTableBuilder: public CapTableReader { -public: -#if !CAPNP_LITE - virtual uint injectCap(kj::Own&& cap) = 0; - // Add the capability to the message and return its index. If the same ClientHook is injected - // twice, this may return the same index both times, but in this case dropCap() needs to be - // called an equal number of times to actually remove the cap. - - virtual void dropCap(uint index) = 0; - // Remove a capability injected earlier. Called when the pointer is overwritten or zero'd out. -#endif // !CAPNP_LITE -}; - -// ------------------------------------------------------------------- - -class PointerBuilder: public kj::DisallowConstCopy { - // Represents a single pointer, usually embedded in a struct or a list. - -public: - inline PointerBuilder(): segment(nullptr), capTable(nullptr), pointer(nullptr) {} - - static inline PointerBuilder getRoot( - SegmentBuilder* segment, CapTableBuilder* capTable, word* location); - // Get a PointerBuilder representing a message root located in the given segment at the given - // location. - - inline bool isNull() { return getPointerType() == PointerType::NULL_; } - PointerType getPointerType() const; - - StructBuilder getStruct(StructSize size, const word* defaultValue); - ListBuilder getList(ElementSize elementSize, const word* defaultValue); - ListBuilder getStructList(StructSize elementSize, const word* defaultValue); - ListBuilder getListAnySize(const word* defaultValue); - template typename T::Builder getBlob( - const void* defaultValue, ByteCount defaultSize); -#if !CAPNP_LITE - kj::Own getCapability(); -#endif // !CAPNP_LITE - // Get methods: Get the value. If it is null, initialize it to a copy of the default value. - // The default value is encoded as an "unchecked message" for structs, lists, and objects, or a - // simple byte array for blobs. - - StructBuilder initStruct(StructSize size); - ListBuilder initList(ElementSize elementSize, ElementCount elementCount); - ListBuilder initStructList(ElementCount elementCount, StructSize size); - template typename T::Builder initBlob(ByteCount size); - // Init methods: Initialize the pointer to a newly-allocated object, discarding the existing - // object. - - void setStruct(const StructReader& value, bool canonical = false); - void setList(const ListReader& value, bool canonical = false); - template void setBlob(typename T::Reader value); -#if !CAPNP_LITE - void setCapability(kj::Own&& cap); -#endif // !CAPNP_LITE - // Set methods: Initialize the pointer to a newly-allocated copy of the given value, discarding - // the existing object. - - void adopt(OrphanBuilder&& orphan); - // Set the pointer to point at the given orphaned value. - - OrphanBuilder disown(); - // Set the pointer to null and return its previous value as an orphan. - - void clear(); - // Clear the pointer to null, discarding its previous value. - - void transferFrom(PointerBuilder other); - // Equivalent to `adopt(other.disown())`. - - void copyFrom(PointerReader other, bool canonical = false); - // Equivalent to `set(other.get())`. - // If you set the canonical flag, it will attempt to lay the target out - // canonically, provided enough space is available. - - PointerReader asReader() const; - - BuilderArena* getArena() const; - // Get the arena containing this pointer. - - CapTableBuilder* getCapTable(); - // Gets the capability context in which this object is operating. - - PointerBuilder imbue(CapTableBuilder* capTable); - // Return a copy of this builder except using the given capability context. - -private: - SegmentBuilder* segment; // Memory segment in which the pointer resides. - CapTableBuilder* capTable; // Table of capability indexes. - WirePointer* pointer; // Pointer to the pointer. - - inline PointerBuilder(SegmentBuilder* segment, CapTableBuilder* capTable, WirePointer* pointer) - : segment(segment), capTable(capTable), pointer(pointer) {} - - friend class StructBuilder; - friend class ListBuilder; - friend class OrphanBuilder; -}; - -class PointerReader { -public: - inline PointerReader() - : segment(nullptr), capTable(nullptr), pointer(nullptr), nestingLimit(0x7fffffff) {} - - static PointerReader getRoot(SegmentReader* segment, CapTableReader* capTable, - const word* location, int nestingLimit); - // Get a PointerReader representing a message root located in the given segment at the given - // location. - - static inline PointerReader getRootUnchecked(const word* location); - // Get a PointerReader for an unchecked message. - - MessageSizeCounts targetSize() const; - // Return the total size of the target object and everything to which it points. Does not count - // far pointer overhead. This is useful for deciding how much space is needed to copy the object - // into a flat array. However, the caller is advised NOT to treat this value as secure. Instead, - // use the result as a hint for allocating the first segment, do the copy, and then throw an - // exception if it overruns. - - inline bool isNull() const { return getPointerType() == PointerType::NULL_; } - PointerType getPointerType() const; - - StructReader getStruct(const word* defaultValue) const; - ListReader getList(ElementSize expectedElementSize, const word* defaultValue) const; - ListReader getListAnySize(const word* defaultValue) const; - template - typename T::Reader getBlob(const void* defaultValue, ByteCount defaultSize) const; -#if !CAPNP_LITE - kj::Own getCapability() const; -#endif // !CAPNP_LITE - // Get methods: Get the value. If it is null, return the default value instead. - // The default value is encoded as an "unchecked message" for structs, lists, and objects, or a - // simple byte array for blobs. - - const word* getUnchecked() const; - // If this is an unchecked message, get a word* pointing at the location of the pointer. This - // word* can actually be passed to readUnchecked() to read the designated sub-object later. If - // this isn't an unchecked message, throws an exception. - - kj::Maybe getArena() const; - // Get the arena containing this pointer. - - CapTableReader* getCapTable(); - // Gets the capability context in which this object is operating. - - PointerReader imbue(CapTableReader* capTable) const; - // Return a copy of this reader except using the given capability context. - - bool isCanonical(const word **readHead); - // Validate this pointer's canonicity, subject to the conditions: - // * All data to the left of readHead has been read thus far (for pointer - // ordering) - // * All pointers in preorder have already been checked - // * This pointer is in the first and only segment of the message - -private: - SegmentReader* segment; // Memory segment in which the pointer resides. - CapTableReader* capTable; // Table of capability indexes. - const WirePointer* pointer; // Pointer to the pointer. null = treat as null pointer. - - int nestingLimit; - // Limits the depth of message structures to guard against stack-overflow-based DoS attacks. - // Once this reaches zero, further pointers will be pruned. - - inline PointerReader(SegmentReader* segment, CapTableReader* capTable, - const WirePointer* pointer, int nestingLimit) - : segment(segment), capTable(capTable), pointer(pointer), nestingLimit(nestingLimit) {} - - friend class StructReader; - friend class ListReader; - friend class PointerBuilder; - friend class OrphanBuilder; -}; - -// ------------------------------------------------------------------- - -class StructBuilder: public kj::DisallowConstCopy { -public: - inline StructBuilder(): segment(nullptr), capTable(nullptr), data(nullptr), pointers(nullptr) {} - - inline word* getLocation() { return reinterpret_cast(data); } - // Get the object's location. Only valid for independently-allocated objects (i.e. not list - // elements). - - inline StructDataBitCount getDataSectionSize() const { return dataSize; } - inline StructPointerCount getPointerSectionSize() const { return pointerCount; } - inline kj::ArrayPtr getDataSectionAsBlob(); - inline _::ListBuilder getPointerSectionAsList(); - - template - KJ_ALWAYS_INLINE(bool hasDataField(StructDataOffset offset)); - // Return true if the field is set to something other than its default value. - - template - KJ_ALWAYS_INLINE(T getDataField(StructDataOffset offset)); - // Gets the data field value of the given type at the given offset. The offset is measured in - // multiples of the field size, determined by the type. - - template - KJ_ALWAYS_INLINE(T getDataField(StructDataOffset offset, Mask mask)); - // Like getDataField() but applies the given XOR mask to the data on load. Used for reading - // fields with non-zero default values. - - template - KJ_ALWAYS_INLINE(void setDataField(StructDataOffset offset, kj::NoInfer value)); - // Sets the data field value at the given offset. - - template - KJ_ALWAYS_INLINE(void setDataField(StructDataOffset offset, - kj::NoInfer value, Mask mask)); - // Like setDataField() but applies the given XOR mask before storing. Used for writing fields - // with non-zero default values. - - KJ_ALWAYS_INLINE(PointerBuilder getPointerField(StructPointerOffset ptrIndex)); - // Get a builder for a pointer field given the index within the pointer section. - - void clearAll(); - // Clear all pointers and data. - - void transferContentFrom(StructBuilder other); - // Adopt all pointers from `other`, and also copy all data. If `other`'s sections are larger - // than this, the extra data is not transferred, meaning there is a risk of data loss when - // transferring from messages built with future versions of the protocol. - - void copyContentFrom(StructReader other); - // Copy content from `other`. If `other`'s sections are larger than this, the extra data is not - // copied, meaning there is a risk of data loss when copying from messages built with future - // versions of the protocol. - - StructReader asReader() const; - // Gets a StructReader pointing at the same memory. - - BuilderArena* getArena(); - // Gets the arena in which this object is allocated. - - CapTableBuilder* getCapTable(); - // Gets the capability context in which this object is operating. - - StructBuilder imbue(CapTableBuilder* capTable); - // Return a copy of this builder except using the given capability context. - -private: - SegmentBuilder* segment; // Memory segment in which the struct resides. - CapTableBuilder* capTable; // Table of capability indexes. - void* data; // Pointer to the encoded data. - WirePointer* pointers; // Pointer to the encoded pointers. - - StructDataBitCount dataSize; - // Size of data section. We use a bit count rather than a word count to more easily handle the - // case of struct lists encoded with less than a word per element. - - StructPointerCount pointerCount; // Size of the pointer section. - - inline StructBuilder(SegmentBuilder* segment, CapTableBuilder* capTable, - void* data, WirePointer* pointers, - StructDataBitCount dataSize, StructPointerCount pointerCount) - : segment(segment), capTable(capTable), data(data), pointers(pointers), - dataSize(dataSize), pointerCount(pointerCount) {} - - friend class ListBuilder; - friend struct WireHelpers; - friend class OrphanBuilder; -}; - -class StructReader { -public: - inline StructReader() - : segment(nullptr), capTable(nullptr), data(nullptr), pointers(nullptr), - dataSize(ZERO * BITS), pointerCount(ZERO * POINTERS), nestingLimit(0x7fffffff) {} - inline StructReader(kj::ArrayPtr data) - : segment(nullptr), capTable(nullptr), data(data.begin()), pointers(nullptr), - dataSize(assumeBits(data.size()) * WORDS * BITS_PER_WORD), - pointerCount(ZERO * POINTERS), nestingLimit(0x7fffffff) {} - - const void* getLocation() const { return data; } - - inline StructDataBitCount getDataSectionSize() const { return dataSize; } - inline StructPointerCount getPointerSectionSize() const { return pointerCount; } - inline kj::ArrayPtr getDataSectionAsBlob(); - inline _::ListReader getPointerSectionAsList(); - - kj::Array canonicalize(); - - template - KJ_ALWAYS_INLINE(bool hasDataField(StructDataOffset offset) const); - // Return true if the field is set to something other than its default value. - - template - KJ_ALWAYS_INLINE(T getDataField(StructDataOffset offset) const); - // Get the data field value of the given type at the given offset. The offset is measured in - // multiples of the field size, determined by the type. Returns zero if the offset is past the - // end of the struct's data section. - - template - KJ_ALWAYS_INLINE(T getDataField(StructDataOffset offset, Mask mask) const); - // Like getDataField(offset), but applies the given XOR mask to the result. Used for reading - // fields with non-zero default values. - - KJ_ALWAYS_INLINE(PointerReader getPointerField(StructPointerOffset ptrIndex) const); - // Get a reader for a pointer field given the index within the pointer section. If the index - // is out-of-bounds, returns a null pointer. - - MessageSizeCounts totalSize() const; - // Return the total size of the struct and everything to which it points. Does not count far - // pointer overhead. This is useful for deciding how much space is needed to copy the struct - // into a flat array. However, the caller is advised NOT to treat this value as secure. Instead, - // use the result as a hint for allocating the first segment, do the copy, and then throw an - // exception if it overruns. - - CapTableReader* getCapTable(); - // Gets the capability context in which this object is operating. - - StructReader imbue(CapTableReader* capTable) const; - // Return a copy of this reader except using the given capability context. - - bool isCanonical(const word **readHead, const word **ptrHead, - bool *dataTrunc, bool *ptrTrunc); - // Validate this pointer's canonicity, subject to the conditions: - // * All data to the left of readHead has been read thus far (for pointer - // ordering) - // * All pointers in preorder have already been checked - // * This pointer is in the first and only segment of the message - // - // If this function returns false, the struct is non-canonical. If it - // returns true, then: - // * If it is a composite in a list, it is canonical if at least one struct - // in the list outputs dataTrunc = 1, and at least one outputs ptrTrunc = 1 - // * If it is derived from a struct pointer, it is canonical if - // dataTrunc = 1 AND ptrTrunc = 1 - -private: - SegmentReader* segment; // Memory segment in which the struct resides. - CapTableReader* capTable; // Table of capability indexes. - - const void* data; - const WirePointer* pointers; - - StructDataBitCount dataSize; - // Size of data section. We use a bit count rather than a word count to more easily handle the - // case of struct lists encoded with less than a word per element. - - StructPointerCount pointerCount; // Size of the pointer section. - - int nestingLimit; - // Limits the depth of message structures to guard against stack-overflow-based DoS attacks. - // Once this reaches zero, further pointers will be pruned. - // TODO(perf): Limit to 16 bits for better packing? - - inline StructReader(SegmentReader* segment, CapTableReader* capTable, - const void* data, const WirePointer* pointers, - StructDataBitCount dataSize, StructPointerCount pointerCount, - int nestingLimit) - : segment(segment), capTable(capTable), data(data), pointers(pointers), - dataSize(dataSize), pointerCount(pointerCount), - nestingLimit(nestingLimit) {} - - friend class ListReader; - friend class StructBuilder; - friend struct WireHelpers; -}; - -// ------------------------------------------------------------------- - -class ListBuilder: public kj::DisallowConstCopy { -public: - inline explicit ListBuilder(ElementSize elementSize) - : segment(nullptr), capTable(nullptr), ptr(nullptr), elementCount(ZERO * ELEMENTS), - step(ZERO * BITS / ELEMENTS), structDataSize(ZERO * BITS), - structPointerCount(ZERO * POINTERS), elementSize(elementSize) {} - - inline word* getLocation() { - // Get the object's location. - - if (elementSize == ElementSize::INLINE_COMPOSITE && ptr != nullptr) { - return reinterpret_cast(ptr) - POINTER_SIZE_IN_WORDS; - } else { - return reinterpret_cast(ptr); - } - } - - inline ElementSize getElementSize() const { return elementSize; } - - inline ListElementCount size() const; - // The number of elements in the list. - - Text::Builder asText(); - Data::Builder asData(); - // Reinterpret the list as a blob. Throws an exception if the elements are not byte-sized. - - template - KJ_ALWAYS_INLINE(T getDataElement(ElementCount index)); - // Get the element of the given type at the given index. - - template - KJ_ALWAYS_INLINE(void setDataElement(ElementCount index, kj::NoInfer value)); - // Set the element at the given index. - - KJ_ALWAYS_INLINE(PointerBuilder getPointerElement(ElementCount index)); - - StructBuilder getStructElement(ElementCount index); - - ListReader asReader() const; - // Get a ListReader pointing at the same memory. - - BuilderArena* getArena(); - // Gets the arena in which this object is allocated. - - CapTableBuilder* getCapTable(); - // Gets the capability context in which this object is operating. - - ListBuilder imbue(CapTableBuilder* capTable); - // Return a copy of this builder except using the given capability context. - -private: - SegmentBuilder* segment; // Memory segment in which the list resides. - CapTableBuilder* capTable; // Table of capability indexes. - - byte* ptr; // Pointer to list content. - - ListElementCount elementCount; // Number of elements in the list. - - BitsPerElementN<23> step; - // The distance between elements. The maximum value occurs when a struct contains 2^16-1 data - // words and 2^16-1 pointers, i.e. 2^17 - 2 words, or 2^23 - 128 bits. - - StructDataBitCount structDataSize; - StructPointerCount structPointerCount; - // The struct properties to use when interpreting the elements as structs. All lists can be - // interpreted as struct lists, so these are always filled in. - - ElementSize elementSize; - // The element size as a ElementSize. This is only really needed to disambiguate INLINE_COMPOSITE - // from other types when the overall size is exactly zero or one words. - - inline ListBuilder(SegmentBuilder* segment, CapTableBuilder* capTable, void* ptr, - BitsPerElementN<23> step, ListElementCount size, - StructDataBitCount structDataSize, StructPointerCount structPointerCount, - ElementSize elementSize) - : segment(segment), capTable(capTable), ptr(reinterpret_cast(ptr)), - elementCount(size), step(step), structDataSize(structDataSize), - structPointerCount(structPointerCount), elementSize(elementSize) {} - - friend class StructBuilder; - friend struct WireHelpers; - friend class OrphanBuilder; -}; - -class ListReader { -public: - inline explicit ListReader(ElementSize elementSize) - : segment(nullptr), capTable(nullptr), ptr(nullptr), elementCount(ZERO * ELEMENTS), - step(ZERO * BITS / ELEMENTS), structDataSize(ZERO * BITS), - structPointerCount(ZERO * POINTERS), elementSize(elementSize), nestingLimit(0x7fffffff) {} - - inline ListElementCount size() const; - // The number of elements in the list. - - inline ElementSize getElementSize() const { return elementSize; } - - Text::Reader asText(); - Data::Reader asData(); - // Reinterpret the list as a blob. Throws an exception if the elements are not byte-sized. - - kj::ArrayPtr asRawBytes(); - - template - KJ_ALWAYS_INLINE(T getDataElement(ElementCount index) const); - // Get the element of the given type at the given index. - - KJ_ALWAYS_INLINE(PointerReader getPointerElement(ElementCount index) const); - - StructReader getStructElement(ElementCount index) const; - - CapTableReader* getCapTable(); - // Gets the capability context in which this object is operating. - - ListReader imbue(CapTableReader* capTable) const; - // Return a copy of this reader except using the given capability context. - - bool isCanonical(const word **readHead, const WirePointer* ref); - // Validate this pointer's canonicity, subject to the conditions: - // * All data to the left of readHead has been read thus far (for pointer - // ordering) - // * All pointers in preorder have already been checked - // * This pointer is in the first and only segment of the message - -private: - SegmentReader* segment; // Memory segment in which the list resides. - CapTableReader* capTable; // Table of capability indexes. - - const byte* ptr; // Pointer to list content. - - ListElementCount elementCount; // Number of elements in the list. - - BitsPerElementN<23> step; - // The distance between elements. The maximum value occurs when a struct contains 2^16-1 data - // words and 2^16-1 pointers, i.e. 2^17 - 2 words, or 2^23 - 2 bits. - - StructDataBitCount structDataSize; - StructPointerCount structPointerCount; - // The struct properties to use when interpreting the elements as structs. All lists can be - // interpreted as struct lists, so these are always filled in. - - ElementSize elementSize; - // The element size as a ElementSize. This is only really needed to disambiguate INLINE_COMPOSITE - // from other types when the overall size is exactly zero or one words. - - int nestingLimit; - // Limits the depth of message structures to guard against stack-overflow-based DoS attacks. - // Once this reaches zero, further pointers will be pruned. - - inline ListReader(SegmentReader* segment, CapTableReader* capTable, const void* ptr, - ListElementCount elementCount, BitsPerElementN<23> step, - StructDataBitCount structDataSize, StructPointerCount structPointerCount, - ElementSize elementSize, int nestingLimit) - : segment(segment), capTable(capTable), ptr(reinterpret_cast(ptr)), - elementCount(elementCount), step(step), structDataSize(structDataSize), - structPointerCount(structPointerCount), elementSize(elementSize), - nestingLimit(nestingLimit) {} - - friend class StructReader; - friend class ListBuilder; - friend struct WireHelpers; - friend class OrphanBuilder; -}; - -// ------------------------------------------------------------------- - -class OrphanBuilder { -public: - inline OrphanBuilder(): segment(nullptr), capTable(nullptr), location(nullptr) { - memset(&tag, 0, sizeof(tag)); - } - OrphanBuilder(const OrphanBuilder& other) = delete; - inline OrphanBuilder(OrphanBuilder&& other) noexcept; - inline ~OrphanBuilder() noexcept(false); - - static OrphanBuilder initStruct(BuilderArena* arena, CapTableBuilder* capTable, StructSize size); - static OrphanBuilder initList(BuilderArena* arena, CapTableBuilder* capTable, - ElementCount elementCount, ElementSize elementSize); - static OrphanBuilder initStructList(BuilderArena* arena, CapTableBuilder* capTable, - ElementCount elementCount, StructSize elementSize); - static OrphanBuilder initText(BuilderArena* arena, CapTableBuilder* capTable, ByteCount size); - static OrphanBuilder initData(BuilderArena* arena, CapTableBuilder* capTable, ByteCount size); - - static OrphanBuilder copy(BuilderArena* arena, CapTableBuilder* capTable, StructReader copyFrom); - static OrphanBuilder copy(BuilderArena* arena, CapTableBuilder* capTable, ListReader copyFrom); - static OrphanBuilder copy(BuilderArena* arena, CapTableBuilder* capTable, PointerReader copyFrom); - static OrphanBuilder copy(BuilderArena* arena, CapTableBuilder* capTable, Text::Reader copyFrom); - static OrphanBuilder copy(BuilderArena* arena, CapTableBuilder* capTable, Data::Reader copyFrom); -#if !CAPNP_LITE - static OrphanBuilder copy(BuilderArena* arena, CapTableBuilder* capTable, - kj::Own copyFrom); -#endif // !CAPNP_LITE - - static OrphanBuilder concat(BuilderArena* arena, CapTableBuilder* capTable, - ElementSize expectedElementSize, StructSize expectedStructSize, - kj::ArrayPtr lists); - - static OrphanBuilder referenceExternalData(BuilderArena* arena, Data::Reader data); - - OrphanBuilder& operator=(const OrphanBuilder& other) = delete; - inline OrphanBuilder& operator=(OrphanBuilder&& other); - - inline bool operator==(decltype(nullptr)) const { return location == nullptr; } - inline bool operator!=(decltype(nullptr)) const { return location != nullptr; } - - StructBuilder asStruct(StructSize size); - // Interpret as a struct, or throw an exception if not a struct. - - ListBuilder asList(ElementSize elementSize); - // Interpret as a list, or throw an exception if not a list. elementSize cannot be - // INLINE_COMPOSITE -- use asStructList() instead. - - ListBuilder asStructList(StructSize elementSize); - // Interpret as a struct list, or throw an exception if not a list. - - ListBuilder asListAnySize(); - // For AnyList. - - Text::Builder asText(); - Data::Builder asData(); - // Interpret as a blob, or throw an exception if not a blob. - - StructReader asStructReader(StructSize size) const; - ListReader asListReader(ElementSize elementSize) const; - ListReader asListReaderAnySize() const; -#if !CAPNP_LITE - kj::Own asCapability() const; -#endif // !CAPNP_LITE - Text::Reader asTextReader() const; - Data::Reader asDataReader() const; - - bool truncate(ElementCount size, bool isText) KJ_WARN_UNUSED_RESULT; - // Resize the orphan list to the given size. Returns false if the list is currently empty but - // the requested size is non-zero, in which case the caller will need to allocate a new list. - - void truncate(ElementCount size, ElementSize elementSize); - void truncate(ElementCount size, StructSize elementSize); - void truncateText(ElementCount size); - // Versions of truncate() that know how to allocate a new list if needed. - -private: - static_assert(ONE * POINTERS * WORDS_PER_POINTER == ONE * WORDS, - "This struct assumes a pointer is one word."); - word tag; - // Contains an encoded WirePointer representing this object. WirePointer is defined in - // layout.c++, but fits in a word. - // - // This may be a FAR pointer. Even in that case, `location` points to the eventual destination - // of that far pointer. The reason we keep the far pointer around rather than just making `tag` - // represent the final destination is because if the eventual adopter of the pointer is not in - // the target's segment then it may be useful to reuse the far pointer landing pad. - // - // If `tag` is not a far pointer, its offset is garbage; only `location` points to the actual - // target. - - SegmentBuilder* segment; - // Segment in which the object resides. - - CapTableBuilder* capTable; - // Table of capability indexes. - - word* location; - // Pointer to the object, or nullptr if the pointer is null. For capabilities, we make this - // 0x1 just so that it is non-null for operator==, but it is never used. - - inline OrphanBuilder(const void* tagPtr, SegmentBuilder* segment, - CapTableBuilder* capTable, word* location) - : segment(segment), capTable(capTable), location(location) { - memcpy(&tag, tagPtr, sizeof(tag)); - } - - inline WirePointer* tagAsPtr() { return reinterpret_cast(&tag); } - inline const WirePointer* tagAsPtr() const { return reinterpret_cast(&tag); } - - void euthanize(); - // Erase the target object, zeroing it out and possibly reclaiming the memory. Called when - // the OrphanBuilder is being destroyed or overwritten and it is non-null. - - friend struct WireHelpers; -}; - -// ======================================================================================= -// Internal implementation details... - -// These are defined in the source file. -template <> typename Text::Builder PointerBuilder::initBlob(ByteCount size); -template <> void PointerBuilder::setBlob(typename Text::Reader value); -template <> typename Text::Builder PointerBuilder::getBlob( - const void* defaultValue, ByteCount defaultSize); -template <> typename Text::Reader PointerReader::getBlob( - const void* defaultValue, ByteCount defaultSize) const; - -template <> typename Data::Builder PointerBuilder::initBlob(ByteCount size); -template <> void PointerBuilder::setBlob(typename Data::Reader value); -template <> typename Data::Builder PointerBuilder::getBlob( - const void* defaultValue, ByteCount defaultSize); -template <> typename Data::Reader PointerReader::getBlob( - const void* defaultValue, ByteCount defaultSize) const; - -inline PointerBuilder PointerBuilder::getRoot( - SegmentBuilder* segment, CapTableBuilder* capTable, word* location) { - return PointerBuilder(segment, capTable, reinterpret_cast(location)); -} - -inline PointerReader PointerReader::getRootUnchecked(const word* location) { - return PointerReader(nullptr, nullptr, - reinterpret_cast(location), 0x7fffffff); -} - -// ------------------------------------------------------------------- - -inline kj::ArrayPtr StructBuilder::getDataSectionAsBlob() { - return kj::ArrayPtr(reinterpret_cast(data), - unbound(dataSize / BITS_PER_BYTE / BYTES)); -} - -inline _::ListBuilder StructBuilder::getPointerSectionAsList() { - return _::ListBuilder(segment, capTable, pointers, ONE * POINTERS * BITS_PER_POINTER / ELEMENTS, - pointerCount * (ONE * ELEMENTS / POINTERS), - ZERO * BITS, ONE * POINTERS, ElementSize::POINTER); -} - -template -inline bool StructBuilder::hasDataField(StructDataOffset offset) { - return getDataField>(offset) != 0; -} - -template <> -inline bool StructBuilder::hasDataField(StructDataOffset offset) { - return false; -} - -template -inline T StructBuilder::getDataField(StructDataOffset offset) { - return reinterpret_cast*>(data)[unbound(offset / ELEMENTS)].get(); -} - -template <> -inline bool StructBuilder::getDataField(StructDataOffset offset) { - BitCount32 boffset = offset * (ONE * BITS / ELEMENTS); - byte* b = reinterpret_cast(data) + boffset / BITS_PER_BYTE; - return (*reinterpret_cast(b) & - unbound(ONE << (boffset % BITS_PER_BYTE / BITS))) != 0; -} - -template <> -inline Void StructBuilder::getDataField(StructDataOffset offset) { - return VOID; -} - -template -inline T StructBuilder::getDataField(StructDataOffset offset, Mask mask) { - return unmask(getDataField >(offset), mask); -} - -template -inline void StructBuilder::setDataField(StructDataOffset offset, kj::NoInfer value) { - reinterpret_cast*>(data)[unbound(offset / ELEMENTS)].set(value); -} - -#if CAPNP_CANONICALIZE_NAN -// Use mask() on floats and doubles to make sure we canonicalize NaNs. -template <> -inline void StructBuilder::setDataField(StructDataOffset offset, float value) { - setDataField(offset, mask(value, 0)); -} -template <> -inline void StructBuilder::setDataField(StructDataOffset offset, double value) { - setDataField(offset, mask(value, 0)); -} -#endif - -template <> -inline void StructBuilder::setDataField(StructDataOffset offset, bool value) { - auto boffset = offset * (ONE * BITS / ELEMENTS); - byte* b = reinterpret_cast(data) + boffset / BITS_PER_BYTE; - uint bitnum = unboundMaxBits<3>(boffset % BITS_PER_BYTE / BITS); - *reinterpret_cast(b) = (*reinterpret_cast(b) & ~(1 << bitnum)) - | (static_cast(value) << bitnum); -} - -template <> -inline void StructBuilder::setDataField(StructDataOffset offset, Void value) {} - -template -inline void StructBuilder::setDataField(StructDataOffset offset, - kj::NoInfer value, Mask m) { - setDataField >(offset, mask(value, m)); -} - -inline PointerBuilder StructBuilder::getPointerField(StructPointerOffset ptrIndex) { - // Hacky because WirePointer is defined in the .c++ file (so is incomplete here). - return PointerBuilder(segment, capTable, reinterpret_cast( - reinterpret_cast(pointers) + ptrIndex * WORDS_PER_POINTER)); -} - -// ------------------------------------------------------------------- - -inline kj::ArrayPtr StructReader::getDataSectionAsBlob() { - return kj::ArrayPtr(reinterpret_cast(data), - unbound(dataSize / BITS_PER_BYTE / BYTES)); -} - -inline _::ListReader StructReader::getPointerSectionAsList() { - return _::ListReader(segment, capTable, pointers, pointerCount * (ONE * ELEMENTS / POINTERS), - ONE * POINTERS * BITS_PER_POINTER / ELEMENTS, ZERO * BITS, ONE * POINTERS, - ElementSize::POINTER, nestingLimit); -} - -template -inline bool StructReader::hasDataField(StructDataOffset offset) const { - return getDataField>(offset) != 0; -} - -template <> -inline bool StructReader::hasDataField(StructDataOffset offset) const { - return false; -} - -template -inline T StructReader::getDataField(StructDataOffset offset) const { - if ((offset + ONE * ELEMENTS) * capnp::bitsPerElement() <= dataSize) { - return reinterpret_cast*>(data)[unbound(offset / ELEMENTS)].get(); - } else { - return static_cast(0); - } -} - -template <> -inline bool StructReader::getDataField(StructDataOffset offset) const { - auto boffset = offset * (ONE * BITS / ELEMENTS); - if (boffset < dataSize) { - const byte* b = reinterpret_cast(data) + boffset / BITS_PER_BYTE; - return (*reinterpret_cast(b) & - unbound(ONE << (boffset % BITS_PER_BYTE / BITS))) != 0; - } else { - return false; - } -} - -template <> -inline Void StructReader::getDataField(StructDataOffset offset) const { - return VOID; -} - -template -T StructReader::getDataField(StructDataOffset offset, Mask mask) const { - return unmask(getDataField >(offset), mask); -} - -inline PointerReader StructReader::getPointerField(StructPointerOffset ptrIndex) const { - if (ptrIndex < pointerCount) { - // Hacky because WirePointer is defined in the .c++ file (so is incomplete here). - return PointerReader(segment, capTable, reinterpret_cast( - reinterpret_cast(pointers) + ptrIndex * WORDS_PER_POINTER), nestingLimit); - } else{ - return PointerReader(); - } -} - -// ------------------------------------------------------------------- - -inline ListElementCount ListBuilder::size() const { return elementCount; } - -template -inline T ListBuilder::getDataElement(ElementCount index) { - return reinterpret_cast*>( - ptr + upgradeBound(index) * step / BITS_PER_BYTE)->get(); - - // TODO(perf): Benchmark this alternate implementation, which I suspect may make better use of - // the x86 SIB byte. Also use it for all the other getData/setData implementations below, and - // the various non-inline methods that look up pointers. - // Also if using this, consider changing ptr back to void* instead of byte*. -// return reinterpret_cast*>(ptr)[ -// index / ELEMENTS * (step / capnp::bitsPerElement())].get(); -} - -template <> -inline bool ListBuilder::getDataElement(ElementCount index) { - // Ignore step for bit lists because bit lists cannot be upgraded to struct lists. - auto bindex = index * (ONE * BITS / ELEMENTS); - byte* b = ptr + bindex / BITS_PER_BYTE; - return (*reinterpret_cast(b) & - unbound(ONE << (bindex % BITS_PER_BYTE / BITS))) != 0; -} - -template <> -inline Void ListBuilder::getDataElement(ElementCount index) { - return VOID; -} - -template -inline void ListBuilder::setDataElement(ElementCount index, kj::NoInfer value) { - reinterpret_cast*>( - ptr + upgradeBound(index) * step / BITS_PER_BYTE)->set(value); -} - -#if CAPNP_CANONICALIZE_NAN -// Use mask() on floats and doubles to make sure we canonicalize NaNs. -template <> -inline void ListBuilder::setDataElement(ElementCount index, float value) { - setDataElement(index, mask(value, 0)); -} -template <> -inline void ListBuilder::setDataElement(ElementCount index, double value) { - setDataElement(index, mask(value, 0)); -} -#endif - -template <> -inline void ListBuilder::setDataElement(ElementCount index, bool value) { - // Ignore stepBytes for bit lists because bit lists cannot be upgraded to struct lists. - auto bindex = index * (ONE * BITS / ELEMENTS); - byte* b = ptr + bindex / BITS_PER_BYTE; - auto bitnum = bindex % BITS_PER_BYTE / BITS; - *reinterpret_cast(b) = (*reinterpret_cast(b) & ~(1 << unbound(bitnum))) - | (static_cast(value) << unbound(bitnum)); -} - -template <> -inline void ListBuilder::setDataElement(ElementCount index, Void value) {} - -inline PointerBuilder ListBuilder::getPointerElement(ElementCount index) { - return PointerBuilder(segment, capTable, reinterpret_cast(ptr + - upgradeBound(index) * step / BITS_PER_BYTE)); -} - -// ------------------------------------------------------------------- - -inline ListElementCount ListReader::size() const { return elementCount; } - -template -inline T ListReader::getDataElement(ElementCount index) const { - return reinterpret_cast*>( - ptr + upgradeBound(index) * step / BITS_PER_BYTE)->get(); -} - -template <> -inline bool ListReader::getDataElement(ElementCount index) const { - // Ignore step for bit lists because bit lists cannot be upgraded to struct lists. - auto bindex = index * (ONE * BITS / ELEMENTS); - const byte* b = ptr + bindex / BITS_PER_BYTE; - return (*reinterpret_cast(b) & - unbound(ONE << (bindex % BITS_PER_BYTE / BITS))) != 0; -} - -template <> -inline Void ListReader::getDataElement(ElementCount index) const { - return VOID; -} - -inline PointerReader ListReader::getPointerElement(ElementCount index) const { - return PointerReader(segment, capTable, reinterpret_cast( - ptr + upgradeBound(index) * step / BITS_PER_BYTE), nestingLimit); -} - -// ------------------------------------------------------------------- - -inline OrphanBuilder::OrphanBuilder(OrphanBuilder&& other) noexcept - : segment(other.segment), capTable(other.capTable), location(other.location) { - memcpy(&tag, &other.tag, sizeof(tag)); // Needs memcpy to comply with aliasing rules. - other.segment = nullptr; - other.location = nullptr; -} - -inline OrphanBuilder::~OrphanBuilder() noexcept(false) { - if (segment != nullptr) euthanize(); -} - -inline OrphanBuilder& OrphanBuilder::operator=(OrphanBuilder&& other) { - // With normal smart pointers, it's important to handle the case where the incoming pointer - // is actually transitively owned by this one. In this case, euthanize() would destroy `other` - // before we copied it. This isn't possible in the case of `OrphanBuilder` because it only - // owns message objects, and `other` is not itself a message object, therefore cannot possibly - // be transitively owned by `this`. - - if (segment != nullptr) euthanize(); - segment = other.segment; - capTable = other.capTable; - location = other.location; - memcpy(&tag, &other.tag, sizeof(tag)); // Needs memcpy to comply with aliasing rules. - other.segment = nullptr; - other.location = nullptr; - return *this; -} - -} // namespace _ (private) -} // namespace capnp - -#endif // CAPNP_LAYOUT_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/list.h b/phonelibs/capnp-cpp/include/capnp/list.h deleted file mode 100644 index 23e5e6c10e..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/list.h +++ /dev/null @@ -1,546 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_LIST_H_ -#define CAPNP_LIST_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include "layout.h" -#include "orphan.h" -#include -#ifdef KJ_STD_COMPAT -#include -#endif // KJ_STD_COMPAT - -namespace capnp { -namespace _ { // private - -template -class TemporaryPointer { - // This class is a little hack which lets us define operator->() in cases where it needs to - // return a pointer to a temporary value. We instead construct a TemporaryPointer and return that - // (by value). The compiler then invokes operator->() on the TemporaryPointer, which itself is - // able to return a real pointer to its member. - -public: - TemporaryPointer(T&& value): value(kj::mv(value)) {} - TemporaryPointer(const T& value): value(value) {} - - inline T* operator->() { return &value; } -private: - T value; -}; - -template -class IndexingIterator { -public: - IndexingIterator() = default; - - inline Element operator*() const { return (*container)[index]; } - inline TemporaryPointer operator->() const { - return TemporaryPointer((*container)[index]); - } - inline Element operator[]( int off) const { return (*container)[index]; } - inline Element operator[](uint off) const { return (*container)[index]; } - - inline IndexingIterator& operator++() { ++index; return *this; } - inline IndexingIterator operator++(int) { IndexingIterator other = *this; ++index; return other; } - inline IndexingIterator& operator--() { --index; return *this; } - inline IndexingIterator operator--(int) { IndexingIterator other = *this; --index; return other; } - - inline IndexingIterator operator+(uint amount) const { return IndexingIterator(container, index + amount); } - inline IndexingIterator operator-(uint amount) const { return IndexingIterator(container, index - amount); } - inline IndexingIterator operator+( int amount) const { return IndexingIterator(container, index + amount); } - inline IndexingIterator operator-( int amount) const { return IndexingIterator(container, index - amount); } - - inline int operator-(const IndexingIterator& other) const { return index - other.index; } - - inline IndexingIterator& operator+=(uint amount) { index += amount; return *this; } - inline IndexingIterator& operator-=(uint amount) { index -= amount; return *this; } - inline IndexingIterator& operator+=( int amount) { index += amount; return *this; } - inline IndexingIterator& operator-=( int amount) { index -= amount; return *this; } - - // STL says comparing iterators of different containers is not allowed, so we only compare - // indices here. - inline bool operator==(const IndexingIterator& other) const { return index == other.index; } - inline bool operator!=(const IndexingIterator& other) const { return index != other.index; } - inline bool operator<=(const IndexingIterator& other) const { return index <= other.index; } - inline bool operator>=(const IndexingIterator& other) const { return index >= other.index; } - inline bool operator< (const IndexingIterator& other) const { return index < other.index; } - inline bool operator> (const IndexingIterator& other) const { return index > other.index; } - -private: - Container* container; - uint index; - - friend Container; - inline IndexingIterator(Container* container, uint index) - : container(container), index(index) {} -}; - -} // namespace _ (private) - -template -struct List { - // List of primitives. - - List() = delete; - - class Reader { - public: - typedef List Reads; - - inline Reader(): reader(_::elementSizeForType()) {} - inline explicit Reader(_::ListReader reader): reader(reader) {} - - inline uint size() const { return unbound(reader.size() / ELEMENTS); } - inline T operator[](uint index) const { - KJ_IREQUIRE(index < size()); - return reader.template getDataElement(bounded(index) * ELEMENTS); - } - - typedef _::IndexingIterator Iterator; - inline Iterator begin() const { return Iterator(this, 0); } - inline Iterator end() const { return Iterator(this, size()); } - - private: - _::ListReader reader; - template - friend struct _::PointerHelpers; - template - friend struct List; - friend class Orphanage; - template - friend struct ToDynamic_; - }; - - class Builder { - public: - typedef List Builds; - - inline Builder(): builder(_::elementSizeForType()) {} - inline Builder(decltype(nullptr)): Builder() {} - inline explicit Builder(_::ListBuilder builder): builder(builder) {} - - inline operator Reader() const { return Reader(builder.asReader()); } - inline Reader asReader() const { return Reader(builder.asReader()); } - - inline uint size() const { return unbound(builder.size() / ELEMENTS); } - inline T operator[](uint index) { - KJ_IREQUIRE(index < size()); - return builder.template getDataElement(bounded(index) * ELEMENTS); - } - inline void set(uint index, T value) { - // Alas, it is not possible to make operator[] return a reference to which you can assign, - // since the encoded representation does not necessarily match the compiler's representation - // of the type. We can't even return a clever class that implements operator T() and - // operator=() because it will lead to surprising behavior when using type inference (e.g. - // calling a template function with inferred argument types, or using "auto" or "decltype"). - - builder.template setDataElement(bounded(index) * ELEMENTS, value); - } - - typedef _::IndexingIterator Iterator; - inline Iterator begin() { return Iterator(this, 0); } - inline Iterator end() { return Iterator(this, size()); } - - private: - _::ListBuilder builder; - template - friend struct _::PointerHelpers; - friend class Orphanage; - template - friend struct ToDynamic_; - }; - - class Pipeline {}; - -private: - inline static _::ListBuilder initPointer(_::PointerBuilder builder, uint size) { - return builder.initList(_::elementSizeForType(), bounded(size) * ELEMENTS); - } - inline static _::ListBuilder getFromPointer(_::PointerBuilder builder, const word* defaultValue) { - return builder.getList(_::elementSizeForType(), defaultValue); - } - inline static _::ListReader getFromPointer( - const _::PointerReader& reader, const word* defaultValue) { - return reader.getList(_::elementSizeForType(), defaultValue); - } - - template - friend struct List; - template - friend struct _::PointerHelpers; -}; - -template -struct List: public List {}; - -template -struct List { - // List of structs. - - List() = delete; - - class Reader { - public: - typedef List Reads; - - inline Reader(): reader(ElementSize::INLINE_COMPOSITE) {} - inline explicit Reader(_::ListReader reader): reader(reader) {} - - inline uint size() const { return unbound(reader.size() / ELEMENTS); } - inline typename T::Reader operator[](uint index) const { - KJ_IREQUIRE(index < size()); - return typename T::Reader(reader.getStructElement(bounded(index) * ELEMENTS)); - } - - typedef _::IndexingIterator Iterator; - inline Iterator begin() const { return Iterator(this, 0); } - inline Iterator end() const { return Iterator(this, size()); } - - private: - _::ListReader reader; - template - friend struct _::PointerHelpers; - template - friend struct List; - friend class Orphanage; - template - friend struct ToDynamic_; - }; - - class Builder { - public: - typedef List Builds; - - inline Builder(): builder(ElementSize::INLINE_COMPOSITE) {} - inline Builder(decltype(nullptr)): Builder() {} - inline explicit Builder(_::ListBuilder builder): builder(builder) {} - - inline operator Reader() const { return Reader(builder.asReader()); } - inline Reader asReader() const { return Reader(builder.asReader()); } - - inline uint size() const { return unbound(builder.size() / ELEMENTS); } - inline typename T::Builder operator[](uint index) { - KJ_IREQUIRE(index < size()); - return typename T::Builder(builder.getStructElement(bounded(index) * ELEMENTS)); - } - - inline void adoptWithCaveats(uint index, Orphan&& orphan) { - // Mostly behaves like you'd expect `adopt` to behave, but with two caveats originating from - // the fact that structs in a struct list are allocated inline rather than by pointer: - // * This actually performs a shallow copy, effectively adopting each of the orphan's - // children rather than adopting the orphan itself. The orphan ends up being discarded, - // possibly wasting space in the message object. - // * If the orphan is larger than the target struct -- say, because the orphan was built - // using a newer version of the schema that has additional fields -- it will be truncated, - // losing data. - - KJ_IREQUIRE(index < size()); - - // We pass a zero-valued StructSize to asStruct() because we do not want the struct to be - // expanded under any circumstances. We're just going to throw it away anyway, and - // transferContentFrom() already carefully compares the struct sizes before transferring. - builder.getStructElement(bounded(index) * ELEMENTS).transferContentFrom( - orphan.builder.asStruct(_::StructSize(ZERO * WORDS, ZERO * POINTERS))); - } - inline void setWithCaveats(uint index, const typename T::Reader& reader) { - // Mostly behaves like you'd expect `set` to behave, but with a caveat originating from - // the fact that structs in a struct list are allocated inline rather than by pointer: - // If the source struct is larger than the target struct -- say, because the source was built - // using a newer version of the schema that has additional fields -- it will be truncated, - // losing data. - // - // Note: If you are trying to concatenate some lists, use Orphanage::newOrphanConcat() to - // do it without losing any data in case the source lists come from a newer version of the - // protocol. (Plus, it's easier to use anyhow.) - - KJ_IREQUIRE(index < size()); - builder.getStructElement(bounded(index) * ELEMENTS).copyContentFrom(reader._reader); - } - - // There are no init(), set(), adopt(), or disown() methods for lists of structs because the - // elements of the list are inlined and are initialized when the list is initialized. This - // means that init() would be redundant, and set() would risk data loss if the input struct - // were from a newer version of the protocol. - - typedef _::IndexingIterator Iterator; - inline Iterator begin() { return Iterator(this, 0); } - inline Iterator end() { return Iterator(this, size()); } - - private: - _::ListBuilder builder; - template - friend struct _::PointerHelpers; - friend class Orphanage; - template - friend struct ToDynamic_; - }; - - class Pipeline {}; - -private: - inline static _::ListBuilder initPointer(_::PointerBuilder builder, uint size) { - return builder.initStructList(bounded(size) * ELEMENTS, _::structSize()); - } - inline static _::ListBuilder getFromPointer(_::PointerBuilder builder, const word* defaultValue) { - return builder.getStructList(_::structSize(), defaultValue); - } - inline static _::ListReader getFromPointer( - const _::PointerReader& reader, const word* defaultValue) { - return reader.getList(ElementSize::INLINE_COMPOSITE, defaultValue); - } - - template - friend struct List; - template - friend struct _::PointerHelpers; -}; - -template -struct List, Kind::LIST> { - // List of lists. - - List() = delete; - - class Reader { - public: - typedef List> Reads; - - inline Reader(): reader(ElementSize::POINTER) {} - inline explicit Reader(_::ListReader reader): reader(reader) {} - - inline uint size() const { return unbound(reader.size() / ELEMENTS); } - inline typename List::Reader operator[](uint index) const { - KJ_IREQUIRE(index < size()); - return typename List::Reader(_::PointerHelpers>::get( - reader.getPointerElement(bounded(index) * ELEMENTS))); - } - - typedef _::IndexingIterator::Reader> Iterator; - inline Iterator begin() const { return Iterator(this, 0); } - inline Iterator end() const { return Iterator(this, size()); } - - private: - _::ListReader reader; - template - friend struct _::PointerHelpers; - template - friend struct List; - friend class Orphanage; - template - friend struct ToDynamic_; - }; - - class Builder { - public: - typedef List> Builds; - - inline Builder(): builder(ElementSize::POINTER) {} - inline Builder(decltype(nullptr)): Builder() {} - inline explicit Builder(_::ListBuilder builder): builder(builder) {} - - inline operator Reader() const { return Reader(builder.asReader()); } - inline Reader asReader() const { return Reader(builder.asReader()); } - - inline uint size() const { return unbound(builder.size() / ELEMENTS); } - inline typename List::Builder operator[](uint index) { - KJ_IREQUIRE(index < size()); - return typename List::Builder(_::PointerHelpers>::get( - builder.getPointerElement(bounded(index) * ELEMENTS))); - } - inline typename List::Builder init(uint index, uint size) { - KJ_IREQUIRE(index < this->size()); - return typename List::Builder(_::PointerHelpers>::init( - builder.getPointerElement(bounded(index) * ELEMENTS), size)); - } - inline void set(uint index, typename List::Reader value) { - KJ_IREQUIRE(index < size()); - builder.getPointerElement(bounded(index) * ELEMENTS).setList(value.reader); - } - void set(uint index, std::initializer_list> value) { - KJ_IREQUIRE(index < size()); - auto l = init(index, value.size()); - uint i = 0; - for (auto& element: value) { - l.set(i++, element); - } - } - inline void adopt(uint index, Orphan&& value) { - KJ_IREQUIRE(index < size()); - builder.getPointerElement(bounded(index) * ELEMENTS).adopt(kj::mv(value.builder)); - } - inline Orphan disown(uint index) { - KJ_IREQUIRE(index < size()); - return Orphan(builder.getPointerElement(bounded(index) * ELEMENTS).disown()); - } - - typedef _::IndexingIterator::Builder> Iterator; - inline Iterator begin() { return Iterator(this, 0); } - inline Iterator end() { return Iterator(this, size()); } - - private: - _::ListBuilder builder; - template - friend struct _::PointerHelpers; - friend class Orphanage; - template - friend struct ToDynamic_; - }; - - class Pipeline {}; - -private: - inline static _::ListBuilder initPointer(_::PointerBuilder builder, uint size) { - return builder.initList(ElementSize::POINTER, bounded(size) * ELEMENTS); - } - inline static _::ListBuilder getFromPointer(_::PointerBuilder builder, const word* defaultValue) { - return builder.getList(ElementSize::POINTER, defaultValue); - } - inline static _::ListReader getFromPointer( - const _::PointerReader& reader, const word* defaultValue) { - return reader.getList(ElementSize::POINTER, defaultValue); - } - - template - friend struct List; - template - friend struct _::PointerHelpers; -}; - -template -struct List { - List() = delete; - - class Reader { - public: - typedef List Reads; - - inline Reader(): reader(ElementSize::POINTER) {} - inline explicit Reader(_::ListReader reader): reader(reader) {} - - inline uint size() const { return unbound(reader.size() / ELEMENTS); } - inline typename T::Reader operator[](uint index) const { - KJ_IREQUIRE(index < size()); - return reader.getPointerElement(bounded(index) * ELEMENTS) - .template getBlob(nullptr, ZERO * BYTES); - } - - typedef _::IndexingIterator Iterator; - inline Iterator begin() const { return Iterator(this, 0); } - inline Iterator end() const { return Iterator(this, size()); } - - private: - _::ListReader reader; - template - friend struct _::PointerHelpers; - template - friend struct List; - friend class Orphanage; - template - friend struct ToDynamic_; - }; - - class Builder { - public: - typedef List Builds; - - inline Builder(): builder(ElementSize::POINTER) {} - inline Builder(decltype(nullptr)): Builder() {} - inline explicit Builder(_::ListBuilder builder): builder(builder) {} - - inline operator Reader() const { return Reader(builder.asReader()); } - inline Reader asReader() const { return Reader(builder.asReader()); } - - inline uint size() const { return unbound(builder.size() / ELEMENTS); } - inline typename T::Builder operator[](uint index) { - KJ_IREQUIRE(index < size()); - return builder.getPointerElement(bounded(index) * ELEMENTS) - .template getBlob(nullptr, ZERO * BYTES); - } - inline void set(uint index, typename T::Reader value) { - KJ_IREQUIRE(index < size()); - builder.getPointerElement(bounded(index) * ELEMENTS).template setBlob(value); - } - inline typename T::Builder init(uint index, uint size) { - KJ_IREQUIRE(index < this->size()); - return builder.getPointerElement(bounded(index) * ELEMENTS) - .template initBlob(bounded(size) * BYTES); - } - inline void adopt(uint index, Orphan&& value) { - KJ_IREQUIRE(index < size()); - builder.getPointerElement(bounded(index) * ELEMENTS).adopt(kj::mv(value.builder)); - } - inline Orphan disown(uint index) { - KJ_IREQUIRE(index < size()); - return Orphan(builder.getPointerElement(bounded(index) * ELEMENTS).disown()); - } - - typedef _::IndexingIterator Iterator; - inline Iterator begin() { return Iterator(this, 0); } - inline Iterator end() { return Iterator(this, size()); } - - private: - _::ListBuilder builder; - template - friend struct _::PointerHelpers; - friend class Orphanage; - template - friend struct ToDynamic_; - }; - - class Pipeline {}; - -private: - inline static _::ListBuilder initPointer(_::PointerBuilder builder, uint size) { - return builder.initList(ElementSize::POINTER, bounded(size) * ELEMENTS); - } - inline static _::ListBuilder getFromPointer(_::PointerBuilder builder, const word* defaultValue) { - return builder.getList(ElementSize::POINTER, defaultValue); - } - inline static _::ListReader getFromPointer( - const _::PointerReader& reader, const word* defaultValue) { - return reader.getList(ElementSize::POINTER, defaultValue); - } - - template - friend struct List; - template - friend struct _::PointerHelpers; -}; - -} // namespace capnp - -#ifdef KJ_STD_COMPAT -namespace std { - -template -struct iterator_traits> - : public std::iterator {}; - -} // namespace std -#endif // KJ_STD_COMPAT - -#endif // CAPNP_LIST_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/membrane.h b/phonelibs/capnp-cpp/include/capnp/membrane.h deleted file mode 100644 index 6fa8a1335d..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/membrane.h +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright (c) 2015 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_MEMBRANE_H_ -#define CAPNP_MEMBRANE_H_ -// In capability theory, a "membrane" is a wrapper around a capability which (usually) forwards -// calls but recursively wraps capabilities in those calls in the same membrane. The purpose of a -// membrane is to enforce a barrier between two capabilities that cannot be bypassed by merely -// introducing new objects. -// -// The most common use case for a membrane is revocation: Say Alice wants to give Bob a capability -// to access Carol, but wants to be able to revoke this capability later. Alice can accomplish this -// by wrapping Carol in a revokable wrapper which passes through calls until such a time as Alice -// indicates it should be revoked, after which all calls through the wrapper will throw exceptions. -// However, a naive wrapper approach has a problem: if Bob makes a call to Carol and sends a new -// capability in that call, or if Carol returns a capability to Bob in the response to a call, then -// the two are now able to communicate using this new capability, which Alice cannot revoke. In -// order to avoid this problem, Alice must use not just a wrapper but a "membrane", which -// recursively wraps all objects that pass through it in either direction. Thus, all connections -// formed between Bob and Carol (originating from Alice's original introduction) can be revoked -// together by revoking the membrane. -// -// Note that when a capability is passed into a membrane and then passed back out, the result is -// the original capability, not a double-membraned capability. This means that in our revocation -// example, if Bob uses his capability to Carol to obtain another capability from her, then send -// it back to her, the capability Carol receives back will NOT be revoked when Bob's access to -// Carol is revoked. Thus Bob can create long-term irrevocable connections. In most practical use -// cases, this is what you want. APIs commonly rely on the fact that a capability obtained and then -// passed back can be recognized as the original capability. -// -// Mark Miller on membranes: http://www.eros-os.org/pipermail/e-lang/2003-January/008434.html - -#include "capability.h" - -namespace capnp { - -class MembranePolicy { - // Applications may implement this interface to define a membrane policy, which allows some - // calls crossing the membrane to be blocked or redirected. - -public: - virtual kj::Maybe inboundCall( - uint64_t interfaceId, uint16_t methodId, Capability::Client target) = 0; - // Given an inbound call (a call originating "outside" the membrane destined for an object - // "inside" the membrane), decides what to do with it. The policy may: - // - // - Return null to indicate that the call should proceed to the destination. All capabilities - // in the parameters or result will be properly wrapped in the same membrane. - // - Return a capability to have the call redirected to that capability. Note that the redirect - // capability will be treated as outside the membrane, so the params and results will not be - // auto-wrapped; however, the callee can easily wrap the returned capability in the membrane - // itself before returning to achieve this effect. - // - Throw an exception to cause the call to fail with that exception. - // - // `target` is the underlying capability (*inside* the membrane) for which the call is destined. - // Generally, the only way you should use `target` is to wrap it in some capability which you - // return as a redirect. The redirect capability may modify the call in some way and send it to - // `target`. Be careful to use `copyIntoMembrane()` and `copyOutOfMembrane()` as appropriate when - // copying parameters or results across the membrane. - // - // Note that since `target` is inside the capability, if you were to directly return it (rather - // than return null), the effect would be that the membrane would be broken: the call would - // proceed directly and any new capabilities introduced through it would not be membraned. You - // generally should not do that. - - virtual kj::Maybe outboundCall( - uint64_t interfaceId, uint16_t methodId, Capability::Client target) = 0; - // Like `inboundCall()`, but applies to calls originating *inside* the membrane and terminating - // outside. - // - // Note: It is strongly recommended that `outboundCall()` returns null in exactly the same cases - // that `inboundCall()` return null. Conversely, for any case where `inboundCall()` would - // redirect or throw, `outboundCall()` should also redirect or throw. Otherwise, you can run - // into inconsistent behavion when a promise is returned across a membrane, and that promise - // later resolves to a capability on the other side of the membrane: calls on the promise - // will enter and then exit the membrane, but calls on the eventual resolution will not cross - // the membrane at all, so it is important that these two cases behave the same. - - virtual kj::Own addRef() = 0; - // Return a new owned pointer to the same policy. - // - // Typically an implementation of MembranePolicy should also inherit kj::Refcounted and implement - // `addRef()` as `return kj::addRef(*this);`. - // - // Note that the membraning system considers two membranes created with the same MembranePolicy - // object actually to be the *same* membrane. This is relevant when an object passes into the - // membrane and then back out (or out and then back in): instead of double-wrapping the object, - // the wrapping will be removed. -}; - -Capability::Client membrane(Capability::Client inner, kj::Own policy); -// Wrap `inner` in a membrane specified by `policy`. `inner` is considered "inside" the membrane, -// while the returned capability should only be called from outside the membrane. - -Capability::Client reverseMembrane(Capability::Client outer, kj::Own policy); -// Like `membrane` but treat the input capability as "outside" the membrane, and return a -// capability appropriate for use inside. -// -// Applications typically won't use this directly; the membraning code automatically sets up -// reverse membranes where needed. - -template -ClientType membrane(ClientType inner, kj::Own policy); -template -ClientType reverseMembrane(ClientType inner, kj::Own policy); -// Convenience templates which return the same interface type as the input. - -template -typename ServerType::Serves::Client membrane( - kj::Own inner, kj::Own policy); -template -typename ServerType::Serves::Client reverseMembrane( - kj::Own inner, kj::Own policy); -// Convenience templates which input a capability server type and return the appropriate client -// type. - -template -Orphan::Reads> copyIntoMembrane( - Reader&& from, Orphanage to, kj::Own policy); -// Copy a Cap'n Proto object (e.g. struct or list), adding the given membrane to any capabilities -// found within it. `from` is interpreted as "outside" the membrane while `to` is "inside". - -template -Orphan::Reads> copyOutOfMembrane( - Reader&& from, Orphanage to, kj::Own policy); -// Like copyIntoMembrane() except that `from` is "inside" the membrane and `to` is "outside". - -// ======================================================================================= -// inline implementation details - -template -ClientType membrane(ClientType inner, kj::Own policy) { - return membrane(Capability::Client(kj::mv(inner)), kj::mv(policy)) - .castAs(); -} -template -ClientType reverseMembrane(ClientType inner, kj::Own policy) { - return reverseMembrane(Capability::Client(kj::mv(inner)), kj::mv(policy)) - .castAs(); -} - -template -typename ServerType::Serves::Client membrane( - kj::Own inner, kj::Own policy) { - return membrane(Capability::Client(kj::mv(inner)), kj::mv(policy)) - .castAs(); -} -template -typename ServerType::Serves::Client reverseMembrane( - kj::Own inner, kj::Own policy) { - return reverseMembrane(Capability::Client(kj::mv(inner)), kj::mv(policy)) - .castAs(); -} - -namespace _ { // private - -OrphanBuilder copyOutOfMembrane(PointerReader from, Orphanage to, - kj::Own policy, bool reverse); -OrphanBuilder copyOutOfMembrane(StructReader from, Orphanage to, - kj::Own policy, bool reverse); -OrphanBuilder copyOutOfMembrane(ListReader from, Orphanage to, - kj::Own policy, bool reverse); - -} // namespace _ (private) - -template -Orphan::Reads> copyIntoMembrane( - Reader&& from, Orphanage to, kj::Own policy) { - return _::copyOutOfMembrane( - _::PointerHelpers::Reads>::getInternalReader(from), - to, kj::mv(policy), true); -} - -template -Orphan::Reads> copyOutOfMembrane( - Reader&& from, Orphanage to, kj::Own policy) { - return _::copyOutOfMembrane( - _::PointerHelpers::Reads>::getInternalReader(from), - to, kj::mv(policy), false); -} - -} // namespace capnp - -#endif // CAPNP_MEMBRANE_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/message.h b/phonelibs/capnp-cpp/include/capnp/message.h deleted file mode 100644 index b4d5e9fc82..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/message.h +++ /dev/null @@ -1,508 +0,0 @@ -// Copyright (c) 2013-2016 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#include -#include -#include -#include -#include "common.h" -#include "layout.h" -#include "any.h" - -#ifndef CAPNP_MESSAGE_H_ -#define CAPNP_MESSAGE_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -namespace capnp { - -namespace _ { // private - class ReaderArena; - class BuilderArena; -} - -class StructSchema; -class Orphanage; -template -class Orphan; - -// ======================================================================================= - -struct ReaderOptions { - // Options controlling how data is read. - - uint64_t traversalLimitInWords = 8 * 1024 * 1024; - // Limits how many total words of data are allowed to be traversed. Traversal is counted when - // a new struct or list builder is obtained, e.g. from a get() accessor. This means that calling - // the getter for the same sub-struct multiple times will cause it to be double-counted. Once - // the traversal limit is reached, an error will be reported. - // - // This limit exists for security reasons. It is possible for an attacker to construct a message - // in which multiple pointers point at the same location. This is technically invalid, but hard - // to detect. Using such a message, an attacker could cause a message which is small on the wire - // to appear much larger when actually traversed, possibly exhausting server resources leading to - // denial-of-service. - // - // It makes sense to set a traversal limit that is much larger than the underlying message. - // Together with sensible coding practices (e.g. trying to avoid calling sub-object getters - // multiple times, which is expensive anyway), this should provide adequate protection without - // inconvenience. - // - // The default limit is 64 MiB. This may or may not be a sensible number for any given use case, - // but probably at least prevents easy exploitation while also avoiding causing problems in most - // typical cases. - - int nestingLimit = 64; - // Limits how deeply-nested a message structure can be, e.g. structs containing other structs or - // lists of structs. - // - // Like the traversal limit, this limit exists for security reasons. Since it is common to use - // recursive code to traverse recursive data structures, an attacker could easily cause a stack - // overflow by sending a very-deeply-nested (or even cyclic) message, without the message even - // being very large. The default limit of 64 is probably low enough to prevent any chance of - // stack overflow, yet high enough that it is never a problem in practice. -}; - -class MessageReader { - // Abstract interface for an object used to read a Cap'n Proto message. Subclasses of - // MessageReader are responsible for reading the raw, flat message content. Callers should - // usually call `messageReader.getRoot()` to get a `MyStructType::Reader` - // representing the root of the message, then use that to traverse the message content. - // - // Some common subclasses of `MessageReader` include `SegmentArrayMessageReader`, whose - // constructor accepts pointers to the raw data, and `StreamFdMessageReader` (from - // `serialize.h`), which reads the message from a file descriptor. One might implement other - // subclasses to handle things like reading from shared memory segments, mmap()ed files, etc. - -public: - MessageReader(ReaderOptions options); - // It is suggested that subclasses take ReaderOptions as a constructor parameter, but give it a - // default value of "ReaderOptions()". The base class constructor doesn't have a default value - // in order to remind subclasses that they really need to give the user a way to provide this. - - virtual ~MessageReader() noexcept(false); - - virtual kj::ArrayPtr getSegment(uint id) = 0; - // Gets the segment with the given ID, or returns null if no such segment exists. This method - // will be called at most once for each segment ID. - - inline const ReaderOptions& getOptions(); - // Get the options passed to the constructor. - - template - typename RootType::Reader getRoot(); - // Get the root struct of the message, interpreting it as the given struct type. - - template - typename RootType::Reader getRoot(SchemaType schema); - // Dynamically interpret the root struct of the message using the given schema (a StructSchema). - // RootType in this case must be DynamicStruct, and you must #include to - // use this. - - bool isCanonical(); - // Returns whether the message encoded in the reader is in canonical form. - -private: - ReaderOptions options; - - // Space in which we can construct a ReaderArena. We don't use ReaderArena directly here - // because we don't want clients to have to #include arena.h, which itself includes a bunch of - // big STL headers. We don't use a pointer to a ReaderArena because that would require an - // extra malloc on every message which could be expensive when processing small messages. - void* arenaSpace[15 + sizeof(kj::MutexGuarded) / sizeof(void*)]; - bool allocatedArena; - - _::ReaderArena* arena() { return reinterpret_cast<_::ReaderArena*>(arenaSpace); } - AnyPointer::Reader getRootInternal(); -}; - -class MessageBuilder { - // Abstract interface for an object used to allocate and build a message. Subclasses of - // MessageBuilder are responsible for allocating the space in which the message will be written. - // The most common subclass is `MallocMessageBuilder`, but other subclasses may be used to do - // tricky things like allocate messages in shared memory or mmap()ed files. - // - // Creating a new message ususually means allocating a new MessageBuilder (ideally on the stack) - // and then calling `messageBuilder.initRoot()` to get a `MyStructType::Builder`. - // That, in turn, can be used to fill in the message content. When done, you can call - // `messageBuilder.getSegmentsForOutput()` to get a list of flat data arrays containing the - // message. - -public: - MessageBuilder(); - virtual ~MessageBuilder() noexcept(false); - KJ_DISALLOW_COPY(MessageBuilder); - - struct SegmentInit { - kj::ArrayPtr space; - - size_t wordsUsed; - // Number of words in `space` which are used; the rest are free space in which additional - // objects may be allocated. - }; - - explicit MessageBuilder(kj::ArrayPtr segments); - // Create a MessageBuilder backed by existing memory. This is an advanced interface that most - // people should not use. THIS METHOD IS INSECURE; see below. - // - // This allows a MessageBuilder to be constructed to modify an in-memory message without first - // making a copy of the content. This is especially useful in conjunction with mmap(). - // - // The contents of each segment must outlive the MessageBuilder, but the SegmentInit array itself - // only need outlive the constructor. - // - // SECURITY: Do not use this in conjunction with untrusted data. This constructor assumes that - // the input message is valid. This constructor is designed to be used with data you control, - // e.g. an mmap'd file which is owned and accessed by only one program. When reading data you - // do not trust, you *must* load it into a Reader and then copy into a Builder as a means of - // validating the content. - // - // WARNING: It is NOT safe to initialize a MessageBuilder in this way from memory that is - // currently in use by another MessageBuilder or MessageReader. Other readers/builders will - // not observe changes to the segment sizes nor newly-allocated segments caused by allocating - // new objects in this message. - - virtual kj::ArrayPtr allocateSegment(uint minimumSize) = 0; - // Allocates an array of at least the given number of words, throwing an exception or crashing if - // this is not possible. It is expected that this method will usually return more space than - // requested, and the caller should use that extra space as much as possible before allocating - // more. The returned space remains valid at least until the MessageBuilder is destroyed. - // - // Cap'n Proto will only call this once at a time, so the subclass need not worry about - // thread-safety. - - template - typename RootType::Builder initRoot(); - // Initialize the root struct of the message as the given struct type. - - template - void setRoot(Reader&& value); - // Set the root struct to a deep copy of the given struct. - - template - typename RootType::Builder getRoot(); - // Get the root struct of the message, interpreting it as the given struct type. - - template - typename RootType::Builder getRoot(SchemaType schema); - // Dynamically interpret the root struct of the message using the given schema (a StructSchema). - // RootType in this case must be DynamicStruct, and you must #include to - // use this. - - template - typename RootType::Builder initRoot(SchemaType schema); - // Dynamically init the root struct of the message using the given schema (a StructSchema). - // RootType in this case must be DynamicStruct, and you must #include to - // use this. - - template - void adoptRoot(Orphan&& orphan); - // Like setRoot() but adopts the orphan without copying. - - kj::ArrayPtr> getSegmentsForOutput(); - // Get the raw data that makes up the message. - - Orphanage getOrphanage(); - - bool isCanonical(); - // Check whether the message builder is in canonical form - -private: - void* arenaSpace[22]; - // Space in which we can construct a BuilderArena. We don't use BuilderArena directly here - // because we don't want clients to have to #include arena.h, which itself includes a bunch of - // big STL headers. We don't use a pointer to a BuilderArena because that would require an - // extra malloc on every message which could be expensive when processing small messages. - - bool allocatedArena = false; - // We have to initialize the arena lazily because when we do so we want to allocate the root - // pointer immediately, and this will allocate a segment, which requires a virtual function - // call on the MessageBuilder. We can't do such a call in the constructor since the subclass - // isn't constructed yet. This is kind of annoying because it means that getOrphanage() is - // not thread-safe, but that shouldn't be a huge deal... - - _::BuilderArena* arena() { return reinterpret_cast<_::BuilderArena*>(arenaSpace); } - _::SegmentBuilder* getRootSegment(); - AnyPointer::Builder getRootInternal(); -}; - -template -typename RootType::Reader readMessageUnchecked(const word* data); -// IF THE INPUT IS INVALID, THIS MAY CRASH, CORRUPT MEMORY, CREATE A SECURITY HOLE IN YOUR APP, -// MURDER YOUR FIRST-BORN CHILD, AND/OR BRING ABOUT ETERNAL DAMNATION ON ALL OF HUMANITY. DO NOT -// USE UNLESS YOU UNDERSTAND THE CONSEQUENCES. -// -// Given a pointer to a known-valid message located in a single contiguous memory segment, -// returns a reader for that message. No bounds-checking will be done while traversing this -// message. Use this only if you have already verified that all pointers are valid and in-bounds, -// and there are no far pointers in the message. -// -// To create a message that can be passed to this function, build a message using a MallocAllocator -// whose preferred segment size is larger than the message size. This guarantees that the message -// will be allocated as a single segment, meaning getSegmentsForOutput() returns a single word -// array. That word array is your message; you may pass a pointer to its first word into -// readMessageUnchecked() to read the message. -// -// This can be particularly handy for embedding messages in generated code: you can -// embed the raw bytes (using AlignedData) then make a Reader for it using this. This is the way -// default values are embedded in code generated by the Cap'n Proto compiler. E.g., if you have -// a message MyMessage, you can read its default value like so: -// MyMessage::Reader reader = Message::readMessageUnchecked(MyMessage::DEFAULT.words); -// -// To sanitize a message from an untrusted source such that it can be safely passed to -// readMessageUnchecked(), use copyToUnchecked(). - -template -void copyToUnchecked(Reader&& reader, kj::ArrayPtr uncheckedBuffer); -// Copy the content of the given reader into the given buffer, such that it can safely be passed to -// readMessageUnchecked(). The buffer's size must be exactly reader.totalSizeInWords() + 1, -// otherwise an exception will be thrown. The buffer must be zero'd before calling. - -template -typename RootType::Reader readDataStruct(kj::ArrayPtr data); -// Interprets the given data as a single, data-only struct. Only primitive fields (booleans, -// numbers, and enums) will be readable; all pointers will be null. This is useful if you want -// to use Cap'n Proto as a language/platform-neutral way to pack some bits. -// -// The input is a word array rather than a byte array to enforce alignment. If you have a byte -// array which you know is word-aligned (or if your platform supports unaligned reads and you don't -// mind the performance penalty), then you can use `reinterpret_cast` to convert a byte array into -// a word array: -// -// kj::arrayPtr(reinterpret_cast(bytes.begin()), -// reinterpret_cast(bytes.end())) - -template -typename kj::ArrayPtr writeDataStruct(BuilderType builder); -// Given a struct builder, get the underlying data section as a word array, suitable for passing -// to `readDataStruct()`. -// -// Note that you may call `.toBytes()` on the returned value to convert to `ArrayPtr`. - -template -static typename Type::Reader defaultValue(); -// Get a default instance of the given struct or list type. -// -// TODO(cleanup): Find a better home for this function? - -// ======================================================================================= - -class SegmentArrayMessageReader: public MessageReader { - // A simple MessageReader that reads from an array of word arrays representing all segments. - // In particular you can read directly from the output of MessageBuilder::getSegmentsForOutput() - // (although it would probably make more sense to call builder.getRoot().asReader() in that case). - -public: - SegmentArrayMessageReader(kj::ArrayPtr> segments, - ReaderOptions options = ReaderOptions()); - // Creates a message pointing at the given segment array, without taking ownership of the - // segments. All arrays passed in must remain valid until the MessageReader is destroyed. - - KJ_DISALLOW_COPY(SegmentArrayMessageReader); - ~SegmentArrayMessageReader() noexcept(false); - - virtual kj::ArrayPtr getSegment(uint id) override; - -private: - kj::ArrayPtr> segments; -}; - -enum class AllocationStrategy: uint8_t { - FIXED_SIZE, - // The builder will prefer to allocate the same amount of space for each segment with no - // heuristic growth. It will still allocate larger segments when the preferred size is too small - // for some single object. This mode is generally not recommended, but can be particularly useful - // for testing in order to force a message to allocate a predictable number of segments. Note - // that you can force every single object in the message to be located in a separate segment by - // using this mode with firstSegmentWords = 0. - - GROW_HEURISTICALLY - // The builder will heuristically decide how much space to allocate for each segment. Each - // allocated segment will be progressively larger than the previous segments on the assumption - // that message sizes are exponentially distributed. The total number of segments that will be - // allocated for a message of size n is O(log n). -}; - -constexpr uint SUGGESTED_FIRST_SEGMENT_WORDS = 1024; -constexpr AllocationStrategy SUGGESTED_ALLOCATION_STRATEGY = AllocationStrategy::GROW_HEURISTICALLY; - -class MallocMessageBuilder: public MessageBuilder { - // A simple MessageBuilder that uses malloc() (actually, calloc()) to allocate segments. This - // implementation should be reasonable for any case that doesn't require writing the message to - // a specific location in memory. - -public: - explicit MallocMessageBuilder(uint firstSegmentWords = SUGGESTED_FIRST_SEGMENT_WORDS, - AllocationStrategy allocationStrategy = SUGGESTED_ALLOCATION_STRATEGY); - // Creates a BuilderContext which allocates at least the given number of words for the first - // segment, and then uses the given strategy to decide how much to allocate for subsequent - // segments. When choosing a value for firstSegmentWords, consider that: - // 1) Reading and writing messages gets slower when multiple segments are involved, so it's good - // if most messages fit in a single segment. - // 2) Unused bytes will not be written to the wire, so generally it is not a big deal to allocate - // more space than you need. It only becomes problematic if you are allocating many messages - // in parallel and thus use lots of memory, or if you allocate so much extra space that just - // zeroing it out becomes a bottleneck. - // The defaults have been chosen to be reasonable for most people, so don't change them unless you - // have reason to believe you need to. - - explicit MallocMessageBuilder(kj::ArrayPtr firstSegment, - AllocationStrategy allocationStrategy = SUGGESTED_ALLOCATION_STRATEGY); - // This version always returns the given array for the first segment, and then proceeds with the - // allocation strategy. This is useful for optimization when building lots of small messages in - // a tight loop: you can reuse the space for the first segment. - // - // firstSegment MUST be zero-initialized. MallocMessageBuilder's destructor will write new zeros - // over any space that was used so that it can be reused. - - KJ_DISALLOW_COPY(MallocMessageBuilder); - virtual ~MallocMessageBuilder() noexcept(false); - - virtual kj::ArrayPtr allocateSegment(uint minimumSize) override; - -private: - uint nextSize; - AllocationStrategy allocationStrategy; - - bool ownFirstSegment; - bool returnedFirstSegment; - - void* firstSegment; - - struct MoreSegments; - kj::Maybe> moreSegments; -}; - -class FlatMessageBuilder: public MessageBuilder { - // THIS IS NOT THE CLASS YOU'RE LOOKING FOR. - // - // If you want to write a message into already-existing scratch space, use `MallocMessageBuilder` - // and pass the scratch space to its constructor. It will then only fall back to malloc() if - // the scratch space is not large enough. - // - // Do NOT use this class unless you really know what you're doing. This class is problematic - // because it requires advance knowledge of the size of your message, which is usually impossible - // to determine without actually building the message. The class was created primarily to - // implement `copyToUnchecked()`, which itself exists only to support other internal parts of - // the Cap'n Proto implementation. - -public: - explicit FlatMessageBuilder(kj::ArrayPtr array); - KJ_DISALLOW_COPY(FlatMessageBuilder); - virtual ~FlatMessageBuilder() noexcept(false); - - void requireFilled(); - // Throws an exception if the flat array is not exactly full. - - virtual kj::ArrayPtr allocateSegment(uint minimumSize) override; - -private: - kj::ArrayPtr array; - bool allocated; -}; - -// ======================================================================================= -// implementation details - -inline const ReaderOptions& MessageReader::getOptions() { - return options; -} - -template -inline typename RootType::Reader MessageReader::getRoot() { - return getRootInternal().getAs(); -} - -template -inline typename RootType::Builder MessageBuilder::initRoot() { - return getRootInternal().initAs(); -} - -template -inline void MessageBuilder::setRoot(Reader&& value) { - getRootInternal().setAs>(value); -} - -template -inline typename RootType::Builder MessageBuilder::getRoot() { - return getRootInternal().getAs(); -} - -template -void MessageBuilder::adoptRoot(Orphan&& orphan) { - return getRootInternal().adopt(kj::mv(orphan)); -} - -template -typename RootType::Reader MessageReader::getRoot(SchemaType schema) { - return getRootInternal().getAs(schema); -} - -template -typename RootType::Builder MessageBuilder::getRoot(SchemaType schema) { - return getRootInternal().getAs(schema); -} - -template -typename RootType::Builder MessageBuilder::initRoot(SchemaType schema) { - return getRootInternal().initAs(schema); -} - -template -typename RootType::Reader readMessageUnchecked(const word* data) { - return AnyPointer::Reader(_::PointerReader::getRootUnchecked(data)).getAs(); -} - -template -void copyToUnchecked(Reader&& reader, kj::ArrayPtr uncheckedBuffer) { - FlatMessageBuilder builder(uncheckedBuffer); - builder.setRoot(kj::fwd(reader)); - builder.requireFilled(); -} - -template -typename RootType::Reader readDataStruct(kj::ArrayPtr data) { - return typename RootType::Reader(_::StructReader(data)); -} - -template -typename kj::ArrayPtr writeDataStruct(BuilderType builder) { - auto bytes = _::PointerHelpers>::getInternalBuilder(kj::mv(builder)) - .getDataSectionAsBlob(); - return kj::arrayPtr(reinterpret_cast(bytes.begin()), - reinterpret_cast(bytes.end())); -} - -template -static typename Type::Reader defaultValue() { - return typename Type::Reader(_::StructReader()); -} - -template -kj::Array canonicalize(T&& reader) { - return _::PointerHelpers>::getInternalReader(reader).canonicalize(); -} - -} // namespace capnp - -#endif // CAPNP_MESSAGE_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/orphan.h b/phonelibs/capnp-cpp/include/capnp/orphan.h deleted file mode 100644 index 8c8b9a6054..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/orphan.h +++ /dev/null @@ -1,440 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_ORPHAN_H_ -#define CAPNP_ORPHAN_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include "layout.h" - -namespace capnp { - -class StructSchema; -class ListSchema; -struct DynamicStruct; -struct DynamicList; -namespace _ { struct OrphanageInternal; } - -template -class Orphan { - // Represents an object which is allocated within some message builder but has no pointers - // pointing at it. An Orphan can later be "adopted" by some other object as one of that object's - // fields, without having to copy the orphan. For a field `foo` of pointer type, the generated - // code will define builder methods `void adoptFoo(Orphan)` and `Orphan disownFoo()`. - // Orphans can also be created independently of any parent using an Orphanage. - // - // `Orphan` can be moved but not copied, like `Own`, so that it is impossible for one - // orphan to be adopted multiple times. If an orphan is destroyed without being adopted, its - // contents are zero'd out (and possibly reused, if we ever implement the ability to reuse space - // in a message arena). - -public: - Orphan() = default; - KJ_DISALLOW_COPY(Orphan); - Orphan(Orphan&&) = default; - Orphan& operator=(Orphan&&) = default; - inline Orphan(_::OrphanBuilder&& builder): builder(kj::mv(builder)) {} - - inline BuilderFor get(); - // Get the underlying builder. If the orphan is null, this will allocate and return a default - // object rather than crash. This is done for security -- otherwise, you might enable a DoS - // attack any time you disown a field and fail to check if it is null. In the case of structs, - // this means that the orphan is no longer null after get() returns. In the case of lists, - // no actual object is allocated since a simple empty ListBuilder can be returned. - - inline ReaderFor getReader() const; - - inline bool operator==(decltype(nullptr)) const { return builder == nullptr; } - inline bool operator!=(decltype(nullptr)) const { return builder != nullptr; } - - inline void truncate(uint size); - // Resize an object (which must be a list or a blob) to the given size. - // - // If the new size is less than the original, the remaining elements will be discarded. The - // list is never moved in this case. If the list happens to be located at the end of its segment - // (which is always true if the list was the last thing allocated), the removed memory will be - // reclaimed (reducing the messag size), otherwise it is simply zeroed. The reclaiming behavior - // is particularly useful for allocating buffer space when you aren't sure how much space you - // actually need: you can pre-allocate, say, a 4k byte array, read() from a file into it, and - // then truncate it back to the amount of space actually used. - // - // If the new size is greater than the original, the list is extended with default values. If - // the list is the last object in its segment *and* there is enough space left in the segment to - // extend it to cover the new values, then the list is extended in-place. Otherwise, it must be - // moved to a new location, leaving a zero'd hole in the previous space that won't be filled. - // This copy is shallow; sub-objects will simply be reparented, not copied. - // - // Any existing readers or builders pointing at the object are invalidated by this call (even if - // it doesn't move). You must call `get()` or `getReader()` again to get the new, valid pointer. - -private: - _::OrphanBuilder builder; - - template - friend struct _::PointerHelpers; - template - friend struct List; - template - friend class Orphan; - friend class Orphanage; - friend class MessageBuilder; -}; - -class Orphanage: private kj::DisallowConstCopy { - // Use to directly allocate Orphan objects, without having a parent object allocate and then - // disown the object. - -public: - inline Orphanage(): arena(nullptr) {} - - template - static Orphanage getForMessageContaining(BuilderType builder); - // Construct an Orphanage that allocates within the message containing the given Builder. This - // allows the constructed Orphans to be adopted by objects within said message. - // - // This constructor takes the builder rather than having the builder have a getOrphanage() method - // because this is an advanced feature and we don't want to pollute the builder APIs with it. - // - // Note that if you have a direct pointer to the `MessageBuilder`, you can simply call its - // `getOrphanage()` method. - - template - Orphan newOrphan() const; - // Allocate a new orphaned struct. - - template - Orphan newOrphan(uint size) const; - // Allocate a new orphaned list or blob. - - Orphan newOrphan(StructSchema schema) const; - // Dynamically create an orphan struct with the given schema. You must - // #include to use this. - - Orphan newOrphan(ListSchema schema, uint size) const; - // Dynamically create an orphan list with the given schema. You must #include - // to use this. - - template - Orphan> newOrphanCopy(Reader copyFrom) const; - // Allocate a new orphaned object (struct, list, or blob) and initialize it as a copy of the - // given object. - - template - Orphan>>> newOrphanConcat(kj::ArrayPtr lists) const; - template - Orphan>>> newOrphanConcat(kj::ArrayPtr lists) const; - // Given an array of List readers, copy and concatenate the lists, creating a new Orphan. - // - // Note that compared to allocating the list yourself and using `setWithCaveats()` to set each - // item, this method avoids the "caveats": the new list will be allocated with the element size - // being the maximum of that from all the input lists. This is particularly important when - // concatenating struct lists: if the lists were created using a newer version of the protocol - // in which some new fields had been added to the struct, using `setWithCaveats()` would - // truncate off those new fields. - - Orphan referenceExternalData(Data::Reader data) const; - // Creates an Orphan that points at an existing region of memory (e.g. from another message) - // without copying it. There are some SEVERE restrictions on how this can be used: - // - The memory must remain valid until the `MessageBuilder` is destroyed (even if the orphan is - // abandoned). - // - Because the data is const, you will not be allowed to obtain a `Data::Builder` - // for this blob. Any call which would return such a builder will throw an exception. You - // can, however, obtain a Reader, e.g. via orphan.getReader() or from a parent Reader (once - // the orphan is adopted). It is your responsibility to make sure your code can deal with - // these problems when using this optimization; if you can't, allocate a copy instead. - // - `data.begin()` must be aligned to a machine word boundary (32-bit or 64-bit depending on - // the CPU). Any pointer returned by malloc() as well as any data blob obtained from another - // Cap'n Proto message satisfies this. - // - If `data.size()` is not a multiple of 8, extra bytes past data.end() up until the next 8-byte - // boundary will be visible in the raw message when it is written out. Thus, there must be no - // secrets in these bytes. Data blobs obtained from other Cap'n Proto messages should be safe - // as these bytes should be zero (unless the sender had the same problem). - // - // The array will actually become one of the message's segments. The data can thus be adopted - // into the message tree without copying it. This is particularly useful when referencing very - // large blobs, such as whole mmap'd files. - -private: - _::BuilderArena* arena; - _::CapTableBuilder* capTable; - - inline explicit Orphanage(_::BuilderArena* arena, _::CapTableBuilder* capTable) - : arena(arena), capTable(capTable) {} - - template - struct GetInnerBuilder; - template - struct GetInnerReader; - template - struct NewOrphanListImpl; - - friend class MessageBuilder; - friend struct _::OrphanageInternal; -}; - -// ======================================================================================= -// Inline implementation details. - -namespace _ { // private - -template -struct OrphanGetImpl; - -template -struct OrphanGetImpl { - static inline void truncateListOf(_::OrphanBuilder& builder, ElementCount size) { - builder.truncate(size, _::elementSizeForType()); - } -}; - -template -struct OrphanGetImpl { - static inline typename T::Builder apply(_::OrphanBuilder& builder) { - return typename T::Builder(builder.asStruct(_::structSize())); - } - static inline typename T::Reader applyReader(const _::OrphanBuilder& builder) { - return typename T::Reader(builder.asStructReader(_::structSize())); - } - static inline void truncateListOf(_::OrphanBuilder& builder, ElementCount size) { - builder.truncate(size, _::structSize()); - } -}; - -#if !CAPNP_LITE -template -struct OrphanGetImpl { - static inline typename T::Client apply(_::OrphanBuilder& builder) { - return typename T::Client(builder.asCapability()); - } - static inline typename T::Client applyReader(const _::OrphanBuilder& builder) { - return typename T::Client(builder.asCapability()); - } - static inline void truncateListOf(_::OrphanBuilder& builder, ElementCount size) { - builder.truncate(size, ElementSize::POINTER); - } -}; -#endif // !CAPNP_LITE - -template -struct OrphanGetImpl, Kind::LIST> { - static inline typename List::Builder apply(_::OrphanBuilder& builder) { - return typename List::Builder(builder.asList(_::ElementSizeForType::value)); - } - static inline typename List::Reader applyReader(const _::OrphanBuilder& builder) { - return typename List::Reader(builder.asListReader(_::ElementSizeForType::value)); - } - static inline void truncateListOf(_::OrphanBuilder& builder, ElementCount size) { - builder.truncate(size, ElementSize::POINTER); - } -}; - -template -struct OrphanGetImpl, Kind::LIST> { - static inline typename List::Builder apply(_::OrphanBuilder& builder) { - return typename List::Builder(builder.asStructList(_::structSize())); - } - static inline typename List::Reader applyReader(const _::OrphanBuilder& builder) { - return typename List::Reader(builder.asListReader(_::ElementSizeForType::value)); - } - static inline void truncateListOf(_::OrphanBuilder& builder, ElementCount size) { - builder.truncate(size, ElementSize::POINTER); - } -}; - -template <> -struct OrphanGetImpl { - static inline Text::Builder apply(_::OrphanBuilder& builder) { - return Text::Builder(builder.asText()); - } - static inline Text::Reader applyReader(const _::OrphanBuilder& builder) { - return Text::Reader(builder.asTextReader()); - } - static inline void truncateListOf(_::OrphanBuilder& builder, ElementCount size) { - builder.truncate(size, ElementSize::POINTER); - } -}; - -template <> -struct OrphanGetImpl { - static inline Data::Builder apply(_::OrphanBuilder& builder) { - return Data::Builder(builder.asData()); - } - static inline Data::Reader applyReader(const _::OrphanBuilder& builder) { - return Data::Reader(builder.asDataReader()); - } - static inline void truncateListOf(_::OrphanBuilder& builder, ElementCount size) { - builder.truncate(size, ElementSize::POINTER); - } -}; - -struct OrphanageInternal { - static inline _::BuilderArena* getArena(Orphanage orphanage) { return orphanage.arena; } - static inline _::CapTableBuilder* getCapTable(Orphanage orphanage) { return orphanage.capTable; } -}; - -} // namespace _ (private) - -template -inline BuilderFor Orphan::get() { - return _::OrphanGetImpl::apply(builder); -} - -template -inline ReaderFor Orphan::getReader() const { - return _::OrphanGetImpl::applyReader(builder); -} - -template -inline void Orphan::truncate(uint size) { - _::OrphanGetImpl>::truncateListOf(builder, bounded(size) * ELEMENTS); -} - -template <> -inline void Orphan::truncate(uint size) { - builder.truncateText(bounded(size) * ELEMENTS); -} - -template <> -inline void Orphan::truncate(uint size) { - builder.truncate(bounded(size) * ELEMENTS, ElementSize::BYTE); -} - -template -struct Orphanage::GetInnerBuilder { - static inline _::StructBuilder apply(typename T::Builder& t) { - return t._builder; - } -}; - -template -struct Orphanage::GetInnerBuilder { - static inline _::ListBuilder apply(typename T::Builder& t) { - return t.builder; - } -}; - -template -Orphanage Orphanage::getForMessageContaining(BuilderType builder) { - auto inner = GetInnerBuilder>::apply(builder); - return Orphanage(inner.getArena(), inner.getCapTable()); -} - -template -Orphan Orphanage::newOrphan() const { - return Orphan(_::OrphanBuilder::initStruct(arena, capTable, _::structSize())); -} - -template -struct Orphanage::NewOrphanListImpl> { - static inline _::OrphanBuilder apply( - _::BuilderArena* arena, _::CapTableBuilder* capTable, uint size) { - return _::OrphanBuilder::initList( - arena, capTable, bounded(size) * ELEMENTS, _::ElementSizeForType::value); - } -}; - -template -struct Orphanage::NewOrphanListImpl> { - static inline _::OrphanBuilder apply( - _::BuilderArena* arena, _::CapTableBuilder* capTable, uint size) { - return _::OrphanBuilder::initStructList( - arena, capTable, bounded(size) * ELEMENTS, _::structSize()); - } -}; - -template <> -struct Orphanage::NewOrphanListImpl { - static inline _::OrphanBuilder apply( - _::BuilderArena* arena, _::CapTableBuilder* capTable, uint size) { - return _::OrphanBuilder::initText(arena, capTable, bounded(size) * BYTES); - } -}; - -template <> -struct Orphanage::NewOrphanListImpl { - static inline _::OrphanBuilder apply( - _::BuilderArena* arena, _::CapTableBuilder* capTable, uint size) { - return _::OrphanBuilder::initData(arena, capTable, bounded(size) * BYTES); - } -}; - -template -Orphan Orphanage::newOrphan(uint size) const { - return Orphan(NewOrphanListImpl::apply(arena, capTable, size)); -} - -template -struct Orphanage::GetInnerReader { - static inline _::StructReader apply(const typename T::Reader& t) { - return t._reader; - } -}; - -template -struct Orphanage::GetInnerReader { - static inline _::ListReader apply(const typename T::Reader& t) { - return t.reader; - } -}; - -template -struct Orphanage::GetInnerReader { - static inline const typename T::Reader& apply(const typename T::Reader& t) { - return t; - } -}; - -template -inline Orphan> Orphanage::newOrphanCopy(Reader copyFrom) const { - return Orphan>(_::OrphanBuilder::copy( - arena, capTable, GetInnerReader>::apply(copyFrom))); -} - -template -inline Orphan>>> -Orphanage::newOrphanConcat(kj::ArrayPtr lists) const { - return newOrphanConcat(kj::implicitCast>(lists)); -} -template -inline Orphan>>> -Orphanage::newOrphanConcat(kj::ArrayPtr lists) const { - // Optimization / simplification: Rely on List::Reader containing nothing except a - // _::ListReader. - static_assert(sizeof(T) == sizeof(_::ListReader), "lists are not bare readers?"); - kj::ArrayPtr raw( - reinterpret_cast(lists.begin()), lists.size()); - typedef ListElementType> Element; - return Orphan>( - _::OrphanBuilder::concat(arena, capTable, - _::elementSizeForType(), - _::minStructSizeForElement(), raw)); -} - -inline Orphan Orphanage::referenceExternalData(Data::Reader data) const { - return Orphan(_::OrphanBuilder::referenceExternalData(arena, data)); -} - -} // namespace capnp - -#endif // CAPNP_ORPHAN_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/persistent.capnp b/phonelibs/capnp-cpp/include/capnp/persistent.capnp deleted file mode 100644 index a13b47168a..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/persistent.capnp +++ /dev/null @@ -1,139 +0,0 @@ -# Copyright (c) 2014 Sandstorm Development Group, Inc. and contributors -# Licensed under the MIT License: -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -@0xb8630836983feed7; - -$import "/capnp/c++.capnp".namespace("capnp"); - -interface Persistent@0xc8cb212fcd9f5691(SturdyRef, Owner) { - # Interface implemented by capabilities that outlive a single connection. A client may save() - # the capability, producing a SturdyRef. The SturdyRef can be stored to disk, then later used to - # obtain a new reference to the capability on a future connection. - # - # The exact format of SturdyRef depends on the "realm" in which the SturdyRef appears. A "realm" - # is an abstract space in which all SturdyRefs have the same format and refer to the same set of - # resources. Every vat is in exactly one realm. All capability clients within that vat must - # produce SturdyRefs of the format appropriate for the realm. - # - # Similarly, every VatNetwork also resides in a particular realm. Usually, a vat's "realm" - # corresponds to the realm of its main VatNetwork. However, a Vat can in fact communicate over - # a VatNetwork in a different realm -- in this case, all SturdyRefs need to be transformed when - # coming or going through said VatNetwork. The RPC system has hooks for registering - # transformation callbacks for this purpose. - # - # Since the format of SturdyRef is realm-dependent, it is not defined here. An application should - # choose an appropriate realm for itself as part of its design. Note that under Sandstorm, every - # application exists in its own realm and is therefore free to define its own SturdyRef format; - # the Sandstorm platform handles translating between realms. - # - # Note that whether a capability is persistent is often orthogonal to its type. In these cases, - # the capability's interface should NOT inherit `Persistent`; instead, just perform a cast at - # runtime. It's not type-safe, but trying to be type-safe in these cases will likely lead to - # tears. In cases where a particular interface only makes sense on persistent capabilities, it - # still should not explicitly inherit Persistent because the `SturdyRef` and `Owner` types will - # vary between realms (they may even be different at the call site than they are on the - # implementation). Instead, mark persistent interfaces with the $persistent annotation (defined - # below). - # - # Sealing - # ------- - # - # As an added security measure, SturdyRefs may be "sealed" to a particular owner, such that - # if the SturdyRef itself leaks to a third party, that party cannot actually restore it because - # they are not the owner. To restore a sealed capability, you must first prove to its host that - # you are the rightful owner. The precise mechanism for this authentication is defined by the - # realm. - # - # Sealing is a defense-in-depth mechanism meant to mitigate damage in the case of catastrophic - # attacks. For example, say an attacker temporarily gains read access to a database full of - # SturdyRefs: it would be unfortunate if it were then necessary to revoke every single reference - # in the database to prevent the attacker from using them. - # - # In general, an "owner" is a course-grained identity. Because capability-based security is still - # the primary mechanism of security, it is not necessary nor desirable to have a separate "owner" - # identity for every single process or object; that is exactly what capabilities are supposed to - # avoid! Instead, it makes sense for an "owner" to literally identify the owner of the machines - # where the capability is stored. If untrusted third parties are able to run arbitrary code on - # said machines, then the sandbox for that code should be designed using Distributed Confinement - # such that the third-party code never sees the bits of the SturdyRefs and cannot directly - # exercise the owner's power to restore refs. See: - # - # http://www.erights.org/elib/capability/dist-confine.html - # - # Resist the urge to represent an Owner as a simple public key. The whole point of sealing is to - # defend against leaked-storage attacks. Such attacks can easily result in the owner's private - # key being stolen as well. A better solution is for `Owner` to contain a simple globally unique - # identifier for the owner, and for everyone to separately maintain a mapping of owner IDs to - # public keys. If an owner's private key is compromised, then humans will need to communicate - # and agree on a replacement public key, then update the mapping. - # - # As a concrete example, an `Owner` could simply contain a domain name, and restoring a SturdyRef - # would require signing a request using the domain's private key. Authenticating this key could - # be accomplished through certificate authorities or web-of-trust techniques. - - save @0 SaveParams -> SaveResults; - # Save a capability persistently so that it can be restored by a future connection. Not all - # capabilities can be saved -- application interfaces should define which capabilities support - # this and which do not. - - struct SaveParams { - sealFor @0 :Owner; - # Seal the SturdyRef so that it can only be restored by the specified Owner. This is meant - # to mitigate damage when a SturdyRef is leaked. See comments above. - # - # Leaving this value null may or may not be allowed; it is up to the realm to decide. If a - # realm does allow a null owner, this should indicate that anyone is allowed to restore the - # ref. - } - struct SaveResults { - sturdyRef @0 :SturdyRef; - } -} - -interface RealmGateway(InternalRef, ExternalRef, InternalOwner, ExternalOwner) { - # Interface invoked when a SturdyRef is about to cross realms. The RPC system supports providing - # a RealmGateway as a callback hook when setting up RPC over some VatNetwork. - - import @0 (cap :Persistent(ExternalRef, ExternalOwner), - params :Persistent(InternalRef, InternalOwner).SaveParams) - -> Persistent(InternalRef, InternalOwner).SaveResults; - # Given an external capability, save it and return an internal reference. Used when someone - # inside the realm tries to save a capability from outside the realm. - - export @1 (cap :Persistent(InternalRef, InternalOwner), - params :Persistent(ExternalRef, ExternalOwner).SaveParams) - -> Persistent(ExternalRef, ExternalOwner).SaveResults; - # Given an internal capability, save it and return an external reference. Used when someone - # outside the realm tries to save a capability from inside the realm. -} - -annotation persistent(interface, field) :Void; -# Apply this annotation to interfaces for objects that will always be persistent, instead of -# extending the Persistent capability, since the correct type parameters to Persistent depend on -# the realm, which is orthogonal to the interface type and therefore should not be defined -# along-side it. -# -# You may also apply this annotation to a capability-typed field which will always contain a -# persistent capability, but where the capability's interface itself is not already marked -# persistent. -# -# Note that absence of the $persistent annotation doesn't mean a capability of that type isn't -# persistent; it just means not *all* such capabilities are persistent. diff --git a/phonelibs/capnp-cpp/include/capnp/persistent.capnp.h b/phonelibs/capnp-cpp/include/capnp/persistent.capnp.h deleted file mode 100644 index f9b443220a..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/persistent.capnp.h +++ /dev/null @@ -1,1328 +0,0 @@ -// Generated by Cap'n Proto compiler, DO NOT EDIT -// source: persistent.capnp - -#ifndef CAPNP_INCLUDED_b8630836983feed7_ -#define CAPNP_INCLUDED_b8630836983feed7_ - -#include -#if !CAPNP_LITE -#include -#endif // !CAPNP_LITE - -#if CAPNP_VERSION != 6001 -#error "Version mismatch between generated code and library headers. You must use the same version of the Cap'n Proto compiler and library." -#endif - - -namespace capnp { -namespace schemas { - -CAPNP_DECLARE_SCHEMA(c8cb212fcd9f5691); -CAPNP_DECLARE_SCHEMA(f76fba59183073a5); -CAPNP_DECLARE_SCHEMA(b76848c18c40efbf); -CAPNP_DECLARE_SCHEMA(84ff286cd00a3ed4); -CAPNP_DECLARE_SCHEMA(f0c2cc1d3909574d); -CAPNP_DECLARE_SCHEMA(ecafa18b482da3aa); -CAPNP_DECLARE_SCHEMA(f622595091cafb67); - -} // namespace schemas -} // namespace capnp - -namespace capnp { - -template -struct Persistent { - Persistent() = delete; - -#if !CAPNP_LITE - class Client; - class Server; -#endif // !CAPNP_LITE - - struct SaveParams; - struct SaveResults; - - #if !CAPNP_LITE - struct _capnpPrivate { - CAPNP_DECLARE_INTERFACE_HEADER(c8cb212fcd9f5691) - static const ::capnp::_::RawBrandedSchema::Scope brandScopes[]; - static const ::capnp::_::RawBrandedSchema::Binding brandBindings[]; - static const ::capnp::_::RawBrandedSchema::Dependency brandDependencies[]; - static const ::capnp::_::RawBrandedSchema specificBrand; - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return ::capnp::_::ChooseBrand<_capnpPrivate, SturdyRef, Owner>::brand(); } - }; - #endif // !CAPNP_LITE -}; - -template -struct Persistent::SaveParams { - SaveParams() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(f76fba59183073a5, 0, 1) - #if !CAPNP_LITE - static const ::capnp::_::RawBrandedSchema::Scope brandScopes[]; - static const ::capnp::_::RawBrandedSchema::Binding brandBindings[]; - static const ::capnp::_::RawBrandedSchema specificBrand; - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return ::capnp::_::ChooseBrand<_capnpPrivate, SturdyRef, Owner>::brand(); } - #endif // !CAPNP_LITE - }; -}; - -template -struct Persistent::SaveResults { - SaveResults() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(b76848c18c40efbf, 0, 1) - #if !CAPNP_LITE - static const ::capnp::_::RawBrandedSchema::Scope brandScopes[]; - static const ::capnp::_::RawBrandedSchema::Binding brandBindings[]; - static const ::capnp::_::RawBrandedSchema specificBrand; - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return ::capnp::_::ChooseBrand<_capnpPrivate, SturdyRef, Owner>::brand(); } - #endif // !CAPNP_LITE - }; -}; - -template -struct RealmGateway { - RealmGateway() = delete; - -#if !CAPNP_LITE - class Client; - class Server; -#endif // !CAPNP_LITE - - struct ImportParams; - struct ExportParams; - - #if !CAPNP_LITE - struct _capnpPrivate { - CAPNP_DECLARE_INTERFACE_HEADER(84ff286cd00a3ed4) - static const ::capnp::_::RawBrandedSchema::Scope brandScopes[]; - static const ::capnp::_::RawBrandedSchema::Binding brandBindings[]; - static const ::capnp::_::RawBrandedSchema::Dependency brandDependencies[]; - static const ::capnp::_::RawBrandedSchema specificBrand; - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return ::capnp::_::ChooseBrand<_capnpPrivate, InternalRef, ExternalRef, InternalOwner, ExternalOwner>::brand(); } - }; - #endif // !CAPNP_LITE -}; - -template -struct RealmGateway::ImportParams { - ImportParams() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(f0c2cc1d3909574d, 0, 2) - #if !CAPNP_LITE - static const ::capnp::_::RawBrandedSchema::Scope brandScopes[]; - static const ::capnp::_::RawBrandedSchema::Binding brandBindings[]; - static const ::capnp::_::RawBrandedSchema::Dependency brandDependencies[]; - static const ::capnp::_::RawBrandedSchema specificBrand; - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return ::capnp::_::ChooseBrand<_capnpPrivate, InternalRef, ExternalRef, InternalOwner, ExternalOwner>::brand(); } - #endif // !CAPNP_LITE - }; -}; - -template -struct RealmGateway::ExportParams { - ExportParams() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(ecafa18b482da3aa, 0, 2) - #if !CAPNP_LITE - static const ::capnp::_::RawBrandedSchema::Scope brandScopes[]; - static const ::capnp::_::RawBrandedSchema::Binding brandBindings[]; - static const ::capnp::_::RawBrandedSchema::Dependency brandDependencies[]; - static const ::capnp::_::RawBrandedSchema specificBrand; - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return ::capnp::_::ChooseBrand<_capnpPrivate, InternalRef, ExternalRef, InternalOwner, ExternalOwner>::brand(); } - #endif // !CAPNP_LITE - }; -}; - -// ======================================================================================= - -#if !CAPNP_LITE -template -class Persistent::Client - : public virtual ::capnp::Capability::Client { -public: - typedef Persistent Calls; - typedef Persistent Reads; - - Client(decltype(nullptr)); - explicit Client(::kj::Own< ::capnp::ClientHook>&& hook); - template ()>> - Client(::kj::Own<_t>&& server); - template ()>> - Client(::kj::Promise<_t>&& promise); - Client(::kj::Exception&& exception); - Client(Client&) = default; - Client(Client&&) = default; - Client& operator=(Client& other); - Client& operator=(Client&& other); - - template - typename Persistent::Client asGeneric() { - return castAs>(); - } - - CAPNP_AUTO_IF_MSVC(::capnp::Request::SaveParams, typename ::capnp::Persistent::SaveResults>) saveRequest( - ::kj::Maybe< ::capnp::MessageSize> sizeHint = nullptr); - -protected: - Client() = default; -}; - -template -class Persistent::Server - : public virtual ::capnp::Capability::Server { -public: - typedef Persistent Serves; - - ::kj::Promise dispatchCall(uint64_t interfaceId, uint16_t methodId, - ::capnp::CallContext< ::capnp::AnyPointer, ::capnp::AnyPointer> context) - override; - -protected: - typedef ::capnp::CallContext::SaveParams, typename ::capnp::Persistent::SaveResults> SaveContext; - virtual ::kj::Promise save(SaveContext context); - - inline typename ::capnp::Persistent::Client thisCap() { - return ::capnp::Capability::Server::thisCap() - .template castAs< ::capnp::Persistent>(); - } - - ::kj::Promise dispatchCallInternal(uint16_t methodId, - ::capnp::CallContext< ::capnp::AnyPointer, ::capnp::AnyPointer> context); -}; -#endif // !CAPNP_LITE - -template -class Persistent::SaveParams::Reader { -public: - typedef SaveParams Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - template - typename Persistent::SaveParams::Reader asPersistentGeneric() { - return typename Persistent::SaveParams::Reader(_reader); - } - - inline bool hasSealFor() const; - inline ::capnp::ReaderFor getSealFor() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -template -class Persistent::SaveParams::Builder { -public: - typedef SaveParams Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - template - typename Persistent::SaveParams::Builder asPersistentGeneric() { - return typename Persistent::SaveParams::Builder(_builder); - } - - inline bool hasSealFor(); - inline ::capnp::BuilderFor getSealFor(); - inline void setSealFor( ::capnp::ReaderFor value); - inline ::capnp::BuilderFor initSealFor(); - inline ::capnp::BuilderFor initSealFor(unsigned int size); - inline void adoptSealFor(::capnp::Orphan&& value); - inline ::capnp::Orphan disownSealFor(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -template -class Persistent::SaveParams::Pipeline { -public: - typedef SaveParams Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline ::capnp::PipelineFor getSealFor(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -template -class Persistent::SaveResults::Reader { -public: - typedef SaveResults Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - template - typename Persistent::SaveResults::Reader asPersistentGeneric() { - return typename Persistent::SaveResults::Reader(_reader); - } - - inline bool hasSturdyRef() const; - inline ::capnp::ReaderFor getSturdyRef() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -template -class Persistent::SaveResults::Builder { -public: - typedef SaveResults Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - template - typename Persistent::SaveResults::Builder asPersistentGeneric() { - return typename Persistent::SaveResults::Builder(_builder); - } - - inline bool hasSturdyRef(); - inline ::capnp::BuilderFor getSturdyRef(); - inline void setSturdyRef( ::capnp::ReaderFor value); - inline ::capnp::BuilderFor initSturdyRef(); - inline ::capnp::BuilderFor initSturdyRef(unsigned int size); - inline void adoptSturdyRef(::capnp::Orphan&& value); - inline ::capnp::Orphan disownSturdyRef(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -template -class Persistent::SaveResults::Pipeline { -public: - typedef SaveResults Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline ::capnp::PipelineFor getSturdyRef(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -#if !CAPNP_LITE -template -class RealmGateway::Client - : public virtual ::capnp::Capability::Client { -public: - typedef RealmGateway Calls; - typedef RealmGateway Reads; - - Client(decltype(nullptr)); - explicit Client(::kj::Own< ::capnp::ClientHook>&& hook); - template ()>> - Client(::kj::Own<_t>&& server); - template ()>> - Client(::kj::Promise<_t>&& promise); - Client(::kj::Exception&& exception); - Client(Client&) = default; - Client(Client&&) = default; - Client& operator=(Client& other); - Client& operator=(Client&& other); - - template - typename RealmGateway::Client asGeneric() { - return castAs>(); - } - - CAPNP_AUTO_IF_MSVC(::capnp::Request::ImportParams, typename ::capnp::Persistent::SaveResults>) importRequest( - ::kj::Maybe< ::capnp::MessageSize> sizeHint = nullptr); - CAPNP_AUTO_IF_MSVC(::capnp::Request::ExportParams, typename ::capnp::Persistent::SaveResults>) exportRequest( - ::kj::Maybe< ::capnp::MessageSize> sizeHint = nullptr); - -protected: - Client() = default; -}; - -template -class RealmGateway::Server - : public virtual ::capnp::Capability::Server { -public: - typedef RealmGateway Serves; - - ::kj::Promise dispatchCall(uint64_t interfaceId, uint16_t methodId, - ::capnp::CallContext< ::capnp::AnyPointer, ::capnp::AnyPointer> context) - override; - -protected: - typedef typename ::capnp::RealmGateway::ImportParams ImportParams; - typedef ::capnp::CallContext::SaveResults> ImportContext; - virtual ::kj::Promise import(ImportContext context); - typedef typename ::capnp::RealmGateway::ExportParams ExportParams; - typedef ::capnp::CallContext::SaveResults> ExportContext; - virtual ::kj::Promise export_(ExportContext context); - - inline typename ::capnp::RealmGateway::Client thisCap() { - return ::capnp::Capability::Server::thisCap() - .template castAs< ::capnp::RealmGateway>(); - } - - ::kj::Promise dispatchCallInternal(uint16_t methodId, - ::capnp::CallContext< ::capnp::AnyPointer, ::capnp::AnyPointer> context); -}; -#endif // !CAPNP_LITE - -template -class RealmGateway::ImportParams::Reader { -public: - typedef ImportParams Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - template - typename RealmGateway::ImportParams::Reader asRealmGatewayGeneric() { - return typename RealmGateway::ImportParams::Reader(_reader); - } - - inline bool hasCap() const; -#if !CAPNP_LITE - inline typename ::capnp::Persistent::Client getCap() const; -#endif // !CAPNP_LITE - - inline bool hasParams() const; - inline typename ::capnp::Persistent::SaveParams::Reader getParams() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -template -class RealmGateway::ImportParams::Builder { -public: - typedef ImportParams Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - template - typename RealmGateway::ImportParams::Builder asRealmGatewayGeneric() { - return typename RealmGateway::ImportParams::Builder(_builder); - } - - inline bool hasCap(); -#if !CAPNP_LITE - inline typename ::capnp::Persistent::Client getCap(); - inline void setCap(typename ::capnp::Persistent::Client&& value); - inline void setCap(typename ::capnp::Persistent::Client& value); - inline void adoptCap(::capnp::Orphan< ::capnp::Persistent>&& value); - inline ::capnp::Orphan< ::capnp::Persistent> disownCap(); -#endif // !CAPNP_LITE - - inline bool hasParams(); - inline typename ::capnp::Persistent::SaveParams::Builder getParams(); - inline void setParams(typename ::capnp::Persistent::SaveParams::Reader value); - inline typename ::capnp::Persistent::SaveParams::Builder initParams(); - inline void adoptParams(::capnp::Orphan::SaveParams>&& value); - inline ::capnp::Orphan::SaveParams> disownParams(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -template -class RealmGateway::ImportParams::Pipeline { -public: - typedef ImportParams Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline typename ::capnp::Persistent::Client getCap(); - inline typename ::capnp::Persistent::SaveParams::Pipeline getParams(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -template -class RealmGateway::ExportParams::Reader { -public: - typedef ExportParams Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - template - typename RealmGateway::ExportParams::Reader asRealmGatewayGeneric() { - return typename RealmGateway::ExportParams::Reader(_reader); - } - - inline bool hasCap() const; -#if !CAPNP_LITE - inline typename ::capnp::Persistent::Client getCap() const; -#endif // !CAPNP_LITE - - inline bool hasParams() const; - inline typename ::capnp::Persistent::SaveParams::Reader getParams() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -template -class RealmGateway::ExportParams::Builder { -public: - typedef ExportParams Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - template - typename RealmGateway::ExportParams::Builder asRealmGatewayGeneric() { - return typename RealmGateway::ExportParams::Builder(_builder); - } - - inline bool hasCap(); -#if !CAPNP_LITE - inline typename ::capnp::Persistent::Client getCap(); - inline void setCap(typename ::capnp::Persistent::Client&& value); - inline void setCap(typename ::capnp::Persistent::Client& value); - inline void adoptCap(::capnp::Orphan< ::capnp::Persistent>&& value); - inline ::capnp::Orphan< ::capnp::Persistent> disownCap(); -#endif // !CAPNP_LITE - - inline bool hasParams(); - inline typename ::capnp::Persistent::SaveParams::Builder getParams(); - inline void setParams(typename ::capnp::Persistent::SaveParams::Reader value); - inline typename ::capnp::Persistent::SaveParams::Builder initParams(); - inline void adoptParams(::capnp::Orphan::SaveParams>&& value); - inline ::capnp::Orphan::SaveParams> disownParams(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -template -class RealmGateway::ExportParams::Pipeline { -public: - typedef ExportParams Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline typename ::capnp::Persistent::Client getCap(); - inline typename ::capnp::Persistent::SaveParams::Pipeline getParams(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -// ======================================================================================= - -#if !CAPNP_LITE -template -inline Persistent::Client::Client(decltype(nullptr)) - : ::capnp::Capability::Client(nullptr) {} -template -inline Persistent::Client::Client( - ::kj::Own< ::capnp::ClientHook>&& hook) - : ::capnp::Capability::Client(::kj::mv(hook)) {} -template -template -inline Persistent::Client::Client(::kj::Own<_t>&& server) - : ::capnp::Capability::Client(::kj::mv(server)) {} -template -template -inline Persistent::Client::Client(::kj::Promise<_t>&& promise) - : ::capnp::Capability::Client(::kj::mv(promise)) {} -template -inline Persistent::Client::Client(::kj::Exception&& exception) - : ::capnp::Capability::Client(::kj::mv(exception)) {} -template -inline typename ::capnp::Persistent::Client& Persistent::Client::operator=(Client& other) { - ::capnp::Capability::Client::operator=(other); - return *this; -} -template -inline typename ::capnp::Persistent::Client& Persistent::Client::operator=(Client&& other) { - ::capnp::Capability::Client::operator=(kj::mv(other)); - return *this; -} - -#endif // !CAPNP_LITE -template -inline bool Persistent::SaveParams::Reader::hasSealFor() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -template -inline bool Persistent::SaveParams::Builder::hasSealFor() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -template -inline ::capnp::ReaderFor Persistent::SaveParams::Reader::getSealFor() const { - return ::capnp::_::PointerHelpers::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -template -inline ::capnp::BuilderFor Persistent::SaveParams::Builder::getSealFor() { - return ::capnp::_::PointerHelpers::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -template -inline ::capnp::PipelineFor Persistent::SaveParams::Pipeline::getSealFor() { - return ::capnp::PipelineFor(_typeless.getPointerField(0)); -} -#endif // !CAPNP_LITE -template -inline void Persistent::SaveParams::Builder::setSealFor( ::capnp::ReaderFor value) { - ::capnp::_::PointerHelpers::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -template -inline ::capnp::BuilderFor Persistent::SaveParams::Builder::initSealFor() { - return ::capnp::_::PointerHelpers::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -template -inline ::capnp::BuilderFor Persistent::SaveParams::Builder::initSealFor(unsigned int size) { - return ::capnp::_::PointerHelpers::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -template -inline void Persistent::SaveParams::Builder::adoptSealFor( - ::capnp::Orphan&& value) { - ::capnp::_::PointerHelpers::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -template -inline ::capnp::Orphan Persistent::SaveParams::Builder::disownSealFor() { - return ::capnp::_::PointerHelpers::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -// Persistent::SaveParams -template -constexpr uint16_t Persistent::SaveParams::_capnpPrivate::dataWordSize; -template -constexpr uint16_t Persistent::SaveParams::_capnpPrivate::pointerCount; -#if !CAPNP_LITE -template -constexpr ::capnp::Kind Persistent::SaveParams::_capnpPrivate::kind; -template -constexpr ::capnp::_::RawSchema const* Persistent::SaveParams::_capnpPrivate::schema; -template -const ::capnp::_::RawBrandedSchema::Scope Persistent::SaveParams::_capnpPrivate::brandScopes[] = { - { 0xc8cb212fcd9f5691, brandBindings + 0, 2, false}, -}; -template -const ::capnp::_::RawBrandedSchema::Binding Persistent::SaveParams::_capnpPrivate::brandBindings[] = { - ::capnp::_::brandBindingFor(), - ::capnp::_::brandBindingFor(), -}; -template -const ::capnp::_::RawBrandedSchema Persistent::SaveParams::_capnpPrivate::specificBrand = { - &::capnp::schemas::s_f76fba59183073a5, brandScopes, nullptr, - 1, 0, nullptr -}; -#endif // !CAPNP_LITE - -template -inline bool Persistent::SaveResults::Reader::hasSturdyRef() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -template -inline bool Persistent::SaveResults::Builder::hasSturdyRef() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -template -inline ::capnp::ReaderFor Persistent::SaveResults::Reader::getSturdyRef() const { - return ::capnp::_::PointerHelpers::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -template -inline ::capnp::BuilderFor Persistent::SaveResults::Builder::getSturdyRef() { - return ::capnp::_::PointerHelpers::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -template -inline ::capnp::PipelineFor Persistent::SaveResults::Pipeline::getSturdyRef() { - return ::capnp::PipelineFor(_typeless.getPointerField(0)); -} -#endif // !CAPNP_LITE -template -inline void Persistent::SaveResults::Builder::setSturdyRef( ::capnp::ReaderFor value) { - ::capnp::_::PointerHelpers::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -template -inline ::capnp::BuilderFor Persistent::SaveResults::Builder::initSturdyRef() { - return ::capnp::_::PointerHelpers::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -template -inline ::capnp::BuilderFor Persistent::SaveResults::Builder::initSturdyRef(unsigned int size) { - return ::capnp::_::PointerHelpers::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -template -inline void Persistent::SaveResults::Builder::adoptSturdyRef( - ::capnp::Orphan&& value) { - ::capnp::_::PointerHelpers::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -template -inline ::capnp::Orphan Persistent::SaveResults::Builder::disownSturdyRef() { - return ::capnp::_::PointerHelpers::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -// Persistent::SaveResults -template -constexpr uint16_t Persistent::SaveResults::_capnpPrivate::dataWordSize; -template -constexpr uint16_t Persistent::SaveResults::_capnpPrivate::pointerCount; -#if !CAPNP_LITE -template -constexpr ::capnp::Kind Persistent::SaveResults::_capnpPrivate::kind; -template -constexpr ::capnp::_::RawSchema const* Persistent::SaveResults::_capnpPrivate::schema; -template -const ::capnp::_::RawBrandedSchema::Scope Persistent::SaveResults::_capnpPrivate::brandScopes[] = { - { 0xc8cb212fcd9f5691, brandBindings + 0, 2, false}, -}; -template -const ::capnp::_::RawBrandedSchema::Binding Persistent::SaveResults::_capnpPrivate::brandBindings[] = { - ::capnp::_::brandBindingFor(), - ::capnp::_::brandBindingFor(), -}; -template -const ::capnp::_::RawBrandedSchema Persistent::SaveResults::_capnpPrivate::specificBrand = { - &::capnp::schemas::s_b76848c18c40efbf, brandScopes, nullptr, - 1, 0, nullptr -}; -#endif // !CAPNP_LITE - -#if !CAPNP_LITE -template -CAPNP_AUTO_IF_MSVC(::capnp::Request::SaveParams, typename ::capnp::Persistent::SaveResults>) -Persistent::Client::saveRequest(::kj::Maybe< ::capnp::MessageSize> sizeHint) { - return newCall::SaveParams, typename ::capnp::Persistent::SaveResults>( - 0xc8cb212fcd9f5691ull, 0, sizeHint); -} -template -::kj::Promise Persistent::Server::save(SaveContext) { - return ::capnp::Capability::Server::internalUnimplemented( - "capnp/persistent.capnp:Persistent", "save", - 0xc8cb212fcd9f5691ull, 0); -} -template -::kj::Promise Persistent::Server::dispatchCall( - uint64_t interfaceId, uint16_t methodId, - ::capnp::CallContext< ::capnp::AnyPointer, ::capnp::AnyPointer> context) { - switch (interfaceId) { - case 0xc8cb212fcd9f5691ull: - return dispatchCallInternal(methodId, context); - default: - return internalUnimplemented("capnp/persistent.capnp:Persistent", interfaceId); - } -} -template -::kj::Promise Persistent::Server::dispatchCallInternal( - uint16_t methodId, - ::capnp::CallContext< ::capnp::AnyPointer, ::capnp::AnyPointer> context) { - switch (methodId) { - case 0: - return save(::capnp::Capability::Server::internalGetTypedContext< - typename ::capnp::Persistent::SaveParams, typename ::capnp::Persistent::SaveResults>(context)); - default: - (void)context; - return ::capnp::Capability::Server::internalUnimplemented( - "capnp/persistent.capnp:Persistent", - 0xc8cb212fcd9f5691ull, methodId); - } -} -#endif // !CAPNP_LITE - -// Persistent -#if !CAPNP_LITE -template -constexpr ::capnp::Kind Persistent::_capnpPrivate::kind; -template -constexpr ::capnp::_::RawSchema const* Persistent::_capnpPrivate::schema; -template -const ::capnp::_::RawBrandedSchema::Scope Persistent::_capnpPrivate::brandScopes[] = { - { 0xc8cb212fcd9f5691, brandBindings + 0, 2, false}, -}; -template -const ::capnp::_::RawBrandedSchema::Binding Persistent::_capnpPrivate::brandBindings[] = { - ::capnp::_::brandBindingFor(), - ::capnp::_::brandBindingFor(), -}; -template -const ::capnp::_::RawBrandedSchema::Dependency Persistent::_capnpPrivate::brandDependencies[] = { - { 33554432, ::capnp::Persistent::SaveParams::_capnpPrivate::brand() }, - { 50331648, ::capnp::Persistent::SaveResults::_capnpPrivate::brand() }, -}; -template -const ::capnp::_::RawBrandedSchema Persistent::_capnpPrivate::specificBrand = { - &::capnp::schemas::s_c8cb212fcd9f5691, brandScopes, brandDependencies, - 1, 2, nullptr -}; -#endif // !CAPNP_LITE - -#if !CAPNP_LITE -template -inline RealmGateway::Client::Client(decltype(nullptr)) - : ::capnp::Capability::Client(nullptr) {} -template -inline RealmGateway::Client::Client( - ::kj::Own< ::capnp::ClientHook>&& hook) - : ::capnp::Capability::Client(::kj::mv(hook)) {} -template -template -inline RealmGateway::Client::Client(::kj::Own<_t>&& server) - : ::capnp::Capability::Client(::kj::mv(server)) {} -template -template -inline RealmGateway::Client::Client(::kj::Promise<_t>&& promise) - : ::capnp::Capability::Client(::kj::mv(promise)) {} -template -inline RealmGateway::Client::Client(::kj::Exception&& exception) - : ::capnp::Capability::Client(::kj::mv(exception)) {} -template -inline typename ::capnp::RealmGateway::Client& RealmGateway::Client::operator=(Client& other) { - ::capnp::Capability::Client::operator=(other); - return *this; -} -template -inline typename ::capnp::RealmGateway::Client& RealmGateway::Client::operator=(Client&& other) { - ::capnp::Capability::Client::operator=(kj::mv(other)); - return *this; -} - -#endif // !CAPNP_LITE -template -inline bool RealmGateway::ImportParams::Reader::hasCap() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -template -inline bool RealmGateway::ImportParams::Builder::hasCap() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -#if !CAPNP_LITE -template -inline typename ::capnp::Persistent::Client RealmGateway::ImportParams::Reader::getCap() const { - return ::capnp::_::PointerHelpers< ::capnp::Persistent>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -template -inline typename ::capnp::Persistent::Client RealmGateway::ImportParams::Builder::getCap() { - return ::capnp::_::PointerHelpers< ::capnp::Persistent>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -template -inline typename ::capnp::Persistent::Client RealmGateway::ImportParams::Pipeline::getCap() { - return typename ::capnp::Persistent::Client(_typeless.getPointerField(0).asCap()); -} -template -inline void RealmGateway::ImportParams::Builder::setCap(typename ::capnp::Persistent::Client&& cap) { - ::capnp::_::PointerHelpers< ::capnp::Persistent>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(cap)); -} -template -inline void RealmGateway::ImportParams::Builder::setCap(typename ::capnp::Persistent::Client& cap) { - ::capnp::_::PointerHelpers< ::capnp::Persistent>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), cap); -} -template -inline void RealmGateway::ImportParams::Builder::adoptCap( - ::capnp::Orphan< ::capnp::Persistent>&& value) { - ::capnp::_::PointerHelpers< ::capnp::Persistent>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -template -inline ::capnp::Orphan< ::capnp::Persistent> RealmGateway::ImportParams::Builder::disownCap() { - return ::capnp::_::PointerHelpers< ::capnp::Persistent>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -#endif // !CAPNP_LITE - -template -inline bool RealmGateway::ImportParams::Reader::hasParams() const { - return !_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -template -inline bool RealmGateway::ImportParams::Builder::hasParams() { - return !_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -template -inline typename ::capnp::Persistent::SaveParams::Reader RealmGateway::ImportParams::Reader::getParams() const { - return ::capnp::_::PointerHelpers::SaveParams>::get(_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -template -inline typename ::capnp::Persistent::SaveParams::Builder RealmGateway::ImportParams::Builder::getParams() { - return ::capnp::_::PointerHelpers::SaveParams>::get(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -template -inline typename ::capnp::Persistent::SaveParams::Pipeline RealmGateway::ImportParams::Pipeline::getParams() { - return typename ::capnp::Persistent::SaveParams::Pipeline(_typeless.getPointerField(1)); -} -#endif // !CAPNP_LITE -template -inline void RealmGateway::ImportParams::Builder::setParams(typename ::capnp::Persistent::SaveParams::Reader value) { - ::capnp::_::PointerHelpers::SaveParams>::set(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), value); -} -template -inline typename ::capnp::Persistent::SaveParams::Builder RealmGateway::ImportParams::Builder::initParams() { - return ::capnp::_::PointerHelpers::SaveParams>::init(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -template -inline void RealmGateway::ImportParams::Builder::adoptParams( - ::capnp::Orphan::SaveParams>&& value) { - ::capnp::_::PointerHelpers::SaveParams>::adopt(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), kj::mv(value)); -} -template -inline ::capnp::Orphan::SaveParams> RealmGateway::ImportParams::Builder::disownParams() { - return ::capnp::_::PointerHelpers::SaveParams>::disown(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} - -// RealmGateway::ImportParams -template -constexpr uint16_t RealmGateway::ImportParams::_capnpPrivate::dataWordSize; -template -constexpr uint16_t RealmGateway::ImportParams::_capnpPrivate::pointerCount; -#if !CAPNP_LITE -template -constexpr ::capnp::Kind RealmGateway::ImportParams::_capnpPrivate::kind; -template -constexpr ::capnp::_::RawSchema const* RealmGateway::ImportParams::_capnpPrivate::schema; -template -const ::capnp::_::RawBrandedSchema::Scope RealmGateway::ImportParams::_capnpPrivate::brandScopes[] = { - { 0x84ff286cd00a3ed4, brandBindings + 0, 4, false}, -}; -template -const ::capnp::_::RawBrandedSchema::Binding RealmGateway::ImportParams::_capnpPrivate::brandBindings[] = { - ::capnp::_::brandBindingFor(), - ::capnp::_::brandBindingFor(), - ::capnp::_::brandBindingFor(), - ::capnp::_::brandBindingFor(), -}; -template -const ::capnp::_::RawBrandedSchema::Dependency RealmGateway::ImportParams::_capnpPrivate::brandDependencies[] = { - { 16777216, ::capnp::Persistent::_capnpPrivate::brand() }, - { 16777217, ::capnp::Persistent::SaveParams::_capnpPrivate::brand() }, -}; -template -const ::capnp::_::RawBrandedSchema RealmGateway::ImportParams::_capnpPrivate::specificBrand = { - &::capnp::schemas::s_f0c2cc1d3909574d, brandScopes, brandDependencies, - 1, 2, nullptr -}; -#endif // !CAPNP_LITE - -template -inline bool RealmGateway::ExportParams::Reader::hasCap() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -template -inline bool RealmGateway::ExportParams::Builder::hasCap() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -#if !CAPNP_LITE -template -inline typename ::capnp::Persistent::Client RealmGateway::ExportParams::Reader::getCap() const { - return ::capnp::_::PointerHelpers< ::capnp::Persistent>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -template -inline typename ::capnp::Persistent::Client RealmGateway::ExportParams::Builder::getCap() { - return ::capnp::_::PointerHelpers< ::capnp::Persistent>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -template -inline typename ::capnp::Persistent::Client RealmGateway::ExportParams::Pipeline::getCap() { - return typename ::capnp::Persistent::Client(_typeless.getPointerField(0).asCap()); -} -template -inline void RealmGateway::ExportParams::Builder::setCap(typename ::capnp::Persistent::Client&& cap) { - ::capnp::_::PointerHelpers< ::capnp::Persistent>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(cap)); -} -template -inline void RealmGateway::ExportParams::Builder::setCap(typename ::capnp::Persistent::Client& cap) { - ::capnp::_::PointerHelpers< ::capnp::Persistent>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), cap); -} -template -inline void RealmGateway::ExportParams::Builder::adoptCap( - ::capnp::Orphan< ::capnp::Persistent>&& value) { - ::capnp::_::PointerHelpers< ::capnp::Persistent>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -template -inline ::capnp::Orphan< ::capnp::Persistent> RealmGateway::ExportParams::Builder::disownCap() { - return ::capnp::_::PointerHelpers< ::capnp::Persistent>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -#endif // !CAPNP_LITE - -template -inline bool RealmGateway::ExportParams::Reader::hasParams() const { - return !_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -template -inline bool RealmGateway::ExportParams::Builder::hasParams() { - return !_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -template -inline typename ::capnp::Persistent::SaveParams::Reader RealmGateway::ExportParams::Reader::getParams() const { - return ::capnp::_::PointerHelpers::SaveParams>::get(_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -template -inline typename ::capnp::Persistent::SaveParams::Builder RealmGateway::ExportParams::Builder::getParams() { - return ::capnp::_::PointerHelpers::SaveParams>::get(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -template -inline typename ::capnp::Persistent::SaveParams::Pipeline RealmGateway::ExportParams::Pipeline::getParams() { - return typename ::capnp::Persistent::SaveParams::Pipeline(_typeless.getPointerField(1)); -} -#endif // !CAPNP_LITE -template -inline void RealmGateway::ExportParams::Builder::setParams(typename ::capnp::Persistent::SaveParams::Reader value) { - ::capnp::_::PointerHelpers::SaveParams>::set(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), value); -} -template -inline typename ::capnp::Persistent::SaveParams::Builder RealmGateway::ExportParams::Builder::initParams() { - return ::capnp::_::PointerHelpers::SaveParams>::init(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -template -inline void RealmGateway::ExportParams::Builder::adoptParams( - ::capnp::Orphan::SaveParams>&& value) { - ::capnp::_::PointerHelpers::SaveParams>::adopt(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), kj::mv(value)); -} -template -inline ::capnp::Orphan::SaveParams> RealmGateway::ExportParams::Builder::disownParams() { - return ::capnp::_::PointerHelpers::SaveParams>::disown(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} - -// RealmGateway::ExportParams -template -constexpr uint16_t RealmGateway::ExportParams::_capnpPrivate::dataWordSize; -template -constexpr uint16_t RealmGateway::ExportParams::_capnpPrivate::pointerCount; -#if !CAPNP_LITE -template -constexpr ::capnp::Kind RealmGateway::ExportParams::_capnpPrivate::kind; -template -constexpr ::capnp::_::RawSchema const* RealmGateway::ExportParams::_capnpPrivate::schema; -template -const ::capnp::_::RawBrandedSchema::Scope RealmGateway::ExportParams::_capnpPrivate::brandScopes[] = { - { 0x84ff286cd00a3ed4, brandBindings + 0, 4, false}, -}; -template -const ::capnp::_::RawBrandedSchema::Binding RealmGateway::ExportParams::_capnpPrivate::brandBindings[] = { - ::capnp::_::brandBindingFor(), - ::capnp::_::brandBindingFor(), - ::capnp::_::brandBindingFor(), - ::capnp::_::brandBindingFor(), -}; -template -const ::capnp::_::RawBrandedSchema::Dependency RealmGateway::ExportParams::_capnpPrivate::brandDependencies[] = { - { 16777216, ::capnp::Persistent::_capnpPrivate::brand() }, - { 16777217, ::capnp::Persistent::SaveParams::_capnpPrivate::brand() }, -}; -template -const ::capnp::_::RawBrandedSchema RealmGateway::ExportParams::_capnpPrivate::specificBrand = { - &::capnp::schemas::s_ecafa18b482da3aa, brandScopes, brandDependencies, - 1, 2, nullptr -}; -#endif // !CAPNP_LITE - -#if !CAPNP_LITE -template -CAPNP_AUTO_IF_MSVC(::capnp::Request::ImportParams, typename ::capnp::Persistent::SaveResults>) -RealmGateway::Client::importRequest(::kj::Maybe< ::capnp::MessageSize> sizeHint) { - return newCall::ImportParams, typename ::capnp::Persistent::SaveResults>( - 0x84ff286cd00a3ed4ull, 0, sizeHint); -} -template -::kj::Promise RealmGateway::Server::import(ImportContext) { - return ::capnp::Capability::Server::internalUnimplemented( - "capnp/persistent.capnp:RealmGateway", "import", - 0x84ff286cd00a3ed4ull, 0); -} -template -CAPNP_AUTO_IF_MSVC(::capnp::Request::ExportParams, typename ::capnp::Persistent::SaveResults>) -RealmGateway::Client::exportRequest(::kj::Maybe< ::capnp::MessageSize> sizeHint) { - return newCall::ExportParams, typename ::capnp::Persistent::SaveResults>( - 0x84ff286cd00a3ed4ull, 1, sizeHint); -} -template -::kj::Promise RealmGateway::Server::export_(ExportContext) { - return ::capnp::Capability::Server::internalUnimplemented( - "capnp/persistent.capnp:RealmGateway", "export", - 0x84ff286cd00a3ed4ull, 1); -} -template -::kj::Promise RealmGateway::Server::dispatchCall( - uint64_t interfaceId, uint16_t methodId, - ::capnp::CallContext< ::capnp::AnyPointer, ::capnp::AnyPointer> context) { - switch (interfaceId) { - case 0x84ff286cd00a3ed4ull: - return dispatchCallInternal(methodId, context); - default: - return internalUnimplemented("capnp/persistent.capnp:RealmGateway", interfaceId); - } -} -template -::kj::Promise RealmGateway::Server::dispatchCallInternal( - uint16_t methodId, - ::capnp::CallContext< ::capnp::AnyPointer, ::capnp::AnyPointer> context) { - switch (methodId) { - case 0: - return import(::capnp::Capability::Server::internalGetTypedContext< - typename ::capnp::RealmGateway::ImportParams, typename ::capnp::Persistent::SaveResults>(context)); - case 1: - return export_(::capnp::Capability::Server::internalGetTypedContext< - typename ::capnp::RealmGateway::ExportParams, typename ::capnp::Persistent::SaveResults>(context)); - default: - (void)context; - return ::capnp::Capability::Server::internalUnimplemented( - "capnp/persistent.capnp:RealmGateway", - 0x84ff286cd00a3ed4ull, methodId); - } -} -#endif // !CAPNP_LITE - -// RealmGateway -#if !CAPNP_LITE -template -constexpr ::capnp::Kind RealmGateway::_capnpPrivate::kind; -template -constexpr ::capnp::_::RawSchema const* RealmGateway::_capnpPrivate::schema; -template -const ::capnp::_::RawBrandedSchema::Scope RealmGateway::_capnpPrivate::brandScopes[] = { - { 0x84ff286cd00a3ed4, brandBindings + 0, 4, false}, -}; -template -const ::capnp::_::RawBrandedSchema::Binding RealmGateway::_capnpPrivate::brandBindings[] = { - ::capnp::_::brandBindingFor(), - ::capnp::_::brandBindingFor(), - ::capnp::_::brandBindingFor(), - ::capnp::_::brandBindingFor(), -}; -template -const ::capnp::_::RawBrandedSchema::Dependency RealmGateway::_capnpPrivate::brandDependencies[] = { - { 33554432, ::capnp::RealmGateway::ImportParams::_capnpPrivate::brand() }, - { 33554433, ::capnp::RealmGateway::ExportParams::_capnpPrivate::brand() }, - { 50331648, ::capnp::Persistent::SaveResults::_capnpPrivate::brand() }, - { 50331649, ::capnp::Persistent::SaveResults::_capnpPrivate::brand() }, -}; -template -const ::capnp::_::RawBrandedSchema RealmGateway::_capnpPrivate::specificBrand = { - &::capnp::schemas::s_84ff286cd00a3ed4, brandScopes, brandDependencies, - 1, 4, nullptr -}; -#endif // !CAPNP_LITE - -} // namespace - -#endif // CAPNP_INCLUDED_b8630836983feed7_ diff --git a/phonelibs/capnp-cpp/include/capnp/pointer-helpers.h b/phonelibs/capnp-cpp/include/capnp/pointer-helpers.h deleted file mode 100644 index fe70e5036f..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/pointer-helpers.h +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_POINTER_HELPERS_H_ -#define CAPNP_POINTER_HELPERS_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include "layout.h" -#include "list.h" - -namespace capnp { -namespace _ { // private - -// PointerHelpers is a template class that assists in wrapping/unwrapping the low-level types in -// layout.h with the high-level public API and generated types. This way, the code generator -// and other templates do not have to specialize on each kind of pointer. - -template -struct PointerHelpers { - static inline typename T::Reader get(PointerReader reader, const word* defaultValue = nullptr) { - return typename T::Reader(reader.getStruct(defaultValue)); - } - static inline typename T::Builder get(PointerBuilder builder, - const word* defaultValue = nullptr) { - return typename T::Builder(builder.getStruct(structSize(), defaultValue)); - } - static inline void set(PointerBuilder builder, typename T::Reader value) { - builder.setStruct(value._reader); - } - static inline void setCanonical(PointerBuilder builder, typename T::Reader value) { - builder.setStruct(value._reader, true); - } - static inline typename T::Builder init(PointerBuilder builder) { - return typename T::Builder(builder.initStruct(structSize())); - } - static inline void adopt(PointerBuilder builder, Orphan&& value) { - builder.adopt(kj::mv(value.builder)); - } - static inline Orphan disown(PointerBuilder builder) { - return Orphan(builder.disown()); - } - static inline _::StructReader getInternalReader(const typename T::Reader& reader) { - return reader._reader; - } - static inline _::StructBuilder getInternalBuilder(typename T::Builder&& builder) { - return builder._builder; - } -}; - -template -struct PointerHelpers, Kind::LIST> { - static inline typename List::Reader get(PointerReader reader, - const word* defaultValue = nullptr) { - return typename List::Reader(List::getFromPointer(reader, defaultValue)); - } - static inline typename List::Builder get(PointerBuilder builder, - const word* defaultValue = nullptr) { - return typename List::Builder(List::getFromPointer(builder, defaultValue)); - } - static inline void set(PointerBuilder builder, typename List::Reader value) { - builder.setList(value.reader); - } - static inline void setCanonical(PointerBuilder builder, typename List::Reader value) { - builder.setList(value.reader, true); - } - static void set(PointerBuilder builder, kj::ArrayPtr> value) { - auto l = init(builder, value.size()); - uint i = 0; - for (auto& element: value) { - l.set(i++, element); - } - } - static inline typename List::Builder init(PointerBuilder builder, uint size) { - return typename List::Builder(List::initPointer(builder, size)); - } - static inline void adopt(PointerBuilder builder, Orphan>&& value) { - builder.adopt(kj::mv(value.builder)); - } - static inline Orphan> disown(PointerBuilder builder) { - return Orphan>(builder.disown()); - } - static inline _::ListReader getInternalReader(const typename List::Reader& reader) { - return reader.reader; - } - static inline _::ListBuilder getInternalBuilder(typename List::Builder&& builder) { - return builder.builder; - } -}; - -template -struct PointerHelpers { - static inline typename T::Reader get(PointerReader reader, - const void* defaultValue = nullptr, - uint defaultBytes = 0) { - return reader.getBlob(defaultValue, bounded(defaultBytes) * BYTES); - } - static inline typename T::Builder get(PointerBuilder builder, - const void* defaultValue = nullptr, - uint defaultBytes = 0) { - return builder.getBlob(defaultValue, bounded(defaultBytes) * BYTES); - } - static inline void set(PointerBuilder builder, typename T::Reader value) { - builder.setBlob(value); - } - static inline void setCanonical(PointerBuilder builder, typename T::Reader value) { - builder.setBlob(value); - } - static inline typename T::Builder init(PointerBuilder builder, uint size) { - return builder.initBlob(bounded(size) * BYTES); - } - static inline void adopt(PointerBuilder builder, Orphan&& value) { - builder.adopt(kj::mv(value.builder)); - } - static inline Orphan disown(PointerBuilder builder) { - return Orphan(builder.disown()); - } -}; - -struct UncheckedMessage { - typedef const word* Reader; -}; - -template <> struct Kind_ { static constexpr Kind kind = Kind::OTHER; }; - -template <> -struct PointerHelpers { - // Reads an AnyPointer field as an unchecked message pointer. Requires that the containing - // message is itself unchecked. This hack is currently private. It is used to locate default - // values within encoded schemas. - - static inline const word* get(PointerReader reader) { - return reader.getUnchecked(); - } -}; - -} // namespace _ (private) -} // namespace capnp - -#endif // CAPNP_POINTER_HELPERS_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/pretty-print.h b/phonelibs/capnp-cpp/include/capnp/pretty-print.h deleted file mode 100644 index e6458bca49..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/pretty-print.h +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_PRETTY_PRINT_H_ -#define CAPNP_PRETTY_PRINT_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include "dynamic.h" -#include - -namespace capnp { - -kj::StringTree prettyPrint(DynamicStruct::Reader value); -kj::StringTree prettyPrint(DynamicStruct::Builder value); -kj::StringTree prettyPrint(DynamicList::Reader value); -kj::StringTree prettyPrint(DynamicList::Builder value); -// Print the given Cap'n Proto struct or list with nice indentation. Note that you can pass any -// struct or list reader or builder type to this method, since they can be implicitly converted -// to one of the dynamic types. -// -// If you don't want indentation, just use the value's KJ stringifier (e.g. pass it to kj::str(), -// any of the KJ debug macros, etc.). - -} // namespace capnp - -#endif // PRETTY_PRINT_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/raw-schema.h b/phonelibs/capnp-cpp/include/capnp/raw-schema.h deleted file mode 100644 index ed9425a624..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/raw-schema.h +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_RAW_SCHEMA_H_ -#define CAPNP_RAW_SCHEMA_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include "common.h" // for uint and friends - -#if _MSC_VER -#include -#endif - -namespace capnp { -namespace _ { // private - -struct RawSchema; - -struct RawBrandedSchema { - // Represents a combination of a schema and bindings for its generic parameters. - // - // Note that while we generate one `RawSchema` per type, we generate a `RawBrandedSchema` for - // every _instance_ of a generic type -- or, at least, every instance that is actually used. For - // generated-code types, we use template magic to initialize these. - - const RawSchema* generic; - // Generic type which we're branding. - - struct Binding { - uint8_t which; // Numeric value of one of schema::Type::Which. - - bool isImplicitParameter; - // For AnyPointer, true if it's an implicit method parameter. - - uint16_t listDepth; // Number of times to wrap the base type in List(). - - uint16_t paramIndex; - // For AnyPointer. If it's a type parameter (scopeId is non-zero) or it's an implicit parameter - // (isImplicitParameter is true), then this is the parameter index. Otherwise this is a numeric - // value of one of schema::Type::AnyPointer::Unconstrained::Which. - - union { - const RawBrandedSchema* schema; // for struct, enum, interface - uint64_t scopeId; // for AnyPointer, if it's a type parameter - }; - - Binding() = default; - inline constexpr Binding(uint8_t which, uint16_t listDepth, const RawBrandedSchema* schema) - : which(which), isImplicitParameter(false), listDepth(listDepth), paramIndex(0), - schema(schema) {} - inline constexpr Binding(uint8_t which, uint16_t listDepth, - uint64_t scopeId, uint16_t paramIndex) - : which(which), isImplicitParameter(false), listDepth(listDepth), paramIndex(paramIndex), - scopeId(scopeId) {} - inline constexpr Binding(uint8_t which, uint16_t listDepth, uint16_t implicitParamIndex) - : which(which), isImplicitParameter(true), listDepth(listDepth), - paramIndex(implicitParamIndex), scopeId(0) {} - }; - - struct Scope { - uint64_t typeId; - // Type ID whose parameters are being bound. - - const Binding* bindings; - uint bindingCount; - // Bindings for those parameters. - - bool isUnbound; - // This scope is unbound, in the sense of SchemaLoader::getUnbound(). - }; - - const Scope* scopes; - // Array of enclosing scopes for which generic variables have been bound, sorted by type ID. - - struct Dependency { - uint location; - const RawBrandedSchema* schema; - }; - - const Dependency* dependencies; - // Map of branded schemas for dependencies of this type, given our brand. Only dependencies that - // are branded are included in this map; if a dependency is missing, use its `defaultBrand`. - - uint32_t scopeCount; - uint32_t dependencyCount; - - enum class DepKind { - // Component of a Dependency::location. Specifies what sort of dependency this is. - - INVALID, - // Mostly defined to ensure that zero is not a valid location. - - FIELD, - // Binding needed for a field's type. The index is the field index (NOT ordinal!). - - METHOD_PARAMS, - // Bindings needed for a method's params type. The index is the method number. - - METHOD_RESULTS, - // Bindings needed for a method's results type. The index is the method ordinal. - - SUPERCLASS, - // Bindings needed for a superclass type. The index is the superclass's index in the - // "extends" list. - - CONST_TYPE - // Bindings needed for the type of a constant. The index is zero. - }; - - static inline uint makeDepLocation(DepKind kind, uint index) { - // Make a number representing the location of a particular dependency within its parent - // schema. - - return (static_cast(kind) << 24) | index; - } - - class Initializer { - public: - virtual void init(const RawBrandedSchema* generic) const = 0; - }; - - const Initializer* lazyInitializer; - // Lazy initializer, invoked by ensureInitialized(). - - inline void ensureInitialized() const { - // Lazy initialization support. Invoke to ensure that initialization has taken place. This - // is required in particular when traversing the dependency list. RawSchemas for compiled-in - // types are always initialized; only dynamically-loaded schemas may be lazy. - -#if __GNUC__ - const Initializer* i = __atomic_load_n(&lazyInitializer, __ATOMIC_ACQUIRE); -#elif _MSC_VER - const Initializer* i = *static_cast(&lazyInitializer); - std::atomic_thread_fence(std::memory_order_acquire); -#else -#error "Platform not supported" -#endif - if (i != nullptr) i->init(this); - } - - inline bool isUnbound() const; - // Checks if this schema is the result of calling SchemaLoader::getUnbound(), in which case - // binding lookups need to be handled specially. -}; - -struct RawSchema { - // The generated code defines a constant RawSchema for every compiled declaration. - // - // This is an internal structure which could change in the future. - - uint64_t id; - - const word* encodedNode; - // Encoded SchemaNode, readable via readMessageUnchecked(encodedNode). - - uint32_t encodedSize; - // Size of encodedNode, in words. - - const RawSchema* const* dependencies; - // Pointers to other types on which this one depends, sorted by ID. The schemas in this table - // may be uninitialized -- you must call ensureInitialized() on the one you wish to use before - // using it. - // - // TODO(someday): Make this a hashtable. - - const uint16_t* membersByName; - // Indexes of members sorted by name. Used to implement name lookup. - // TODO(someday): Make this a hashtable. - - uint32_t dependencyCount; - uint32_t memberCount; - // Sizes of above tables. - - const uint16_t* membersByDiscriminant; - // List of all member indexes ordered by discriminant value. Those which don't have a - // discriminant value are listed at the end, in order by ordinal. - - const RawSchema* canCastTo; - // Points to the RawSchema of a compiled-in type to which it is safe to cast any DynamicValue - // with this schema. This is null for all compiled-in types; it is only set by SchemaLoader on - // dynamically-loaded types. - - class Initializer { - public: - virtual void init(const RawSchema* schema) const = 0; - }; - - const Initializer* lazyInitializer; - // Lazy initializer, invoked by ensureInitialized(). - - inline void ensureInitialized() const { - // Lazy initialization support. Invoke to ensure that initialization has taken place. This - // is required in particular when traversing the dependency list. RawSchemas for compiled-in - // types are always initialized; only dynamically-loaded schemas may be lazy. - -#if __GNUC__ - const Initializer* i = __atomic_load_n(&lazyInitializer, __ATOMIC_ACQUIRE); -#elif _MSC_VER - const Initializer* i = *static_cast(&lazyInitializer); - std::atomic_thread_fence(std::memory_order_acquire); -#else -#error "Platform not supported" -#endif - if (i != nullptr) i->init(this); - } - - RawBrandedSchema defaultBrand; - // Specifies the brand to use for this schema if no generic parameters have been bound to - // anything. Generally, in the default brand, all generic parameters are treated as if they were - // bound to `AnyPointer`. -}; - -inline bool RawBrandedSchema::isUnbound() const { - // The unbound schema is the only one that has no scopes but is not the default schema. - return scopeCount == 0 && this != &generic->defaultBrand; -} - -} // namespace _ (private) -} // namespace capnp - -#endif // CAPNP_RAW_SCHEMA_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/rpc-prelude.h b/phonelibs/capnp-cpp/include/capnp/rpc-prelude.h deleted file mode 100644 index 7d26e39de8..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/rpc-prelude.h +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// This file contains a bunch of internal declarations that must appear before rpc.h can start. -// We don't define these directly in rpc.h because it makes the file hard to read. - -#ifndef CAPNP_RPC_PRELUDE_H_ -#define CAPNP_RPC_PRELUDE_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include "capability.h" -#include "persistent.capnp.h" - -namespace capnp { - -class OutgoingRpcMessage; -class IncomingRpcMessage; - -template -class RpcSystem; - -namespace _ { // private - -class VatNetworkBase { - // Non-template version of VatNetwork. Ignore this class; see VatNetwork in rpc.h. - -public: - class Connection; - - struct ConnectionAndProvisionId { - kj::Own connection; - kj::Own firstMessage; - Orphan provisionId; - }; - - class Connection { - public: - virtual kj::Own newOutgoingMessage(uint firstSegmentWordSize) = 0; - virtual kj::Promise>> receiveIncomingMessage() = 0; - virtual kj::Promise shutdown() = 0; - virtual AnyStruct::Reader baseGetPeerVatId() = 0; - }; - virtual kj::Maybe> baseConnect(AnyStruct::Reader vatId) = 0; - virtual kj::Promise> baseAccept() = 0; -}; - -class SturdyRefRestorerBase { -public: - virtual Capability::Client baseRestore(AnyPointer::Reader ref) = 0; -}; - -class BootstrapFactoryBase { - // Non-template version of BootstrapFactory. Ignore this class; see BootstrapFactory in rpc.h. -public: - virtual Capability::Client baseCreateFor(AnyStruct::Reader clientId) = 0; -}; - -class RpcSystemBase { - // Non-template version of RpcSystem. Ignore this class; see RpcSystem in rpc.h. - -public: - RpcSystemBase(VatNetworkBase& network, kj::Maybe bootstrapInterface, - kj::Maybe::Client> gateway); - RpcSystemBase(VatNetworkBase& network, BootstrapFactoryBase& bootstrapFactory, - kj::Maybe::Client> gateway); - RpcSystemBase(VatNetworkBase& network, SturdyRefRestorerBase& restorer); - RpcSystemBase(RpcSystemBase&& other) noexcept; - ~RpcSystemBase() noexcept(false); - -private: - class Impl; - kj::Own impl; - - Capability::Client baseBootstrap(AnyStruct::Reader vatId); - Capability::Client baseRestore(AnyStruct::Reader vatId, AnyPointer::Reader objectId); - void baseSetFlowLimit(size_t words); - - template - friend class capnp::RpcSystem; -}; - -template struct InternalRefFromRealmGateway_; -template -struct InternalRefFromRealmGateway_> { - typedef InternalRef Type; -}; -template -using InternalRefFromRealmGateway = typename InternalRefFromRealmGateway_::Type; -template -using InternalRefFromRealmGatewayClient = InternalRefFromRealmGateway; - -template struct ExternalRefFromRealmGateway_; -template -struct ExternalRefFromRealmGateway_> { - typedef ExternalRef Type; -}; -template -using ExternalRefFromRealmGateway = typename ExternalRefFromRealmGateway_::Type; -template -using ExternalRefFromRealmGatewayClient = ExternalRefFromRealmGateway; - -} // namespace _ (private) -} // namespace capnp - -#endif // CAPNP_RPC_PRELUDE_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/rpc-twoparty.capnp b/phonelibs/capnp-cpp/include/capnp/rpc-twoparty.capnp deleted file mode 100644 index 0b670e8ac3..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/rpc-twoparty.capnp +++ /dev/null @@ -1,169 +0,0 @@ -# Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -# Licensed under the MIT License: -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -@0xa184c7885cdaf2a1; -# This file defines the "network-specific parameters" in rpc.capnp to support a network consisting -# of two vats. Each of these vats may in fact be in communication with other vats, but any -# capabilities they forward must be proxied. Thus, to each end of the connection, all capabilities -# received from the other end appear to live in a single vat. -# -# Two notable use cases for this model include: -# - Regular client-server communications, where a remote client machine (perhaps living on an end -# user's personal device) connects to a server. The server may be part of a cluster, and may -# call on other servers in the cluster to help service the user's request. It may even obtain -# capabilities from these other servers which it passes on to the user. To simplify network -# common traversal problems (e.g. if the user is behind a firewall), it is probably desirable to -# multiplex all communications between the server cluster and the client over the original -# connection rather than form new ones. This connection should use the two-party protocol, as -# the client has no interest in knowing about additional servers. -# - Applications running in a sandbox. A supervisor process may execute a confined application -# such that all of the confined app's communications with the outside world must pass through -# the supervisor. In this case, the connection between the confined app and the supervisor might -# as well use the two-party protocol, because the confined app is intentionally prevented from -# talking to any other vat anyway. Any external resources will be proxied through the supervisor, -# and so to the contained app will appear as if they were hosted by the supervisor itself. -# -# Since there are only two vats in this network, there is never a need for three-way introductions, -# so level 3 is free. Moreover, because it is never necessary to form new connections, the -# two-party protocol can be used easily anywhere where a two-way byte stream exists, without regard -# to where that byte stream goes or how it was initiated. This makes the two-party runtime library -# highly reusable. -# -# Joins (level 4) _could_ be needed in cases where one or both vats are participating in other -# networks that use joins. For instance, if Alice and Bob are speaking through the two-party -# protocol, and Bob is also participating on another network, Bob may send Alice two or more -# proxied capabilities which, unbeknownst to Bob at the time, are in fact pointing at the same -# remote object. Alice may then request to join these capabilities, at which point Bob will have -# to forward the join to the other network. Note, however, that if Alice is _not_ participating on -# any other network, then Alice will never need to _receive_ a Join, because Alice would always -# know when two locally-hosted capabilities are the same and would never export a redundant alias -# to Bob. So, Alice can respond to all incoming joins with an error, and only needs to implement -# outgoing joins if she herself desires to use this feature. Also, outgoing joins are relatively -# easy to implement in this scenario. -# -# What all this means is that a level 4 implementation of the confined network is barely more -# complicated than a level 2 implementation. However, such an implementation allows the "client" -# or "confined" app to access the server's/supervisor's network with equal functionality to any -# native participant. In other words, an application which implements only the two-party protocol -# can be paired with a proxy app in order to participate in any network. -# -# So, when implementing Cap'n Proto in a new language, it makes sense to implement only the -# two-party protocol initially, and then pair applications with an appropriate proxy written in -# C++, rather than implement other parameterizations of the RPC protocol directly. - -using Cxx = import "/capnp/c++.capnp"; -$Cxx.namespace("capnp::rpc::twoparty"); - -# Note: SturdyRef is not specified here. It is up to the application to define semantics of -# SturdyRefs if desired. - -enum Side { - server @0; - # The object lives on the "server" or "supervisor" end of the connection. Only the - # server/supervisor knows how to interpret the ref; to the client, it is opaque. - # - # Note that containers intending to implement strong confinement should rewrite SturdyRefs - # received from the external network before passing them on to the confined app. The confined - # app thus does not ever receive the raw bits of the SturdyRef (which it could perhaps - # maliciously leak), but instead receives only a thing that it can pass back to the container - # later to restore the ref. See: - # http://www.erights.org/elib/capability/dist-confine.html - - client @1; - # The object lives on the "client" or "confined app" end of the connection. Only the client - # knows how to interpret the ref; to the server/supervisor, it is opaque. Most clients do not - # actually know how to persist capabilities at all, so use of this is unusual. -} - -struct VatId { - side @0 :Side; -} - -struct ProvisionId { - # Only used for joins, since three-way introductions never happen on a two-party network. - - joinId @0 :UInt32; - # The ID from `JoinKeyPart`. -} - -struct RecipientId {} -# Never used, because there are only two parties. - -struct ThirdPartyCapId {} -# Never used, because there is no third party. - -struct JoinKeyPart { - # Joins in the two-party case are simplified by a few observations. - # - # First, on a two-party network, a Join only ever makes sense if the receiving end is also - # connected to other networks. A vat which is not connected to any other network can safely - # reject all joins. - # - # Second, since a two-party connection bisects the network -- there can be no other connections - # between the networks at either end of the connection -- if one part of a join crosses the - # connection, then _all_ parts must cross it. Therefore, a vat which is receiving a Join request - # off some other network which needs to be forwarded across the two-party connection can - # collect all the parts on its end and only forward them across the two-party connection when all - # have been received. - # - # For example, imagine that Alice and Bob are vats connected over a two-party connection, and - # each is also connected to other networks. At some point, Alice receives one part of a Join - # request off her network. The request is addressed to a capability that Alice received from - # Bob and is proxying to her other network. Alice goes ahead and responds to the Join part as - # if she hosted the capability locally (this is important so that if not all the Join parts end - # up at Alice, the original sender can detect the failed Join without hanging). As other parts - # trickle in, Alice verifies that each part is addressed to a capability from Bob and continues - # to respond to each one. Once the complete set of join parts is received, Alice checks if they - # were all for the exact same capability. If so, she doesn't need to send anything to Bob at - # all. Otherwise, she collects the set of capabilities (from Bob) to which the join parts were - # addressed and essentially initiates a _new_ Join request on those capabilities to Bob. Alice - # does not forward the Join parts she received herself, but essentially forwards the Join as a - # whole. - # - # On Bob's end, since he knows that Alice will always send all parts of a Join together, he - # simply waits until he's received them all, then performs a join on the respective capabilities - # as if it had been requested locally. - - joinId @0 :UInt32; - # A number identifying this join, chosen by the sender. May be reused once `Finish` messages are - # sent corresponding to all of the `Join` messages. - - partCount @1 :UInt16; - # The number of capabilities to be joined. - - partNum @2 :UInt16; - # Which part this request targets -- a number in the range [0, partCount). -} - -struct JoinResult { - joinId @0 :UInt32; - # Matches `JoinKeyPart`. - - succeeded @1 :Bool; - # All JoinResults in the set will have the same value for `succeeded`. The receiver actually - # implements the join by waiting for all the `JoinKeyParts` and then performing its own join on - # them, then going back and answering all the join requests afterwards. - - cap @2 :AnyPointer; - # One of the JoinResults will have a non-null `cap` which is the joined capability. - # - # TODO(cleanup): Change `AnyPointer` to `Capability` when that is supported. -} diff --git a/phonelibs/capnp-cpp/include/capnp/rpc-twoparty.capnp.h b/phonelibs/capnp-cpp/include/capnp/rpc-twoparty.capnp.h deleted file mode 100644 index 9d7820646a..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/rpc-twoparty.capnp.h +++ /dev/null @@ -1,726 +0,0 @@ -// Generated by Cap'n Proto compiler, DO NOT EDIT -// source: rpc-twoparty.capnp - -#ifndef CAPNP_INCLUDED_a184c7885cdaf2a1_ -#define CAPNP_INCLUDED_a184c7885cdaf2a1_ - -#include - -#if CAPNP_VERSION != 6001 -#error "Version mismatch between generated code and library headers. You must use the same version of the Cap'n Proto compiler and library." -#endif - - -namespace capnp { -namespace schemas { - -CAPNP_DECLARE_SCHEMA(9fd69ebc87b9719c); -enum class Side_9fd69ebc87b9719c: uint16_t { - SERVER, - CLIENT, -}; -CAPNP_DECLARE_ENUM(Side, 9fd69ebc87b9719c); -CAPNP_DECLARE_SCHEMA(d20b909fee733a8e); -CAPNP_DECLARE_SCHEMA(b88d09a9c5f39817); -CAPNP_DECLARE_SCHEMA(89f389b6fd4082c1); -CAPNP_DECLARE_SCHEMA(b47f4979672cb59d); -CAPNP_DECLARE_SCHEMA(95b29059097fca83); -CAPNP_DECLARE_SCHEMA(9d263a3630b7ebee); - -} // namespace schemas -} // namespace capnp - -namespace capnp { -namespace rpc { -namespace twoparty { - -typedef ::capnp::schemas::Side_9fd69ebc87b9719c Side; - -struct VatId { - VatId() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(d20b909fee733a8e, 1, 0) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct ProvisionId { - ProvisionId() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(b88d09a9c5f39817, 1, 0) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct RecipientId { - RecipientId() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(89f389b6fd4082c1, 0, 0) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct ThirdPartyCapId { - ThirdPartyCapId() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(b47f4979672cb59d, 0, 0) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct JoinKeyPart { - JoinKeyPart() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(95b29059097fca83, 1, 0) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct JoinResult { - JoinResult() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(9d263a3630b7ebee, 1, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -// ======================================================================================= - -class VatId::Reader { -public: - typedef VatId Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::capnp::rpc::twoparty::Side getSide() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class VatId::Builder { -public: - typedef VatId Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::capnp::rpc::twoparty::Side getSide(); - inline void setSide( ::capnp::rpc::twoparty::Side value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class VatId::Pipeline { -public: - typedef VatId Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class ProvisionId::Reader { -public: - typedef ProvisionId Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint32_t getJoinId() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class ProvisionId::Builder { -public: - typedef ProvisionId Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint32_t getJoinId(); - inline void setJoinId( ::uint32_t value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class ProvisionId::Pipeline { -public: - typedef ProvisionId Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class RecipientId::Reader { -public: - typedef RecipientId Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class RecipientId::Builder { -public: - typedef RecipientId Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class RecipientId::Pipeline { -public: - typedef RecipientId Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class ThirdPartyCapId::Reader { -public: - typedef ThirdPartyCapId Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class ThirdPartyCapId::Builder { -public: - typedef ThirdPartyCapId Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class ThirdPartyCapId::Pipeline { -public: - typedef ThirdPartyCapId Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class JoinKeyPart::Reader { -public: - typedef JoinKeyPart Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint32_t getJoinId() const; - - inline ::uint16_t getPartCount() const; - - inline ::uint16_t getPartNum() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class JoinKeyPart::Builder { -public: - typedef JoinKeyPart Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint32_t getJoinId(); - inline void setJoinId( ::uint32_t value); - - inline ::uint16_t getPartCount(); - inline void setPartCount( ::uint16_t value); - - inline ::uint16_t getPartNum(); - inline void setPartNum( ::uint16_t value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class JoinKeyPart::Pipeline { -public: - typedef JoinKeyPart Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class JoinResult::Reader { -public: - typedef JoinResult Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint32_t getJoinId() const; - - inline bool getSucceeded() const; - - inline bool hasCap() const; - inline ::capnp::AnyPointer::Reader getCap() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class JoinResult::Builder { -public: - typedef JoinResult Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint32_t getJoinId(); - inline void setJoinId( ::uint32_t value); - - inline bool getSucceeded(); - inline void setSucceeded(bool value); - - inline bool hasCap(); - inline ::capnp::AnyPointer::Builder getCap(); - inline ::capnp::AnyPointer::Builder initCap(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class JoinResult::Pipeline { -public: - typedef JoinResult Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -// ======================================================================================= - -inline ::capnp::rpc::twoparty::Side VatId::Reader::getSide() const { - return _reader.getDataField< ::capnp::rpc::twoparty::Side>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::rpc::twoparty::Side VatId::Builder::getSide() { - return _builder.getDataField< ::capnp::rpc::twoparty::Side>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void VatId::Builder::setSide( ::capnp::rpc::twoparty::Side value) { - _builder.setDataField< ::capnp::rpc::twoparty::Side>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline ::uint32_t ProvisionId::Reader::getJoinId() const { - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t ProvisionId::Builder::getJoinId() { - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void ProvisionId::Builder::setJoinId( ::uint32_t value) { - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline ::uint32_t JoinKeyPart::Reader::getJoinId() const { - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t JoinKeyPart::Builder::getJoinId() { - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void JoinKeyPart::Builder::setJoinId( ::uint32_t value) { - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline ::uint16_t JoinKeyPart::Reader::getPartCount() const { - return _reader.getDataField< ::uint16_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} - -inline ::uint16_t JoinKeyPart::Builder::getPartCount() { - return _builder.getDataField< ::uint16_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} -inline void JoinKeyPart::Builder::setPartCount( ::uint16_t value) { - _builder.setDataField< ::uint16_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, value); -} - -inline ::uint16_t JoinKeyPart::Reader::getPartNum() const { - return _reader.getDataField< ::uint16_t>( - ::capnp::bounded<3>() * ::capnp::ELEMENTS); -} - -inline ::uint16_t JoinKeyPart::Builder::getPartNum() { - return _builder.getDataField< ::uint16_t>( - ::capnp::bounded<3>() * ::capnp::ELEMENTS); -} -inline void JoinKeyPart::Builder::setPartNum( ::uint16_t value) { - _builder.setDataField< ::uint16_t>( - ::capnp::bounded<3>() * ::capnp::ELEMENTS, value); -} - -inline ::uint32_t JoinResult::Reader::getJoinId() const { - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t JoinResult::Builder::getJoinId() { - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void JoinResult::Builder::setJoinId( ::uint32_t value) { - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool JoinResult::Reader::getSucceeded() const { - return _reader.getDataField( - ::capnp::bounded<32>() * ::capnp::ELEMENTS); -} - -inline bool JoinResult::Builder::getSucceeded() { - return _builder.getDataField( - ::capnp::bounded<32>() * ::capnp::ELEMENTS); -} -inline void JoinResult::Builder::setSucceeded(bool value) { - _builder.setDataField( - ::capnp::bounded<32>() * ::capnp::ELEMENTS, value); -} - -inline bool JoinResult::Reader::hasCap() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool JoinResult::Builder::hasCap() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::AnyPointer::Reader JoinResult::Reader::getCap() const { - return ::capnp::AnyPointer::Reader(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder JoinResult::Builder::getCap() { - return ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder JoinResult::Builder::initCap() { - auto result = ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); - result.clear(); - return result; -} - -} // namespace -} // namespace -} // namespace - -#endif // CAPNP_INCLUDED_a184c7885cdaf2a1_ diff --git a/phonelibs/capnp-cpp/include/capnp/rpc-twoparty.h b/phonelibs/capnp-cpp/include/capnp/rpc-twoparty.h deleted file mode 100644 index 093c1fecdf..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/rpc-twoparty.h +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_RPC_TWOPARTY_H_ -#define CAPNP_RPC_TWOPARTY_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include "rpc.h" -#include "message.h" -#include -#include - -namespace capnp { - -namespace rpc { - namespace twoparty { - typedef VatId SturdyRefHostId; // For backwards-compatibility with version 0.4. - } -} - -typedef VatNetwork - TwoPartyVatNetworkBase; - -class TwoPartyVatNetwork: public TwoPartyVatNetworkBase, - private TwoPartyVatNetworkBase::Connection { - // A `VatNetwork` that consists of exactly two parties communicating over an arbitrary byte - // stream. This is used to implement the common case of a client/server network. - // - // See `ez-rpc.h` for a simple interface for setting up two-party clients and servers. - // Use `TwoPartyVatNetwork` only if you need the advanced features. - -public: - TwoPartyVatNetwork(kj::AsyncIoStream& stream, rpc::twoparty::Side side, - ReaderOptions receiveOptions = ReaderOptions()); - KJ_DISALLOW_COPY(TwoPartyVatNetwork); - - kj::Promise onDisconnect() { return disconnectPromise.addBranch(); } - // Returns a promise that resolves when the peer disconnects. - - rpc::twoparty::Side getSide() { return side; } - - // implements VatNetwork ----------------------------------------------------- - - kj::Maybe> connect( - rpc::twoparty::VatId::Reader ref) override; - kj::Promise> accept() override; - -private: - class OutgoingMessageImpl; - class IncomingMessageImpl; - - kj::AsyncIoStream& stream; - rpc::twoparty::Side side; - MallocMessageBuilder peerVatId; - ReaderOptions receiveOptions; - bool accepted = false; - - kj::Maybe> previousWrite; - // Resolves when the previous write completes. This effectively serves as the write queue. - // Becomes null when shutdown() is called. - - kj::Own>> acceptFulfiller; - // Fulfiller for the promise returned by acceptConnectionAsRefHost() on the client side, or the - // second call on the server side. Never fulfilled, because there is only one connection. - - kj::ForkedPromise disconnectPromise = nullptr; - - class FulfillerDisposer: public kj::Disposer { - // Hack: TwoPartyVatNetwork is both a VatNetwork and a VatNetwork::Connection. When the RPC - // system detects (or initiates) a disconnection, it drops its reference to the Connection. - // When all references have been dropped, then we want disconnectPromise to be fulfilled. - // So we hand out Owns with this disposer attached, so that we can detect when - // they are dropped. - - public: - mutable kj::Own> fulfiller; - mutable uint refcount = 0; - - void disposeImpl(void* pointer) const override; - }; - FulfillerDisposer disconnectFulfiller; - - kj::Own asConnection(); - // Returns a pointer to this with the disposer set to disconnectFulfiller. - - // implements Connection ----------------------------------------------------- - - rpc::twoparty::VatId::Reader getPeerVatId() override; - kj::Own newOutgoingMessage(uint firstSegmentWordSize) override; - kj::Promise>> receiveIncomingMessage() override; - kj::Promise shutdown() override; -}; - -class TwoPartyServer: private kj::TaskSet::ErrorHandler { - // Convenience class which implements a simple server which accepts connections on a listener - // socket and serices them as two-party connections. - -public: - explicit TwoPartyServer(Capability::Client bootstrapInterface); - - void accept(kj::Own&& connection); - // Accepts the connection for servicing. - - kj::Promise listen(kj::ConnectionReceiver& listener); - // Listens for connections on the given listener. The returned promise never resolves unless an - // exception is thrown while trying to accept. You may discard the returned promise to cancel - // listening. - -private: - Capability::Client bootstrapInterface; - kj::TaskSet tasks; - - struct AcceptedConnection; - - void taskFailed(kj::Exception&& exception) override; -}; - -class TwoPartyClient { - // Convenience class which implements a simple client. - -public: - explicit TwoPartyClient(kj::AsyncIoStream& connection); - TwoPartyClient(kj::AsyncIoStream& connection, Capability::Client bootstrapInterface, - rpc::twoparty::Side side = rpc::twoparty::Side::CLIENT); - - Capability::Client bootstrap(); - // Get the server's bootstrap interface. - - inline kj::Promise onDisconnect() { return network.onDisconnect(); } - -private: - TwoPartyVatNetwork network; - RpcSystem rpcSystem; -}; - -} // namespace capnp - -#endif // CAPNP_RPC_TWOPARTY_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/rpc.capnp b/phonelibs/capnp-cpp/include/capnp/rpc.capnp deleted file mode 100644 index cd808b39f7..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/rpc.capnp +++ /dev/null @@ -1,1399 +0,0 @@ -# Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -# Licensed under the MIT License: -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -@0xb312981b2552a250; -# Recall that Cap'n Proto RPC allows messages to contain references to remote objects that -# implement interfaces. These references are called "capabilities", because they both designate -# the remote object to use and confer permission to use it. -# -# Recall also that Cap'n Proto RPC has the feature that when a method call itself returns a -# capability, the caller can begin calling methods on that capability _before the first call has -# returned_. The caller essentially sends a message saying "Hey server, as soon as you finish -# that previous call, do this with the result!". Cap'n Proto's RPC protocol makes this possible. -# -# The protocol is significantly more complicated than most RPC protocols. However, this is -# implementation complexity that underlies an easy-to-grasp higher-level model of object oriented -# programming. That is, just like TCP is a surprisingly complicated protocol that implements a -# conceptually-simple byte stream abstraction, Cap'n Proto is a surprisingly complicated protocol -# that implements a conceptually-simple object abstraction. -# -# Cap'n Proto RPC is based heavily on CapTP, the object-capability protocol used by the E -# programming language: -# http://www.erights.org/elib/distrib/captp/index.html -# -# Cap'n Proto RPC takes place between "vats". A vat hosts some set of objects and talks to other -# vats through direct bilateral connections. Typically, there is a 1:1 correspondence between vats -# and processes (in the unix sense of the word), although this is not strictly always true (one -# process could run multiple vats, or a distributed virtual vat might live across many processes). -# -# Cap'n Proto does not distinguish between "clients" and "servers" -- this is up to the application. -# Either end of any connection can potentially hold capabilities pointing to the other end, and -# can call methods on those capabilities. In the doc comments below, we use the words "sender" -# and "receiver". These refer to the sender and receiver of an instance of the struct or field -# being documented. Sometimes we refer to a "third-party" that is neither the sender nor the -# receiver. Documentation is generally written from the point of view of the sender. -# -# It is generally up to the vat network implementation to securely verify that connections are made -# to the intended vat as well as to encrypt transmitted data for privacy and integrity. See the -# `VatNetwork` example interface near the end of this file. -# -# When a new connection is formed, the only interesting things that can be done are to send a -# `Bootstrap` (level 0) or `Accept` (level 3) message. -# -# Unless otherwise specified, messages must be delivered to the receiving application in the same -# order in which they were initiated by the sending application. The goal is to support "E-Order", -# which states that two calls made on the same reference must be delivered in the order which they -# were made: -# http://erights.org/elib/concurrency/partial-order.html -# -# Since the full protocol is complicated, we define multiple levels of support that an -# implementation may target. For many applications, level 1 support will be sufficient. -# Comments in this file indicate which level requires the corresponding feature to be -# implemented. -# -# * **Level 0:** The implementation does not support object references. Only the bootstrap interface -# can be called. At this level, the implementation does not support object-oriented protocols and -# is similar in complexity to JSON-RPC or Protobuf services. This level should be considered only -# a temporary stepping-stone toward level 1 as the lack of object references drastically changes -# how protocols are designed. Applications _should not_ attempt to design their protocols around -# the limitations of level 0 implementations. -# -# * **Level 1:** The implementation supports simple bilateral interaction with object references -# and promise pipelining, but interactions between three or more parties are supported only via -# proxying of objects. E.g. if Alice (in Vat A) wants to send Bob (in Vat B) a capability -# pointing to Carol (in Vat C), Alice must create a proxy of Carol within Vat A and send Bob a -# reference to that; Bob cannot form a direct connection to Carol. Level 1 implementations do -# not support checking if two capabilities received from different vats actually point to the -# same object ("join"), although they should be able to do this check on capabilities received -# from the same vat. -# -# * **Level 2:** The implementation supports saving persistent capabilities -- i.e. capabilities -# that remain valid even after disconnect, and can be restored on a future connection. When a -# capability is saved, the requester receives a `SturdyRef`, which is a token that can be used -# to restore the capability later. -# -# * **Level 3:** The implementation supports three-way interactions. That is, if Alice (in Vat A) -# sends Bob (in Vat B) a capability pointing to Carol (in Vat C), then Vat B will automatically -# form a direct connection to Vat C rather than have requests be proxied through Vat A. -# -# * **Level 4:** The entire protocol is implemented, including joins (checking if two capabilities -# are equivalent). -# -# Note that an implementation must also support specific networks (transports), as described in -# the "Network-specific Parameters" section below. An implementation might have different levels -# depending on the network used. -# -# New implementations of Cap'n Proto should start out targeting the simplistic two-party network -# type as defined in `rpc-twoparty.capnp`. With this network type, level 3 is irrelevant and -# levels 2 and 4 are much easier than usual to implement. When such an implementation is paired -# with a container proxy, the contained app effectively gets to make full use of the proxy's -# network at level 4. And since Cap'n Proto IPC is extremely fast, it may never make sense to -# bother implementing any other vat network protocol -- just use the correct container type and get -# it for free. - -using Cxx = import "/capnp/c++.capnp"; -$Cxx.namespace("capnp::rpc"); - -# ======================================================================================== -# The Four Tables -# -# Cap'n Proto RPC connections are stateful (although an application built on Cap'n Proto could -# export a stateless interface). As in CapTP, for each open connection, a vat maintains four state -# tables: questions, answers, imports, and exports. See the diagram at: -# http://www.erights.org/elib/distrib/captp/4tables.html -# -# The question table corresponds to the other end's answer table, and the imports table corresponds -# to the other end's exports table. -# -# The entries in each table are identified by ID numbers (defined below as 32-bit integers). These -# numbers are always specific to the connection; a newly-established connection starts with no -# valid IDs. Since low-numbered IDs will pack better, it is suggested that IDs be assigned like -# Unix file descriptors -- prefer the lowest-number ID that is currently available. -# -# IDs in the questions/answers tables are chosen by the questioner and generally represent method -# calls that are in progress. -# -# IDs in the imports/exports tables are chosen by the exporter and generally represent objects on -# which methods may be called. Exports may be "settled", meaning the exported object is an actual -# object living in the exporter's vat, or they may be "promises", meaning the exported object is -# the as-yet-unknown result of an ongoing operation and will eventually be resolved to some other -# object once that operation completes. Calls made to a promise will be forwarded to the eventual -# target once it is known. The eventual replacement object does *not* get the same ID as the -# promise, as it may turn out to be an object that is already exported (so already has an ID) or -# may even live in a completely different vat (and so won't get an ID on the same export table -# at all). -# -# IDs can be reused over time. To make this safe, we carefully define the lifetime of IDs. Since -# messages using the ID could be traveling in both directions simultaneously, we must define the -# end of life of each ID _in each direction_. The ID is only safe to reuse once it has been -# released by both sides. -# -# When a Cap'n Proto connection is lost, everything on the four tables is lost. All questions are -# canceled and throw exceptions. All imports become broken (all future calls to them throw -# exceptions). All exports and answers are implicitly released. The only things not lost are -# persistent capabilities (`SturdyRef`s). The application must plan for this and should respond by -# establishing a new connection and restoring from these persistent capabilities. - -using QuestionId = UInt32; -# **(level 0)** -# -# Identifies a question in the sender's question table (which corresponds to the receiver's answer -# table). The questioner (caller) chooses an ID when making a call. The ID remains valid in -# caller -> callee messages until a Finish message is sent, and remains valid in callee -> caller -# messages until a Return message is sent. - -using AnswerId = QuestionId; -# **(level 0)** -# -# Identifies an answer in the sender's answer table (which corresponds to the receiver's question -# table). -# -# AnswerId is physically equivalent to QuestionId, since the question and answer tables correspond, -# but we define a separate type for documentation purposes: we always use the type representing -# the sender's point of view. - -using ExportId = UInt32; -# **(level 1)** -# -# Identifies an exported capability or promise in the sender's export table (which corresponds -# to the receiver's import table). The exporter chooses an ID before sending a capability over the -# wire. If the capability is already in the table, the exporter should reuse the same ID. If the -# ID is a promise (as opposed to a settled capability), this must be indicated at the time the ID -# is introduced (e.g. by using `senderPromise` instead of `senderHosted` in `CapDescriptor`); in -# this case, the importer shall expect a later `Resolve` message that replaces the promise. -# -# ExportId/ImportIds are subject to reference counting. Whenever an `ExportId` is sent over the -# wire (from the exporter to the importer), the export's reference count is incremented (unless -# otherwise specified). The reference count is later decremented by a `Release` message. Since -# the `Release` message can specify an arbitrary number by which to reduce the reference count, the -# importer should usually batch reference decrements and only send a `Release` when it believes the -# reference count has hit zero. Of course, it is possible that a new reference to the export is -# in-flight at the time that the `Release` message is sent, so it is necessary for the exporter to -# keep track of the reference count on its end as well to avoid race conditions. -# -# When a connection is lost, all exports are implicitly released. It is not possible to restore -# a connection state after disconnect (although a transport layer could implement a concept of -# persistent connections if it is transparent to the RPC layer). - -using ImportId = ExportId; -# **(level 1)** -# -# Identifies an imported capability or promise in the sender's import table (which corresponds to -# the receiver's export table). -# -# ImportId is physically equivalent to ExportId, since the export and import tables correspond, -# but we define a separate type for documentation purposes: we always use the type representing -# the sender's point of view. -# -# An `ImportId` remains valid in importer -> exporter messages until the importer has sent -# `Release` messages that (it believes) have reduced the reference count to zero. - -# ======================================================================================== -# Messages - -struct Message { - # An RPC connection is a bi-directional stream of Messages. - - union { - unimplemented @0 :Message; - # The sender previously received this message from the peer but didn't understand it or doesn't - # yet implement the functionality that was requested. So, the sender is echoing the message - # back. In some cases, the receiver may be able to recover from this by pretending the sender - # had taken some appropriate "null" action. - # - # For example, say `resolve` is received by a level 0 implementation (because a previous call - # or return happened to contain a promise). The level 0 implementation will echo it back as - # `unimplemented`. The original sender can then simply release the cap to which the promise - # had resolved, thus avoiding a leak. - # - # For any message type that introduces a question, if the message comes back unimplemented, - # the original sender may simply treat it as if the question failed with an exception. - # - # In cases where there is no sensible way to react to an `unimplemented` message (without - # resource leaks or other serious problems), the connection may need to be aborted. This is - # a gray area; different implementations may take different approaches. - - abort @1 :Exception; - # Sent when a connection is being aborted due to an unrecoverable error. This could be e.g. - # because the sender received an invalid or nonsensical message (`isCallersFault` is true) or - # because the sender had an internal error (`isCallersFault` is false). The sender will shut - # down the outgoing half of the connection after `abort` and will completely close the - # connection shortly thereafter (it's up to the sender how much of a time buffer they want to - # offer for the client to receive the `abort` before the connection is reset). - - # Level 0 features ----------------------------------------------- - - bootstrap @8 :Bootstrap; # Request the peer's bootstrap interface. - call @2 :Call; # Begin a method call. - return @3 :Return; # Complete a method call. - finish @4 :Finish; # Release a returned answer / cancel a call. - - # Level 1 features ----------------------------------------------- - - resolve @5 :Resolve; # Resolve a previously-sent promise. - release @6 :Release; # Release a capability so that the remote object can be deallocated. - disembargo @13 :Disembargo; # Lift an embargo used to enforce E-order over promise resolution. - - # Level 2 features ----------------------------------------------- - - obsoleteSave @7 :AnyPointer; - # Obsolete request to save a capability, resulting in a SturdyRef. This has been replaced - # by the `Persistent` interface defined in `persistent.capnp`. This operation was never - # implemented. - - obsoleteDelete @9 :AnyPointer; - # Obsolete way to delete a SturdyRef. This operation was never implemented. - - # Level 3 features ----------------------------------------------- - - provide @10 :Provide; # Provide a capability to a third party. - accept @11 :Accept; # Accept a capability provided by a third party. - - # Level 4 features ----------------------------------------------- - - join @12 :Join; # Directly connect to the common root of two or more proxied caps. - } -} - -# Level 0 message types ---------------------------------------------- - -struct Bootstrap { - # **(level 0)** - # - # Get the "bootstrap" interface exported by the remote vat. - # - # For level 0, 1, and 2 implementations, the "bootstrap" interface is simply the main interface - # exported by a vat. If the vat acts as a server fielding connections from clients, then the - # bootstrap interface defines the basic functionality available to a client when it connects. - # The exact interface definition obviously depends on the application. - # - # We call this a "bootstrap" because in an ideal Cap'n Proto world, bootstrap interfaces would - # never be used. In such a world, any time you connect to a new vat, you do so because you - # received an introduction from some other vat (see `ThirdPartyCapId`). Thus, the first message - # you send is `Accept`, and further communications derive from there. `Bootstrap` is not used. - # - # In such an ideal world, DNS itself would support Cap'n Proto -- performing a DNS lookup would - # actually return a new Cap'n Proto capability, thus introducing you to the target system via - # level 3 RPC. Applications would receive the capability to talk to DNS in the first place as - # an initial endowment or part of a Powerbox interaction. Therefore, an app can form arbitrary - # connections without ever using `Bootstrap`. - # - # Of course, in the real world, DNS is not Cap'n-Proto-based, and we don't want Cap'n Proto to - # require a whole new internet infrastructure to be useful. Therefore, we offer bootstrap - # interfaces as a way to get up and running without a level 3 introduction. Thus, bootstrap - # interfaces are used to "bootstrap" from other, non-Cap'n-Proto-based means of service discovery, - # such as legacy DNS. - # - # Note that a vat need not provide a bootstrap interface, and in fact many vats (especially those - # acting as clients) do not. In this case, the vat should either reply to `Bootstrap` with a - # `Return` indicating an exception, or should return a dummy capability with no methods. - - questionId @0 :QuestionId; - # A new question ID identifying this request, which will eventually receive a Return message - # containing the restored capability. - - deprecatedObjectId @1 :AnyPointer; - # ** DEPRECATED ** - # - # A Vat may export multiple bootstrap interfaces. In this case, `deprecatedObjectId` specifies - # which one to return. If this pointer is null, then the default bootstrap interface is returned. - # - # As of verison 0.5, use of this field is deprecated. If a service wants to export multiple - # bootstrap interfaces, it should instead define a single bootstarp interface that has methods - # that return each of the other interfaces. - # - # **History** - # - # In the first version of Cap'n Proto RPC (0.4.x) the `Bootstrap` message was called `Restore`. - # At the time, it was thought that this would eventually serve as the way to restore SturdyRefs - # (level 2). Meanwhile, an application could offer its "main" interface on a well-known - # (non-secret) SturdyRef. - # - # Since level 2 RPC was not implemented at the time, the `Restore` message was in practice only - # used to obtain the main interface. Since most applications had only one main interface that - # they wanted to restore, they tended to designate this with a null `objectId`. - # - # Unfortunately, the earliest version of the EZ RPC interfaces set a precedent of exporting - # multiple main interfaces by allowing them to be exported under string names. In this case, - # `objectId` was a Text value specifying the name. - # - # All of this proved problematic for several reasons: - # - # - The arrangement assumed that a client wishing to restore a SturdyRef would know exactly what - # machine to connect to and would be able to immediately restore a SturdyRef on connection. - # However, in practice, the ability to restore SturdyRefs is itself a capability that may - # require going through an authentication process to obtain. Thus, it makes more sense to - # define a "restorer service" as a full Cap'n Proto interface. If this restorer interface is - # offered as the vat's bootstrap interface, then this is equivalent to the old arrangement. - # - # - Overloading "Restore" for the purpose of obtaining well-known capabilities encouraged the - # practice of exporting singleton services with string names. If singleton services are desired, - # it is better to have one main interface that has methods that can be used to obtain each - # service, in order to get all the usual benefits of schemas and type checking. - # - # - Overloading "Restore" also had a security problem: Often, "main" or "well-known" - # capabilities exported by a vat are in fact not public: they are intended to be accessed only - # by clients who are capable of forming a connection to the vat. This can lead to trouble if - # the client itself has other clients and wishes to foward some `Restore` requests from those - # external clients -- it has to be very careful not to allow through `Restore` requests - # addressing the default capability. - # - # For example, consider the case of a sandboxed Sandstorm application and its supervisor. The - # application exports a default capability to its supervisor that provides access to - # functionality that only the supervisor is supposed to access. Meanwhile, though, applications - # may publish other capabilities that may be persistent, in which case the application needs - # to field `Restore` requests that could come from anywhere. These requests of course have to - # pass through the supervisor, as all communications with the outside world must. But, the - # supervisor has to be careful not to honor an external request addressing the application's - # default capability, since this capability is privileged. Unfortunately, the default - # capability cannot be given an unguessable name, because then the supervisor itself would not - # be able to address it! - # - # As of Cap'n Proto 0.5, `Restore` has been renamed to `Bootstrap` and is no longer planned for - # use in restoring SturdyRefs. - # - # Note that 0.4 also defined a message type called `Delete` that, like `Restore`, addressed a - # SturdyRef, but indicated that the client would not restore the ref again in the future. This - # operation was never implemented, so it was removed entirely. If a "delete" operation is desired, - # it should exist as a method on the same interface that handles restoring SturdyRefs. However, - # the utility of such an operation is questionable. You wouldn't be able to rely on it for - # garbage collection since a client could always disappear permanently without remembering to - # delete all its SturdyRefs, thus leaving them dangling forever. Therefore, it is advisable to - # design systems such that SturdyRefs never represent "owned" pointers. - # - # For example, say a SturdyRef points to an image file hosted on some server. That image file - # should also live inside a collection (a gallery, perhaps) hosted on the same server, owned by - # a user who can delete the image at any time. If the user deletes the image, the SturdyRef - # stops working. On the other hand, if the SturdyRef is discarded, this has no effect on the - # existence of the image in its collection. -} - -struct Call { - # **(level 0)** - # - # Message type initiating a method call on a capability. - - questionId @0 :QuestionId; - # A number, chosen by the caller, that identifies this call in future messages. This number - # must be different from all other calls originating from the same end of the connection (but - # may overlap with question IDs originating from the opposite end). A fine strategy is to use - # sequential question IDs, but the recipient should not assume this. - # - # A question ID can be reused once both: - # - A matching Return has been received from the callee. - # - A matching Finish has been sent from the caller. - - target @1 :MessageTarget; - # The object that should receive this call. - - interfaceId @2 :UInt64; - # The type ID of the interface being called. Each capability may implement multiple interfaces. - - methodId @3 :UInt16; - # The ordinal number of the method to call within the requested interface. - - allowThirdPartyTailCall @8 :Bool = false; - # Indicates whether or not the receiver is allowed to send a `Return` containing - # `acceptFromThirdParty`. Level 3 implementations should set this true. Otherwise, the callee - # will have to proxy the return in the case of a tail call to a third-party vat. - - params @4 :Payload; - # The call parameters. `params.content` is a struct whose fields correspond to the parameters of - # the method. - - sendResultsTo :union { - # Where should the return message be sent? - - caller @5 :Void; - # Send the return message back to the caller (the usual). - - yourself @6 :Void; - # **(level 1)** - # - # Don't actually return the results to the sender. Instead, hold on to them and await - # instructions from the sender regarding what to do with them. In particular, the sender - # may subsequently send a `Return` for some other call (which the receiver had previously made - # to the sender) with `takeFromOtherQuestion` set. The results from this call are then used - # as the results of the other call. - # - # When `yourself` is used, the receiver must still send a `Return` for the call, but sets the - # field `resultsSentElsewhere` in that `Return` rather than including the results. - # - # This feature can be used to implement tail calls in which a call from Vat A to Vat B ends up - # returning the result of a call from Vat B back to Vat A. - # - # In particular, the most common use case for this feature is when Vat A makes a call to a - # promise in Vat B, and then that promise ends up resolving to a capability back in Vat A. - # Vat B must forward all the queued calls on that promise back to Vat A, but can set `yourself` - # in the calls so that the results need not pass back through Vat B. - # - # For example: - # - Alice, in Vat A, call foo() on Bob in Vat B. - # - Alice makes a pipelined call bar() on the promise returned by foo(). - # - Later on, Bob resolves the promise from foo() to point at Carol, who lives in Vat A (next - # to Alice). - # - Vat B dutifully forwards the bar() call to Carol. Let us call this forwarded call bar'(). - # Notice that bar() and bar'() are travelling in opposite directions on the same network - # link. - # - The `Call` for bar'() has `sendResultsTo` set to `yourself`, with the value being the - # question ID originally assigned to the bar() call. - # - Vat A receives bar'() and delivers it to Carol. - # - When bar'() returns, Vat A immediately takes the results and returns them from bar(). - # - Meanwhile, Vat A sends a `Return` for bar'() to Vat B, with `resultsSentElsewhere` set in - # place of results. - # - Vat A sends a `Finish` for that call to Vat B. - # - Vat B receives the `Return` for bar'() and sends a `Return` for bar(), with - # `receivedFromYourself` set in place of the results. - # - Vat B receives the `Finish` for bar() and sends a `Finish` to bar'(). - - thirdParty @7 :RecipientId; - # **(level 3)** - # - # The call's result should be returned to a different vat. The receiver (the callee) expects - # to receive an `Accept` message from the indicated vat, and should return the call's result - # to it, rather than to the sender of the `Call`. - # - # This operates much like `yourself`, above, except that Carol is in a separate Vat C. `Call` - # messages are sent from Vat A -> Vat B and Vat B -> Vat C. A `Return` message is sent from - # Vat B -> Vat A that contains `acceptFromThirdParty` in place of results. When Vat A sends - # an `Accept` to Vat C, it receives back a `Return` containing the call's actual result. Vat C - # also sends a `Return` to Vat B with `resultsSentElsewhere`. - } -} - -struct Return { - # **(level 0)** - # - # Message type sent from callee to caller indicating that the call has completed. - - answerId @0 :AnswerId; - # Equal to the QuestionId of the corresponding `Call` message. - - releaseParamCaps @1 :Bool = true; - # If true, all capabilities that were in the params should be considered released. The sender - # must not send separate `Release` messages for them. Level 0 implementations in particular - # should always set this true. This defaults true because if level 0 implementations forget to - # set it they'll never notice (just silently leak caps), but if level >=1 implementations forget - # to set it to false they'll quickly get errors. - - union { - results @2 :Payload; - # The result. - # - # For regular method calls, `results.content` points to the result struct. - # - # For a `Return` in response to an `Accept`, `results` contains a single capability (rather - # than a struct), and `results.content` is just a capability pointer with index 0. A `Finish` - # is still required in this case. - - exception @3 :Exception; - # Indicates that the call failed and explains why. - - canceled @4 :Void; - # Indicates that the call was canceled due to the caller sending a Finish message - # before the call had completed. - - resultsSentElsewhere @5 :Void; - # This is set when returning from a `Call` that had `sendResultsTo` set to something other - # than `caller`. - - takeFromOtherQuestion @6 :QuestionId; - # The sender has also sent (before this message) a `Call` with the given question ID and with - # `sendResultsTo.yourself` set, and the results of that other call should be used as the - # results here. - - acceptFromThirdParty @7 :ThirdPartyCapId; - # **(level 3)** - # - # The caller should contact a third-party vat to pick up the results. An `Accept` message - # sent to the vat will return the result. This pairs with `Call.sendResultsTo.thirdParty`. - # It should only be used if the corresponding `Call` had `allowThirdPartyTailCall` set. - } -} - -struct Finish { - # **(level 0)** - # - # Message type sent from the caller to the callee to indicate: - # 1) The questionId will no longer be used in any messages sent by the callee (no further - # pipelined requests). - # 2) If the call has not returned yet, the caller no longer cares about the result. If nothing - # else cares about the result either (e.g. there are no other outstanding calls pipelined on - # the result of this one) then the callee may wish to immediately cancel the operation and - # send back a Return message with "canceled" set. However, implementations are not required - # to support premature cancellation -- instead, the implementation may wait until the call - # actually completes and send a normal `Return` message. - # - # TODO(someday): Should we separate (1) and implicitly releasing result capabilities? It would be - # possible and useful to notify the server that it doesn't need to keep around the response to - # service pipeline requests even though the caller still wants to receive it / hasn't yet - # finished processing it. It could also be useful to notify the server that it need not marshal - # the results because the caller doesn't want them anyway, even if the caller is still sending - # pipelined calls, although this seems less useful (just saving some bytes on the wire). - - questionId @0 :QuestionId; - # ID of the call whose result is to be released. - - releaseResultCaps @1 :Bool = true; - # If true, all capabilities that were in the results should be considered released. The sender - # must not send separate `Release` messages for them. Level 0 implementations in particular - # should always set this true. This defaults true because if level 0 implementations forget to - # set it they'll never notice (just silently leak caps), but if level >=1 implementations forget - # set it false they'll quickly get errors. -} - -# Level 1 message types ---------------------------------------------- - -struct Resolve { - # **(level 1)** - # - # Message type sent to indicate that a previously-sent promise has now been resolved to some other - # object (possibly another promise) -- or broken, or canceled. - # - # Keep in mind that it's possible for a `Resolve` to be sent to a level 0 implementation that - # doesn't implement it. For example, a method call or return might contain a capability in the - # payload. Normally this is fine even if the receiver is level 0, because they will implicitly - # release all such capabilities on return / finish. But if the cap happens to be a promise, then - # a follow-up `Resolve` may be sent regardless of this release. The level 0 receiver will reply - # with an `unimplemented` message, and the sender (of the `Resolve`) can respond to this as if the - # receiver had immediately released any capability to which the promise resolved. - # - # When implementing promise resolution, it's important to understand how embargos work and the - # tricky case of the Tribble 4-way race condition. See the comments for the Disembargo message, - # below. - - promiseId @0 :ExportId; - # The ID of the promise to be resolved. - # - # Unlike all other instances of `ExportId` sent from the exporter, the `Resolve` message does - # _not_ increase the reference count of `promiseId`. In fact, it is expected that the receiver - # will release the export soon after receiving `Resolve`, and the sender will not send this - # `ExportId` again until it has been released and recycled. - # - # When an export ID sent over the wire (e.g. in a `CapDescriptor`) is indicated to be a promise, - # this indicates that the sender will follow up at some point with a `Resolve` message. If the - # same `promiseId` is sent again before `Resolve`, still only one `Resolve` is sent. If the - # same ID is sent again later _after_ a `Resolve`, it can only be because the export's - # reference count hit zero in the meantime and the ID was re-assigned to a new export, therefore - # this later promise does _not_ correspond to the earlier `Resolve`. - # - # If a promise ID's reference count reaches zero before a `Resolve` is sent, the `Resolve` - # message may or may not still be sent (the `Resolve` may have already been in-flight when - # `Release` was sent, but if the `Release` is received before `Resolve` then there is no longer - # any reason to send a `Resolve`). Thus a `Resolve` may be received for a promise of which - # the receiver has no knowledge, because it already released it earlier. In this case, the - # receiver should simply release the capability to which the promise resolved. - - union { - cap @1 :CapDescriptor; - # The object to which the promise resolved. - # - # The sender promises that from this point forth, until `promiseId` is released, it shall - # simply forward all messages to the capability designated by `cap`. This is true even if - # `cap` itself happens to desigate another promise, and that other promise later resolves -- - # messages sent to `promiseId` shall still go to that other promise, not to its resolution. - # This is important in the case that the receiver of the `Resolve` ends up sending a - # `Disembargo` message towards `promiseId` in order to control message ordering -- that - # `Disembargo` really needs to reflect back to exactly the object designated by `cap` even - # if that object is itself a promise. - - exception @2 :Exception; - # Indicates that the promise was broken. - } -} - -struct Release { - # **(level 1)** - # - # Message type sent to indicate that the sender is done with the given capability and the receiver - # can free resources allocated to it. - - id @0 :ImportId; - # What to release. - - referenceCount @1 :UInt32; - # The amount by which to decrement the reference count. The export is only actually released - # when the reference count reaches zero. -} - -struct Disembargo { - # **(level 1)** - # - # Message sent to indicate that an embargo on a recently-resolved promise may now be lifted. - # - # Embargos are used to enforce E-order in the presence of promise resolution. That is, if an - # application makes two calls foo() and bar() on the same capability reference, in that order, - # the calls should be delivered in the order in which they were made. But if foo() is called - # on a promise, and that promise happens to resolve before bar() is called, then the two calls - # may travel different paths over the network, and thus could arrive in the wrong order. In - # this case, the call to `bar()` must be embargoed, and a `Disembargo` message must be sent along - # the same path as `foo()` to ensure that the `Disembargo` arrives after `foo()`. Once the - # `Disembargo` arrives, `bar()` can then be delivered. - # - # There are two particular cases where embargos are important. Consider object Alice, in Vat A, - # who holds a promise P, pointing towards Vat B, that eventually resolves to Carol. The two - # cases are: - # - Carol lives in Vat A, i.e. next to Alice. In this case, Vat A needs to send a `Disembargo` - # message that echos through Vat B and back, to ensure that all pipelined calls on the promise - # have been delivered. - # - Carol lives in a different Vat C. When the promise resolves, a three-party handoff occurs - # (see `Provide` and `Accept`, which constitute level 3 of the protocol). In this case, we - # piggyback on the state that has already been set up to handle the handoff: the `Accept` - # message (from Vat A to Vat C) is embargoed, as are all pipelined messages sent to it, while - # a `Disembargo` message is sent from Vat A through Vat B to Vat C. See `Accept.embargo` for - # an example. - # - # Note that in the case where Carol actually lives in Vat B (i.e., the same vat that the promise - # already pointed at), no embargo is needed, because the pipelined calls are delivered over the - # same path as the later direct calls. - # - # Keep in mind that promise resolution happens both in the form of Resolve messages as well as - # Return messages (which resolve PromisedAnswers). Embargos apply in both cases. - # - # An alternative strategy for enforcing E-order over promise resolution could be for Vat A to - # implement the embargo internally. When Vat A is notified of promise resolution, it could - # send a dummy no-op call to promise P and wait for it to complete. Until that call completes, - # all calls to the capability are queued locally. This strategy works, but is pessimistic: - # in the three-party case, it requires an A -> B -> C -> B -> A round trip before calls can start - # being delivered directly to from Vat A to Vat C. The `Disembargo` message allows latency to be - # reduced. (In the two-party loopback case, the `Disembargo` message is just a more explicit way - # of accomplishing the same thing as a no-op call, but isn't any faster.) - # - # *The Tribble 4-way Race Condition* - # - # Any implementation of promise resolution and embargos must be aware of what we call the - # "Tribble 4-way race condition", after Dean Tribble, who explained the problem in a lively - # Friam meeting. - # - # Embargos are designed to work in the case where a two-hop path is being shortened to one hop. - # But sometimes there are more hops. Imagine that Alice has a reference to a remote promise P1 - # that eventually resolves to _another_ remote promise P2 (in a third vat), which _at the same - # time_ happens to resolve to Bob (in a fourth vat). In this case, we're shortening from a 3-hop - # path (with four parties) to a 1-hop path (Alice -> Bob). - # - # Extending the embargo/disembargo protocol to be able to shorted multiple hops at once seems - # difficult. Instead, we make a rule that prevents this case from coming up: - # - # One a promise P has been resolved to a remove object reference R, then all further messages - # received addressed to P will be forwarded strictly to R. Even if it turns out later that R is - # itself a promise, and has resolved to some other object Q, messages sent to P will still be - # forwarded to R, not directly to Q (R will of course further forward the messages to Q). - # - # This rule does not cause a significant performance burden because once P has resolved to R, it - # is expected that people sending messages to P will shortly start sending them to R instead and - # drop P. P is at end-of-life anyway, so it doesn't matter if it ignores chances to further - # optimize its path. - - target @0 :MessageTarget; - # What is to be disembargoed. - - using EmbargoId = UInt32; - # Used in `senderLoopback` and `receiverLoopback`, below. - - context :union { - senderLoopback @1 :EmbargoId; - # The sender is requesting a disembargo on a promise that is known to resolve back to a - # capability hosted by the sender. As soon as the receiver has echoed back all pipelined calls - # on this promise, it will deliver the Disembargo back to the sender with `receiverLoopback` - # set to the same value as `senderLoopback`. This value is chosen by the sender, and since - # it is also consumed be the sender, the sender can use whatever strategy it wants to make sure - # the value is unambiguous. - # - # The receiver must verify that the target capability actually resolves back to the sender's - # vat. Otherwise, the sender has committed a protocol error and should be disconnected. - - receiverLoopback @2 :EmbargoId; - # The receiver previously sent a `senderLoopback` Disembargo towards a promise resolving to - # this capability, and that Disembargo is now being echoed back. - - accept @3 :Void; - # **(level 3)** - # - # The sender is requesting a disembargo on a promise that is known to resolve to a third-party - # capability that the sender is currently in the process of accepting (using `Accept`). - # The receiver of this `Disembargo` has an outstanding `Provide` on said capability. The - # receiver should now send a `Disembargo` with `provide` set to the question ID of that - # `Provide` message. - # - # See `Accept.embargo` for an example. - - provide @4 :QuestionId; - # **(level 3)** - # - # The sender is requesting a disembargo on a capability currently being provided to a third - # party. The question ID identifies the `Provide` message previously sent by the sender to - # this capability. On receipt, the receiver (the capability host) shall release the embargo - # on the `Accept` message that it has received from the third party. See `Accept.embargo` for - # an example. - } -} - -# Level 2 message types ---------------------------------------------- - -# See persistent.capnp. - -# Level 3 message types ---------------------------------------------- - -struct Provide { - # **(level 3)** - # - # Message type sent to indicate that the sender wishes to make a particular capability implemented - # by the receiver available to a third party for direct access (without the need for the third - # party to proxy through the sender). - # - # (In CapTP, `Provide` and `Accept` are methods of the global `NonceLocator` object exported by - # every vat. In Cap'n Proto, we bake this into the core protocol.) - - questionId @0 :QuestionId; - # Question ID to be held open until the recipient has received the capability. A result will be - # returned once the third party has successfully received the capability. The sender must at some - # point send a `Finish` message as with any other call, and that message can be used to cancel the - # whole operation. - - target @1 :MessageTarget; - # What is to be provided to the third party. - - recipient @2 :RecipientId; - # Identity of the third party that is expected to pick up the capability. -} - -struct Accept { - # **(level 3)** - # - # Message type sent to pick up a capability hosted by the receiving vat and provided by a third - # party. The third party previously designated the capability using `Provide`. - # - # This message is also used to pick up a redirected return -- see `Return.redirect`. - - questionId @0 :QuestionId; - # A new question ID identifying this accept message, which will eventually receive a Return - # message containing the provided capability (or the call result in the case of a redirected - # return). - - provision @1 :ProvisionId; - # Identifies the provided object to be picked up. - - embargo @2 :Bool; - # If true, this accept shall be temporarily embargoed. The resulting `Return` will not be sent, - # and any pipelined calls will not be delivered, until the embargo is released. The receiver - # (the capability host) will expect the provider (the vat that sent the `Provide` message) to - # eventually send a `Disembargo` message with the field `context.provide` set to the question ID - # of the original `Provide` message. At that point, the embargo is released and the queued - # messages are delivered. - # - # For example: - # - Alice, in Vat A, holds a promise P, which currently points toward Vat B. - # - Alice calls foo() on P. The `Call` message is sent to Vat B. - # - The promise P in Vat B ends up resolving to Carol, in Vat C. - # - Vat B sends a `Provide` message to Vat C, identifying Vat A as the recipient. - # - Vat B sends a `Resolve` message to Vat A, indicating that the promise has resolved to a - # `ThirdPartyCapId` identifying Carol in Vat C. - # - Vat A sends an `Accept` message to Vat C to pick up the capability. Since Vat A knows that - # it has an outstanding call to the promise, it sets `embargo` to `true` in the `Accept` - # message. - # - Vat A sends a `Disembargo` message to Vat B on promise P, with `context.accept` set. - # - Alice makes a call bar() to promise P, which is now pointing towards Vat C. Alice doesn't - # know anything about the mechanics of promise resolution happening under the hood, but she - # expects that bar() will be delivered after foo() because that is the order in which she - # initiated the calls. - # - Vat A sends the bar() call to Vat C, as a pipelined call on the result of the `Accept` (which - # hasn't returned yet, due to the embargo). Since calls to the newly-accepted capability - # are embargoed, Vat C does not deliver the call yet. - # - At some point, Vat B forwards the foo() call from the beginning of this example on to Vat C. - # - Vat B forwards the `Disembargo` from Vat A on to vat C. It sets `context.provide` to the - # question ID of the `Provide` message it had sent previously. - # - Vat C receives foo() before `Disembargo`, thus allowing it to correctly deliver foo() - # before delivering bar(). - # - Vat C receives `Disembargo` from Vat B. It can now send a `Return` for the `Accept` from - # Vat A, as well as deliver bar(). -} - -# Level 4 message types ---------------------------------------------- - -struct Join { - # **(level 4)** - # - # Message type sent to implement E.join(), which, given a number of capabilities that are - # expected to be equivalent, finds the underlying object upon which they all agree and forms a - # direct connection to it, skipping any proxies that may have been constructed by other vats - # while transmitting the capability. See: - # http://erights.org/elib/equality/index.html - # - # Note that this should only serve to bypass fully-transparent proxies -- proxies that were - # created merely for convenience, without any intention of hiding the underlying object. - # - # For example, say Bob holds two capabilities hosted by Alice and Carol, but he expects that both - # are simply proxies for a capability hosted elsewhere. He then issues a join request, which - # operates as follows: - # - Bob issues Join requests on both Alice and Carol. Each request contains a different piece - # of the JoinKey. - # - Alice is proxying a capability hosted by Dana, so forwards the request to Dana's cap. - # - Dana receives the first request and sees that the JoinKeyPart is one of two. She notes that - # she doesn't have the other part yet, so she records the request and responds with a - # JoinResult. - # - Alice relays the JoinAswer back to Bob. - # - Carol is also proxying a capability from Dana, and so forwards her Join request to Dana as - # well. - # - Dana receives Carol's request and notes that she now has both parts of a JoinKey. She - # combines them in order to form information needed to form a secure connection to Bob. She - # also responds with another JoinResult. - # - Bob receives the responses from Alice and Carol. He uses the returned JoinResults to - # determine how to connect to Dana and attempts to form the connection. Since Bob and Dana now - # agree on a secret key that neither Alice nor Carol ever saw, this connection can be made - # securely even if Alice or Carol is conspiring against the other. (If Alice and Carol are - # conspiring _together_, they can obviously reproduce the key, but this doesn't matter because - # the whole point of the join is to verify that Alice and Carol agree on what capability they - # are proxying.) - # - # If the two capabilities aren't actually proxies of the same object, then the join requests - # will come back with conflicting `hostId`s and the join will fail before attempting to form any - # connection. - - questionId @0 :QuestionId; - # Question ID used to respond to this Join. (Note that this ID only identifies one part of the - # request for one hop; each part has a different ID and relayed copies of the request have - # (probably) different IDs still.) - # - # The receiver will reply with a `Return` whose `results` is a JoinResult. This `JoinResult` - # is relayed from the joined object's host, possibly with transformation applied as needed - # by the network. - # - # Like any return, the result must be released using a `Finish`. However, this release - # should not occur until the joiner has either successfully connected to the joined object. - # Vats relaying a `Join` message similarly must not release the result they receive until the - # return they relayed back towards the joiner has itself been released. This allows the - # joined object's host to detect when the Join operation is canceled before completing -- if - # it receives a `Finish` for one of the join results before the joiner successfully - # connects. It can then free any resources it had allocated as part of the join. - - target @1 :MessageTarget; - # The capability to join. - - keyPart @2 :JoinKeyPart; - # A part of the join key. These combine to form the complete join key, which is used to establish - # a direct connection. - - # TODO(before implementing): Change this so that multiple parts can be sent in a single Join - # message, so that if multiple join parts are going to cross the same connection they can be sent - # together, so that the receive can potentially optimize its handling of them. In the case where - # all parts are bundled together, should the recipient be expected to simply return a cap, so - # that the caller can immediately start pipelining to it? -} - -# ======================================================================================== -# Common structures used in messages - -struct MessageTarget { - # The target of a `Call` or other messages that target a capability. - - union { - importedCap @0 :ImportId; - # This message is to a capability or promise previously imported by the caller (exported by - # the receiver). - - promisedAnswer @1 :PromisedAnswer; - # This message is to a capability that is expected to be returned by another call that has not - # yet been completed. - # - # At level 0, this is supported only for addressing the result of a previous `Bootstrap`, so - # that initial startup doesn't require a round trip. - } -} - -struct Payload { - # Represents some data structure that might contain capabilities. - - content @0 :AnyPointer; - # Some Cap'n Proto data structure. Capability pointers embedded in this structure index into - # `capTable`. - - capTable @1 :List(CapDescriptor); - # Descriptors corresponding to the cap pointers in `content`. -} - -struct CapDescriptor { - # **(level 1)** - # - # When an application-defined type contains an interface pointer, that pointer contains an index - # into the message's capability table -- i.e. the `capTable` part of the `Payload`. Each - # capability in the table is represented as a `CapDescriptor`. The runtime API should not reveal - # the CapDescriptor directly to the application, but should instead wrap it in some kind of - # callable object with methods corresponding to the interface that the capability implements. - # - # Keep in mind that `ExportIds` in a `CapDescriptor` are subject to reference counting. See the - # description of `ExportId`. - - union { - none @0 :Void; - # There is no capability here. This `CapDescriptor` should not appear in the payload content. - # A `none` CapDescriptor can be generated when an application inserts a capability into a - # message and then later changes its mind and removes it -- rewriting all of the other - # capability pointers may be hard, so instead a tombstone is left, similar to the way a removed - # struct or list instance is zeroed out of the message but the space is not reclaimed. - # Hopefully this is unusual. - - senderHosted @1 :ExportId; - # A capability newly exported by the sender. This is the ID of the new capability in the - # sender's export table (receiver's import table). - - senderPromise @2 :ExportId; - # A promise that the sender will resolve later. The sender will send exactly one Resolve - # message at a future point in time to replace this promise. Note that even if the same - # `senderPromise` is received multiple times, only one `Resolve` is sent to cover all of - # them. If `senderPromise` is released before the `Resolve` is sent, the sender (of this - # `CapDescriptor`) may choose not to send the `Resolve` at all. - - receiverHosted @3 :ImportId; - # A capability (or promise) previously exported by the receiver (imported by the sender). - - receiverAnswer @4 :PromisedAnswer; - # A capability expected to be returned in the results of a currently-outstanding call posed - # by the sender. - - thirdPartyHosted @5 :ThirdPartyCapDescriptor; - # **(level 3)** - # - # A capability that lives in neither the sender's nor the receiver's vat. The sender needs - # to form a direct connection to a third party to pick up the capability. - # - # Level 1 and 2 implementations that receive a `thirdPartyHosted` may simply send calls to its - # `vine` instead. - } -} - -struct PromisedAnswer { - # **(mostly level 1)** - # - # Specifies how to derive a promise from an unanswered question, by specifying the path of fields - # to follow from the root of the eventual result struct to get to the desired capability. Used - # to address method calls to a not-yet-returned capability or to pass such a capability as an - # input to some other method call. - # - # Level 0 implementations must support `PromisedAnswer` only for the case where the answer is - # to a `Bootstrap` message. In this case, `path` is always empty since `Bootstrap` always returns - # a raw capability. - - questionId @0 :QuestionId; - # ID of the question (in the sender's question table / receiver's answer table) whose answer is - # expected to contain the capability. - - transform @1 :List(Op); - # Operations / transformations to apply to the result in order to get the capability actually - # being addressed. E.g. if the result is a struct and you want to call a method on a capability - # pointed to by a field of the struct, you need a `getPointerField` op. - - struct Op { - union { - noop @0 :Void; - # Does nothing. This member is mostly defined so that we can make `Op` a union even - # though (as of this writing) only one real operation is defined. - - getPointerField @1 :UInt16; - # Get a pointer field within a struct. The number is an index into the pointer section, NOT - # a field ordinal, so that the receiver does not need to understand the schema. - - # TODO(someday): We could add: - # - For lists, the ability to address every member of the list, or a slice of the list, the - # result of which would be another list. This is useful for implementing the equivalent of - # a SQL table join (not to be confused with the `Join` message type). - # - Maybe some ability to test a union. - # - Probably not a good idea: the ability to specify an arbitrary script to run on the - # result. We could define a little stack-based language where `Op` specifies one - # "instruction" or transformation to apply. Although this is not a good idea - # (over-engineered), any narrower additions to `Op` should be designed as if this - # were the eventual goal. - } - } -} - -struct ThirdPartyCapDescriptor { - # **(level 3)** - # - # Identifies a capability in a third-party vat that the sender wants the receiver to pick up. - - id @0 :ThirdPartyCapId; - # Identifies the third-party host and the specific capability to accept from it. - - vineId @1 :ExportId; - # A proxy for the third-party object exported by the sender. In CapTP terminology this is called - # a "vine", because it is an indirect reference to the third-party object that snakes through the - # sender vat. This serves two purposes: - # - # * Level 1 and 2 implementations that don't understand how to connect to a third party may - # simply send calls to the vine. Such calls will be forwarded to the third-party by the - # sender. - # - # * Level 3 implementations must release the vine once they have successfully picked up the - # object from the third party. This ensures that the capability is not released by the sender - # prematurely. - # - # The sender will close the `Provide` request that it has sent to the third party as soon as - # it receives either a `Call` or a `Release` message directed at the vine. -} - -struct Exception { - # **(level 0)** - # - # Describes an arbitrary error that prevented an operation (e.g. a call) from completing. - # - # Cap'n Proto exceptions always indicate that something went wrong. In other words, in a fantasy - # world where everything always works as expected, no exceptions would ever be thrown. Clients - # should only ever catch exceptions as a means to implement fault-tolerance, where "fault" can - # mean: - # - Bugs. - # - Invalid input. - # - Configuration errors. - # - Network problems. - # - Insufficient resources. - # - Version skew (unimplemented functionality). - # - Other logistical problems. - # - # Exceptions should NOT be used to flag application-specific conditions that a client is expected - # to handle in an application-specific way. Put another way, in the Cap'n Proto world, - # "checked exceptions" (where an interface explicitly defines the exceptions it throws and - # clients are forced by the type system to handle those exceptions) do NOT make sense. - - reason @0 :Text; - # Human-readable failure description. - - type @3 :Type; - # The type of the error. The purpose of this enum is not to describe the error itself, but - # rather to describe how the client might want to respond to the error. - - enum Type { - failed @0; - # A generic problem occurred, and it is believed that if the operation were repeated without - # any change in the state of the world, the problem would occur again. - # - # A client might respond to this error by logging it for investigation by the developer and/or - # displaying it to the user. - - overloaded @1; - # The request was rejected due to a temporary lack of resources. - # - # Examples include: - # - There's not enough CPU time to keep up with incoming requests, so some are rejected. - # - The server ran out of RAM or disk space during the request. - # - The operation timed out (took significantly longer than it should have). - # - # A client might respond to this error by scheduling to retry the operation much later. The - # client should NOT retry again immediately since this would likely exacerbate the problem. - - disconnected @2; - # The method failed because a connection to some necessary capability was lost. - # - # Examples include: - # - The client introduced the server to a third-party capability, the connection to that third - # party was subsequently lost, and then the client requested that the server use the dead - # capability for something. - # - The client previously requested that the server obtain a capability from some third party. - # The server returned a capability to an object wrapping the third-party capability. Later, - # the server's connection to the third party was lost. - # - The capability has been revoked. Revocation does not necessarily mean that the client is - # no longer authorized to use the capability; it is often used simply as a way to force the - # client to repeat the setup process, perhaps to efficiently move them to a new back-end or - # get them to recognize some other change that has occurred. - # - # A client should normally respond to this error by releasing all capabilities it is currently - # holding related to the one it called and then re-creating them by restoring SturdyRefs and/or - # repeating the method calls used to create them originally. In other words, disconnect and - # start over. This should in turn cause the server to obtain a new copy of the capability that - # it lost, thus making everything work. - # - # If the client receives another `disconnencted` error in the process of rebuilding the - # capability and retrying the call, it should treat this as an `overloaded` error: the network - # is currently unreliable, possibly due to load or other temporary issues. - - unimplemented @3; - # The server doesn't implement the requested method. If there is some other method that the - # client could call (perhaps an older and/or slower interface), it should try that instead. - # Otherwise, this should be treated like `failed`. - } - - obsoleteIsCallersFault @1 :Bool; - # OBSOLETE. Ignore. - - obsoleteDurability @2 :UInt16; - # OBSOLETE. See `type` instead. -} - -# ======================================================================================== -# Network-specific Parameters -# -# Some parts of the Cap'n Proto RPC protocol are not specified here because different vat networks -# may wish to use different approaches to solving them. For example, on the public internet, you -# may want to authenticate vats using public-key cryptography, but on a local intranet with trusted -# infrastructure, you may be happy to authenticate based on network address only, or some other -# lightweight mechanism. -# -# To accommodate this, we specify several "parameter" types. Each type is defined here as an -# alias for `AnyPointer`, but a specific network will want to define a specific set of types to use. -# All vats in a vat network must agree on these parameters in order to be able to communicate. -# Inter-network communication can be accomplished through "gateways" that perform translation -# between the primitives used on each network; these gateways may need to be deeply stateful, -# depending on the translations they perform. -# -# For interaction over the global internet between parties with no other prior arrangement, a -# particular set of bindings for these types is defined elsewhere. (TODO(someday): Specify where -# these common definitions live.) -# -# Another common network type is the two-party network, in which one of the parties typically -# interacts with the outside world entirely through the other party. In such a connection between -# Alice and Bob, all objects that exist on Bob's other networks appear to Alice as if they were -# hosted by Bob himself, and similarly all objects on Alice's network (if she even has one) appear -# to Bob as if they were hosted by Alice. This network type is interesting because from the point -# of view of a simple application that communicates with only one other party via the two-party -# protocol, there are no three-party interactions at all, and joins are unusually simple to -# implement, so implementing at level 4 is barely more complicated than implementing at level 1. -# Moreover, if you pair an app implementing the two-party network with a container that implements -# some other network, the app can then participate on the container's network just as if it -# implemented that network directly. The types used by the two-party network are defined in -# `rpc-twoparty.capnp`. -# -# The things that we need to parameterize are: -# - How to store capabilities long-term without holding a connection open (mostly level 2). -# - How to authenticate vats in three-party introductions (level 3). -# - How to implement `Join` (level 4). -# -# Persistent references -# --------------------- -# -# **(mostly level 2)** -# -# We want to allow some capabilities to be stored long-term, even if a connection is lost and later -# recreated. ExportId is a short-term identifier that is specific to a connection, so it doesn't -# help here. We need a way to specify long-term identifiers, as well as a strategy for -# reconnecting to a referenced capability later. -# -# Three-party interactions -# ------------------------ -# -# **(level 3)** -# -# In cases where more than two vats are interacting, we have situations where VatA holds a -# capability hosted by VatB and wants to send that capability to VatC. This can be accomplished -# by VatA proxying requests on the new capability, but doing so has two big problems: -# - It's inefficient, requiring an extra network hop. -# - If VatC receives another capability to the same object from VatD, it is difficult for VatC to -# detect that the two capabilities are really the same and to implement the E "join" operation, -# which is necessary for certain four-or-more-party interactions, such as the escrow pattern. -# See: http://www.erights.org/elib/equality/grant-matcher/index.html -# -# Instead, we want a way for VatC to form a direct, authenticated connection to VatB. -# -# Join -# ---- -# -# **(level 4)** -# -# The `Join` message type and corresponding operation arranges for a direct connection to be formed -# between the joiner and the host of the joined object, and this connection must be authenticated. -# Thus, the details are network-dependent. - -using SturdyRef = AnyPointer; -# **(level 2)** -# -# Identifies a persisted capability that can be restored in the future. How exactly a SturdyRef -# is restored to a live object is specified along with the SturdyRef definition (i.e. not by -# rpc.capnp). -# -# Generally a SturdyRef needs to specify three things: -# - How to reach the vat that can restore the ref (e.g. a hostname or IP address). -# - How to authenticate the vat after connecting (e.g. a public key fingerprint). -# - The identity of a specific object hosted by the vat. Generally, this is an opaque pointer whose -# format is defined by the specific vat -- the client has no need to inspect the object ID. -# It is important that the objec ID be unguessable if the object is not public (and objects -# should almost never be public). -# -# The above are only suggestions. Some networks might work differently. For example, a private -# network might employ a special restorer service whose sole purpose is to restore SturdyRefs. -# In this case, the entire contents of SturdyRef might be opaque, because they are intended only -# to be forwarded to the restorer service. - -using ProvisionId = AnyPointer; -# **(level 3)** -# -# The information that must be sent in an `Accept` message to identify the object being accepted. -# -# In a network where each vat has a public/private key pair, this could simply be the public key -# fingerprint of the provider vat along with the question ID used in the `Provide` message sent from -# that provider. - -using RecipientId = AnyPointer; -# **(level 3)** -# -# The information that must be sent in a `Provide` message to identify the recipient of the -# capability. -# -# In a network where each vat has a public/private key pair, this could simply be the public key -# fingerprint of the recipient. (CapTP also calls for a nonce to identify the object. In our -# case, the `Provide` message's `questionId` can serve as the nonce.) - -using ThirdPartyCapId = AnyPointer; -# **(level 3)** -# -# The information needed to connect to a third party and accept a capability from it. -# -# In a network where each vat has a public/private key pair, this could be a combination of the -# third party's public key fingerprint, hints on how to connect to the third party (e.g. an IP -# address), and the question ID used in the corresponding `Provide` message sent to that third party -# (used to identify which capability to pick up). - -using JoinKeyPart = AnyPointer; -# **(level 4)** -# -# A piece of a secret key. One piece is sent along each path that is expected to lead to the same -# place. Once the pieces are combined, a direct connection may be formed between the sender and -# the receiver, bypassing any men-in-the-middle along the paths. See the `Join` message type. -# -# The motivation for Joins is discussed under "Supporting Equality" in the "Unibus" protocol -# sketch: http://www.erights.org/elib/distrib/captp/unibus.html -# -# In a network where each vat has a public/private key pair and each vat forms no more than one -# connection to each other vat, Joins will rarely -- perhaps never -- be needed, as objects never -# need to be transparently proxied and references to the same object sent over the same connection -# have the same export ID. Thus, a successful join requires only checking that the two objects -# come from the same connection and have the same ID, and then completes immediately. -# -# However, in networks where two vats may form more than one connection between each other, or -# where proxying of objects occurs, joins are necessary. -# -# Typically, each JoinKeyPart would include a fixed-length data value such that all value parts -# XOR'd together forms a shared secret that can be used to form an encrypted connection between -# the joiner and the joined object's host. Each JoinKeyPart should also include an indication of -# how many parts to expect and a hash of the shared secret (used to match up parts). - -using JoinResult = AnyPointer; -# **(level 4)** -# -# Information returned as the result to a `Join` message, needed by the joiner in order to form a -# direct connection to a joined object. This might simply be the address of the joined object's -# host vat, since the `JoinKey` has already been communicated so the two vats already have a shared -# secret to use to authenticate each other. -# -# The `JoinResult` should also contain information that can be used to detect when the Join -# requests ended up reaching different objects, so that this situation can be detected easily. -# This could be a simple matter of including a sequence number -- if the joiner receives two -# `JoinResult`s with sequence number 0, then they must have come from different objects and the -# whole join is a failure. - -# ======================================================================================== -# Network interface sketch -# -# The interfaces below are meant to be pseudo-code to illustrate how the details of a particular -# vat network might be abstracted away. They are written like Cap'n Proto interfaces, but in -# practice you'd probably define these interfaces manually in the target programming language. A -# Cap'n Proto RPC implementation should be able to use these interfaces without knowing the -# definitions of the various network-specific parameters defined above. - -# interface VatNetwork { -# # Represents a vat network, with the ability to connect to particular vats and receive -# # connections from vats. -# # -# # Note that methods returning a `Connection` may return a pre-existing `Connection`, and the -# # caller is expected to find and share state with existing users of the connection. -# -# # Level 0 features ----------------------------------------------- -# -# connect(vatId :VatId) :Connection; -# # Connect to the given vat. The transport should return a promise that does not -# # resolve until authentication has completed, but allows messages to be pipelined in before -# # that; the transport either queues these messages until authenticated, or sends them encrypted -# # such that only the authentic vat would be able to decrypt them. The latter approach avoids a -# # round trip for authentication. -# -# accept() :Connection; -# # Wait for the next incoming connection and return it. Only connections formed by -# # connect() are returned by this method. -# -# # Level 4 features ----------------------------------------------- -# -# newJoiner(count :UInt32) :NewJoinerResponse; -# # Prepare a new Join operation, which will eventually lead to forming a new direct connection -# # to the host of the joined capability. `count` is the number of capabilities to join. -# -# struct NewJoinerResponse { -# joinKeyParts :List(JoinKeyPart); -# # Key parts to send in Join messages to each capability. -# -# joiner :Joiner; -# # Used to establish the final connection. -# } -# -# interface Joiner { -# addJoinResult(result :JoinResult) :Void; -# # Add a JoinResult received in response to one of the `Join` messages. All `JoinResult`s -# # returned from all paths must be added before trying to connect. -# -# connect() :ConnectionAndProvisionId; -# # Try to form a connection to the joined capability's host, verifying that it has received -# # all of the JoinKeyParts. Once the connection is formed, the caller should send an `Accept` -# # message on it with the specified `ProvisionId` in order to receive the final capability. -# } -# -# acceptConnectionFromJoiner(parts :List(JoinKeyPart), paths :List(VatPath)) -# :ConnectionAndProvisionId; -# # Called on a joined capability's host to receive the connection from the joiner, once all -# # key parts have arrived. The caller should expect to receive an `Accept` message over the -# # connection with the given ProvisionId. -# } -# -# interface Connection { -# # Level 0 features ----------------------------------------------- -# -# send(message :Message) :Void; -# # Send the message. Returns successfully when the message (and all preceding messages) has -# # been acknowledged by the recipient. -# -# receive() :Message; -# # Receive the next message, and acknowledges receipt to the sender. Messages are received in -# # the order in which they are sent. -# -# # Level 3 features ----------------------------------------------- -# -# introduceTo(recipient :Connection) :IntroductionInfo; -# # Call before starting a three-way introduction, assuming a `Provide` message is to be sent on -# # this connection and a `ThirdPartyCapId` is to be sent to `recipient`. -# -# struct IntroductionInfo { -# sendToRecipient :ThirdPartyCapId; -# sendToTarget :RecipientId; -# } -# -# connectToIntroduced(capId :ThirdPartyCapId) :ConnectionAndProvisionId; -# # Given a ThirdPartyCapId received over this connection, connect to the third party. The -# # caller should then send an `Accept` message over the new connection. -# -# acceptIntroducedConnection(recipientId :RecipientId) :Connection; -# # Given a RecipientId received in a `Provide` message on this `Connection`, wait for the -# # recipient to connect, and return the connection formed. Usually, the first message received -# # on the new connection will be an `Accept` message. -# } -# -# struct ConnectionAndProvisionId { -# # **(level 3)** -# -# connection :Connection; -# # Connection on which to issue `Accept` message. -# -# provision :ProvisionId; -# # `ProvisionId` to send in the `Accept` message. -# } diff --git a/phonelibs/capnp-cpp/include/capnp/rpc.capnp.h b/phonelibs/capnp-cpp/include/capnp/rpc.capnp.h deleted file mode 100644 index 0a440397fc..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/rpc.capnp.h +++ /dev/null @@ -1,4898 +0,0 @@ -// Generated by Cap'n Proto compiler, DO NOT EDIT -// source: rpc.capnp - -#ifndef CAPNP_INCLUDED_b312981b2552a250_ -#define CAPNP_INCLUDED_b312981b2552a250_ - -#include - -#if CAPNP_VERSION != 6001 -#error "Version mismatch between generated code and library headers. You must use the same version of the Cap'n Proto compiler and library." -#endif - - -namespace capnp { -namespace schemas { - -CAPNP_DECLARE_SCHEMA(91b79f1f808db032); -CAPNP_DECLARE_SCHEMA(e94ccf8031176ec4); -CAPNP_DECLARE_SCHEMA(836a53ce789d4cd4); -CAPNP_DECLARE_SCHEMA(dae8b0f61aab5f99); -CAPNP_DECLARE_SCHEMA(9e19b28d3db3573a); -CAPNP_DECLARE_SCHEMA(d37d2eb2c2f80e63); -CAPNP_DECLARE_SCHEMA(bbc29655fa89086e); -CAPNP_DECLARE_SCHEMA(ad1a6c0d7dd07497); -CAPNP_DECLARE_SCHEMA(f964368b0fbd3711); -CAPNP_DECLARE_SCHEMA(d562b4df655bdd4d); -CAPNP_DECLARE_SCHEMA(9c6a046bfbc1ac5a); -CAPNP_DECLARE_SCHEMA(d4c9b56290554016); -CAPNP_DECLARE_SCHEMA(fbe1980490e001af); -CAPNP_DECLARE_SCHEMA(95bc14545813fbc1); -CAPNP_DECLARE_SCHEMA(9a0e61223d96743b); -CAPNP_DECLARE_SCHEMA(8523ddc40b86b8b0); -CAPNP_DECLARE_SCHEMA(d800b1d6cd6f1ca0); -CAPNP_DECLARE_SCHEMA(f316944415569081); -CAPNP_DECLARE_SCHEMA(d37007fde1f0027d); -CAPNP_DECLARE_SCHEMA(d625b7063acf691a); -CAPNP_DECLARE_SCHEMA(b28c96e23f4cbd58); -enum class Type_b28c96e23f4cbd58: uint16_t { - FAILED, - OVERLOADED, - DISCONNECTED, - UNIMPLEMENTED, -}; -CAPNP_DECLARE_ENUM(Type, b28c96e23f4cbd58); - -} // namespace schemas -} // namespace capnp - -namespace capnp { -namespace rpc { - -struct Message { - Message() = delete; - - class Reader; - class Builder; - class Pipeline; - enum Which: uint16_t { - UNIMPLEMENTED, - ABORT, - CALL, - RETURN, - FINISH, - RESOLVE, - RELEASE, - OBSOLETE_SAVE, - BOOTSTRAP, - OBSOLETE_DELETE, - PROVIDE, - ACCEPT, - JOIN, - DISEMBARGO, - }; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(91b79f1f808db032, 1, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Bootstrap { - Bootstrap() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(e94ccf8031176ec4, 1, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Call { - Call() = delete; - - class Reader; - class Builder; - class Pipeline; - struct SendResultsTo; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(836a53ce789d4cd4, 3, 3) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Call::SendResultsTo { - SendResultsTo() = delete; - - class Reader; - class Builder; - class Pipeline; - enum Which: uint16_t { - CALLER, - YOURSELF, - THIRD_PARTY, - }; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(dae8b0f61aab5f99, 3, 3) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Return { - Return() = delete; - - class Reader; - class Builder; - class Pipeline; - enum Which: uint16_t { - RESULTS, - EXCEPTION, - CANCELED, - RESULTS_SENT_ELSEWHERE, - TAKE_FROM_OTHER_QUESTION, - ACCEPT_FROM_THIRD_PARTY, - }; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(9e19b28d3db3573a, 2, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Finish { - Finish() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(d37d2eb2c2f80e63, 1, 0) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Resolve { - Resolve() = delete; - - class Reader; - class Builder; - class Pipeline; - enum Which: uint16_t { - CAP, - EXCEPTION, - }; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(bbc29655fa89086e, 1, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Release { - Release() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(ad1a6c0d7dd07497, 1, 0) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Disembargo { - Disembargo() = delete; - - class Reader; - class Builder; - class Pipeline; - struct Context; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(f964368b0fbd3711, 1, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Disembargo::Context { - Context() = delete; - - class Reader; - class Builder; - class Pipeline; - enum Which: uint16_t { - SENDER_LOOPBACK, - RECEIVER_LOOPBACK, - ACCEPT, - PROVIDE, - }; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(d562b4df655bdd4d, 1, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Provide { - Provide() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(9c6a046bfbc1ac5a, 1, 2) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Accept { - Accept() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(d4c9b56290554016, 1, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Join { - Join() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(fbe1980490e001af, 1, 2) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct MessageTarget { - MessageTarget() = delete; - - class Reader; - class Builder; - class Pipeline; - enum Which: uint16_t { - IMPORTED_CAP, - PROMISED_ANSWER, - }; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(95bc14545813fbc1, 1, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Payload { - Payload() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(9a0e61223d96743b, 0, 2) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct CapDescriptor { - CapDescriptor() = delete; - - class Reader; - class Builder; - class Pipeline; - enum Which: uint16_t { - NONE, - SENDER_HOSTED, - SENDER_PROMISE, - RECEIVER_HOSTED, - RECEIVER_ANSWER, - THIRD_PARTY_HOSTED, - }; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(8523ddc40b86b8b0, 1, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct PromisedAnswer { - PromisedAnswer() = delete; - - class Reader; - class Builder; - class Pipeline; - struct Op; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(d800b1d6cd6f1ca0, 1, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct PromisedAnswer::Op { - Op() = delete; - - class Reader; - class Builder; - class Pipeline; - enum Which: uint16_t { - NOOP, - GET_POINTER_FIELD, - }; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(f316944415569081, 1, 0) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct ThirdPartyCapDescriptor { - ThirdPartyCapDescriptor() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(d37007fde1f0027d, 1, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Exception { - Exception() = delete; - - class Reader; - class Builder; - class Pipeline; - typedef ::capnp::schemas::Type_b28c96e23f4cbd58 Type; - - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(d625b7063acf691a, 1, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -// ======================================================================================= - -class Message::Reader { -public: - typedef Message Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline Which which() const; - inline bool isUnimplemented() const; - inline bool hasUnimplemented() const; - inline ::capnp::rpc::Message::Reader getUnimplemented() const; - - inline bool isAbort() const; - inline bool hasAbort() const; - inline ::capnp::rpc::Exception::Reader getAbort() const; - - inline bool isCall() const; - inline bool hasCall() const; - inline ::capnp::rpc::Call::Reader getCall() const; - - inline bool isReturn() const; - inline bool hasReturn() const; - inline ::capnp::rpc::Return::Reader getReturn() const; - - inline bool isFinish() const; - inline bool hasFinish() const; - inline ::capnp::rpc::Finish::Reader getFinish() const; - - inline bool isResolve() const; - inline bool hasResolve() const; - inline ::capnp::rpc::Resolve::Reader getResolve() const; - - inline bool isRelease() const; - inline bool hasRelease() const; - inline ::capnp::rpc::Release::Reader getRelease() const; - - inline bool isObsoleteSave() const; - inline bool hasObsoleteSave() const; - inline ::capnp::AnyPointer::Reader getObsoleteSave() const; - - inline bool isBootstrap() const; - inline bool hasBootstrap() const; - inline ::capnp::rpc::Bootstrap::Reader getBootstrap() const; - - inline bool isObsoleteDelete() const; - inline bool hasObsoleteDelete() const; - inline ::capnp::AnyPointer::Reader getObsoleteDelete() const; - - inline bool isProvide() const; - inline bool hasProvide() const; - inline ::capnp::rpc::Provide::Reader getProvide() const; - - inline bool isAccept() const; - inline bool hasAccept() const; - inline ::capnp::rpc::Accept::Reader getAccept() const; - - inline bool isJoin() const; - inline bool hasJoin() const; - inline ::capnp::rpc::Join::Reader getJoin() const; - - inline bool isDisembargo() const; - inline bool hasDisembargo() const; - inline ::capnp::rpc::Disembargo::Reader getDisembargo() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Message::Builder { -public: - typedef Message Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline Which which(); - inline bool isUnimplemented(); - inline bool hasUnimplemented(); - inline ::capnp::rpc::Message::Builder getUnimplemented(); - inline void setUnimplemented( ::capnp::rpc::Message::Reader value); - inline ::capnp::rpc::Message::Builder initUnimplemented(); - inline void adoptUnimplemented(::capnp::Orphan< ::capnp::rpc::Message>&& value); - inline ::capnp::Orphan< ::capnp::rpc::Message> disownUnimplemented(); - - inline bool isAbort(); - inline bool hasAbort(); - inline ::capnp::rpc::Exception::Builder getAbort(); - inline void setAbort( ::capnp::rpc::Exception::Reader value); - inline ::capnp::rpc::Exception::Builder initAbort(); - inline void adoptAbort(::capnp::Orphan< ::capnp::rpc::Exception>&& value); - inline ::capnp::Orphan< ::capnp::rpc::Exception> disownAbort(); - - inline bool isCall(); - inline bool hasCall(); - inline ::capnp::rpc::Call::Builder getCall(); - inline void setCall( ::capnp::rpc::Call::Reader value); - inline ::capnp::rpc::Call::Builder initCall(); - inline void adoptCall(::capnp::Orphan< ::capnp::rpc::Call>&& value); - inline ::capnp::Orphan< ::capnp::rpc::Call> disownCall(); - - inline bool isReturn(); - inline bool hasReturn(); - inline ::capnp::rpc::Return::Builder getReturn(); - inline void setReturn( ::capnp::rpc::Return::Reader value); - inline ::capnp::rpc::Return::Builder initReturn(); - inline void adoptReturn(::capnp::Orphan< ::capnp::rpc::Return>&& value); - inline ::capnp::Orphan< ::capnp::rpc::Return> disownReturn(); - - inline bool isFinish(); - inline bool hasFinish(); - inline ::capnp::rpc::Finish::Builder getFinish(); - inline void setFinish( ::capnp::rpc::Finish::Reader value); - inline ::capnp::rpc::Finish::Builder initFinish(); - inline void adoptFinish(::capnp::Orphan< ::capnp::rpc::Finish>&& value); - inline ::capnp::Orphan< ::capnp::rpc::Finish> disownFinish(); - - inline bool isResolve(); - inline bool hasResolve(); - inline ::capnp::rpc::Resolve::Builder getResolve(); - inline void setResolve( ::capnp::rpc::Resolve::Reader value); - inline ::capnp::rpc::Resolve::Builder initResolve(); - inline void adoptResolve(::capnp::Orphan< ::capnp::rpc::Resolve>&& value); - inline ::capnp::Orphan< ::capnp::rpc::Resolve> disownResolve(); - - inline bool isRelease(); - inline bool hasRelease(); - inline ::capnp::rpc::Release::Builder getRelease(); - inline void setRelease( ::capnp::rpc::Release::Reader value); - inline ::capnp::rpc::Release::Builder initRelease(); - inline void adoptRelease(::capnp::Orphan< ::capnp::rpc::Release>&& value); - inline ::capnp::Orphan< ::capnp::rpc::Release> disownRelease(); - - inline bool isObsoleteSave(); - inline bool hasObsoleteSave(); - inline ::capnp::AnyPointer::Builder getObsoleteSave(); - inline ::capnp::AnyPointer::Builder initObsoleteSave(); - - inline bool isBootstrap(); - inline bool hasBootstrap(); - inline ::capnp::rpc::Bootstrap::Builder getBootstrap(); - inline void setBootstrap( ::capnp::rpc::Bootstrap::Reader value); - inline ::capnp::rpc::Bootstrap::Builder initBootstrap(); - inline void adoptBootstrap(::capnp::Orphan< ::capnp::rpc::Bootstrap>&& value); - inline ::capnp::Orphan< ::capnp::rpc::Bootstrap> disownBootstrap(); - - inline bool isObsoleteDelete(); - inline bool hasObsoleteDelete(); - inline ::capnp::AnyPointer::Builder getObsoleteDelete(); - inline ::capnp::AnyPointer::Builder initObsoleteDelete(); - - inline bool isProvide(); - inline bool hasProvide(); - inline ::capnp::rpc::Provide::Builder getProvide(); - inline void setProvide( ::capnp::rpc::Provide::Reader value); - inline ::capnp::rpc::Provide::Builder initProvide(); - inline void adoptProvide(::capnp::Orphan< ::capnp::rpc::Provide>&& value); - inline ::capnp::Orphan< ::capnp::rpc::Provide> disownProvide(); - - inline bool isAccept(); - inline bool hasAccept(); - inline ::capnp::rpc::Accept::Builder getAccept(); - inline void setAccept( ::capnp::rpc::Accept::Reader value); - inline ::capnp::rpc::Accept::Builder initAccept(); - inline void adoptAccept(::capnp::Orphan< ::capnp::rpc::Accept>&& value); - inline ::capnp::Orphan< ::capnp::rpc::Accept> disownAccept(); - - inline bool isJoin(); - inline bool hasJoin(); - inline ::capnp::rpc::Join::Builder getJoin(); - inline void setJoin( ::capnp::rpc::Join::Reader value); - inline ::capnp::rpc::Join::Builder initJoin(); - inline void adoptJoin(::capnp::Orphan< ::capnp::rpc::Join>&& value); - inline ::capnp::Orphan< ::capnp::rpc::Join> disownJoin(); - - inline bool isDisembargo(); - inline bool hasDisembargo(); - inline ::capnp::rpc::Disembargo::Builder getDisembargo(); - inline void setDisembargo( ::capnp::rpc::Disembargo::Reader value); - inline ::capnp::rpc::Disembargo::Builder initDisembargo(); - inline void adoptDisembargo(::capnp::Orphan< ::capnp::rpc::Disembargo>&& value); - inline ::capnp::Orphan< ::capnp::rpc::Disembargo> disownDisembargo(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Message::Pipeline { -public: - typedef Message Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Bootstrap::Reader { -public: - typedef Bootstrap Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint32_t getQuestionId() const; - - inline bool hasDeprecatedObjectId() const; - inline ::capnp::AnyPointer::Reader getDeprecatedObjectId() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Bootstrap::Builder { -public: - typedef Bootstrap Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint32_t getQuestionId(); - inline void setQuestionId( ::uint32_t value); - - inline bool hasDeprecatedObjectId(); - inline ::capnp::AnyPointer::Builder getDeprecatedObjectId(); - inline ::capnp::AnyPointer::Builder initDeprecatedObjectId(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Bootstrap::Pipeline { -public: - typedef Bootstrap Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Call::Reader { -public: - typedef Call Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint32_t getQuestionId() const; - - inline bool hasTarget() const; - inline ::capnp::rpc::MessageTarget::Reader getTarget() const; - - inline ::uint64_t getInterfaceId() const; - - inline ::uint16_t getMethodId() const; - - inline bool hasParams() const; - inline ::capnp::rpc::Payload::Reader getParams() const; - - inline typename SendResultsTo::Reader getSendResultsTo() const; - - inline bool getAllowThirdPartyTailCall() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Call::Builder { -public: - typedef Call Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint32_t getQuestionId(); - inline void setQuestionId( ::uint32_t value); - - inline bool hasTarget(); - inline ::capnp::rpc::MessageTarget::Builder getTarget(); - inline void setTarget( ::capnp::rpc::MessageTarget::Reader value); - inline ::capnp::rpc::MessageTarget::Builder initTarget(); - inline void adoptTarget(::capnp::Orphan< ::capnp::rpc::MessageTarget>&& value); - inline ::capnp::Orphan< ::capnp::rpc::MessageTarget> disownTarget(); - - inline ::uint64_t getInterfaceId(); - inline void setInterfaceId( ::uint64_t value); - - inline ::uint16_t getMethodId(); - inline void setMethodId( ::uint16_t value); - - inline bool hasParams(); - inline ::capnp::rpc::Payload::Builder getParams(); - inline void setParams( ::capnp::rpc::Payload::Reader value); - inline ::capnp::rpc::Payload::Builder initParams(); - inline void adoptParams(::capnp::Orphan< ::capnp::rpc::Payload>&& value); - inline ::capnp::Orphan< ::capnp::rpc::Payload> disownParams(); - - inline typename SendResultsTo::Builder getSendResultsTo(); - inline typename SendResultsTo::Builder initSendResultsTo(); - - inline bool getAllowThirdPartyTailCall(); - inline void setAllowThirdPartyTailCall(bool value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Call::Pipeline { -public: - typedef Call Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline ::capnp::rpc::MessageTarget::Pipeline getTarget(); - inline ::capnp::rpc::Payload::Pipeline getParams(); - inline typename SendResultsTo::Pipeline getSendResultsTo(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Call::SendResultsTo::Reader { -public: - typedef SendResultsTo Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline Which which() const; - inline bool isCaller() const; - inline ::capnp::Void getCaller() const; - - inline bool isYourself() const; - inline ::capnp::Void getYourself() const; - - inline bool isThirdParty() const; - inline bool hasThirdParty() const; - inline ::capnp::AnyPointer::Reader getThirdParty() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Call::SendResultsTo::Builder { -public: - typedef SendResultsTo Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline Which which(); - inline bool isCaller(); - inline ::capnp::Void getCaller(); - inline void setCaller( ::capnp::Void value = ::capnp::VOID); - - inline bool isYourself(); - inline ::capnp::Void getYourself(); - inline void setYourself( ::capnp::Void value = ::capnp::VOID); - - inline bool isThirdParty(); - inline bool hasThirdParty(); - inline ::capnp::AnyPointer::Builder getThirdParty(); - inline ::capnp::AnyPointer::Builder initThirdParty(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Call::SendResultsTo::Pipeline { -public: - typedef SendResultsTo Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Return::Reader { -public: - typedef Return Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline Which which() const; - inline ::uint32_t getAnswerId() const; - - inline bool getReleaseParamCaps() const; - - inline bool isResults() const; - inline bool hasResults() const; - inline ::capnp::rpc::Payload::Reader getResults() const; - - inline bool isException() const; - inline bool hasException() const; - inline ::capnp::rpc::Exception::Reader getException() const; - - inline bool isCanceled() const; - inline ::capnp::Void getCanceled() const; - - inline bool isResultsSentElsewhere() const; - inline ::capnp::Void getResultsSentElsewhere() const; - - inline bool isTakeFromOtherQuestion() const; - inline ::uint32_t getTakeFromOtherQuestion() const; - - inline bool isAcceptFromThirdParty() const; - inline bool hasAcceptFromThirdParty() const; - inline ::capnp::AnyPointer::Reader getAcceptFromThirdParty() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Return::Builder { -public: - typedef Return Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline Which which(); - inline ::uint32_t getAnswerId(); - inline void setAnswerId( ::uint32_t value); - - inline bool getReleaseParamCaps(); - inline void setReleaseParamCaps(bool value); - - inline bool isResults(); - inline bool hasResults(); - inline ::capnp::rpc::Payload::Builder getResults(); - inline void setResults( ::capnp::rpc::Payload::Reader value); - inline ::capnp::rpc::Payload::Builder initResults(); - inline void adoptResults(::capnp::Orphan< ::capnp::rpc::Payload>&& value); - inline ::capnp::Orphan< ::capnp::rpc::Payload> disownResults(); - - inline bool isException(); - inline bool hasException(); - inline ::capnp::rpc::Exception::Builder getException(); - inline void setException( ::capnp::rpc::Exception::Reader value); - inline ::capnp::rpc::Exception::Builder initException(); - inline void adoptException(::capnp::Orphan< ::capnp::rpc::Exception>&& value); - inline ::capnp::Orphan< ::capnp::rpc::Exception> disownException(); - - inline bool isCanceled(); - inline ::capnp::Void getCanceled(); - inline void setCanceled( ::capnp::Void value = ::capnp::VOID); - - inline bool isResultsSentElsewhere(); - inline ::capnp::Void getResultsSentElsewhere(); - inline void setResultsSentElsewhere( ::capnp::Void value = ::capnp::VOID); - - inline bool isTakeFromOtherQuestion(); - inline ::uint32_t getTakeFromOtherQuestion(); - inline void setTakeFromOtherQuestion( ::uint32_t value); - - inline bool isAcceptFromThirdParty(); - inline bool hasAcceptFromThirdParty(); - inline ::capnp::AnyPointer::Builder getAcceptFromThirdParty(); - inline ::capnp::AnyPointer::Builder initAcceptFromThirdParty(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Return::Pipeline { -public: - typedef Return Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Finish::Reader { -public: - typedef Finish Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint32_t getQuestionId() const; - - inline bool getReleaseResultCaps() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Finish::Builder { -public: - typedef Finish Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint32_t getQuestionId(); - inline void setQuestionId( ::uint32_t value); - - inline bool getReleaseResultCaps(); - inline void setReleaseResultCaps(bool value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Finish::Pipeline { -public: - typedef Finish Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Resolve::Reader { -public: - typedef Resolve Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline Which which() const; - inline ::uint32_t getPromiseId() const; - - inline bool isCap() const; - inline bool hasCap() const; - inline ::capnp::rpc::CapDescriptor::Reader getCap() const; - - inline bool isException() const; - inline bool hasException() const; - inline ::capnp::rpc::Exception::Reader getException() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Resolve::Builder { -public: - typedef Resolve Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline Which which(); - inline ::uint32_t getPromiseId(); - inline void setPromiseId( ::uint32_t value); - - inline bool isCap(); - inline bool hasCap(); - inline ::capnp::rpc::CapDescriptor::Builder getCap(); - inline void setCap( ::capnp::rpc::CapDescriptor::Reader value); - inline ::capnp::rpc::CapDescriptor::Builder initCap(); - inline void adoptCap(::capnp::Orphan< ::capnp::rpc::CapDescriptor>&& value); - inline ::capnp::Orphan< ::capnp::rpc::CapDescriptor> disownCap(); - - inline bool isException(); - inline bool hasException(); - inline ::capnp::rpc::Exception::Builder getException(); - inline void setException( ::capnp::rpc::Exception::Reader value); - inline ::capnp::rpc::Exception::Builder initException(); - inline void adoptException(::capnp::Orphan< ::capnp::rpc::Exception>&& value); - inline ::capnp::Orphan< ::capnp::rpc::Exception> disownException(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Resolve::Pipeline { -public: - typedef Resolve Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Release::Reader { -public: - typedef Release Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint32_t getId() const; - - inline ::uint32_t getReferenceCount() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Release::Builder { -public: - typedef Release Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint32_t getId(); - inline void setId( ::uint32_t value); - - inline ::uint32_t getReferenceCount(); - inline void setReferenceCount( ::uint32_t value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Release::Pipeline { -public: - typedef Release Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Disembargo::Reader { -public: - typedef Disembargo Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline bool hasTarget() const; - inline ::capnp::rpc::MessageTarget::Reader getTarget() const; - - inline typename Context::Reader getContext() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Disembargo::Builder { -public: - typedef Disembargo Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline bool hasTarget(); - inline ::capnp::rpc::MessageTarget::Builder getTarget(); - inline void setTarget( ::capnp::rpc::MessageTarget::Reader value); - inline ::capnp::rpc::MessageTarget::Builder initTarget(); - inline void adoptTarget(::capnp::Orphan< ::capnp::rpc::MessageTarget>&& value); - inline ::capnp::Orphan< ::capnp::rpc::MessageTarget> disownTarget(); - - inline typename Context::Builder getContext(); - inline typename Context::Builder initContext(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Disembargo::Pipeline { -public: - typedef Disembargo Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline ::capnp::rpc::MessageTarget::Pipeline getTarget(); - inline typename Context::Pipeline getContext(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Disembargo::Context::Reader { -public: - typedef Context Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline Which which() const; - inline bool isSenderLoopback() const; - inline ::uint32_t getSenderLoopback() const; - - inline bool isReceiverLoopback() const; - inline ::uint32_t getReceiverLoopback() const; - - inline bool isAccept() const; - inline ::capnp::Void getAccept() const; - - inline bool isProvide() const; - inline ::uint32_t getProvide() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Disembargo::Context::Builder { -public: - typedef Context Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline Which which(); - inline bool isSenderLoopback(); - inline ::uint32_t getSenderLoopback(); - inline void setSenderLoopback( ::uint32_t value); - - inline bool isReceiverLoopback(); - inline ::uint32_t getReceiverLoopback(); - inline void setReceiverLoopback( ::uint32_t value); - - inline bool isAccept(); - inline ::capnp::Void getAccept(); - inline void setAccept( ::capnp::Void value = ::capnp::VOID); - - inline bool isProvide(); - inline ::uint32_t getProvide(); - inline void setProvide( ::uint32_t value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Disembargo::Context::Pipeline { -public: - typedef Context Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Provide::Reader { -public: - typedef Provide Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint32_t getQuestionId() const; - - inline bool hasTarget() const; - inline ::capnp::rpc::MessageTarget::Reader getTarget() const; - - inline bool hasRecipient() const; - inline ::capnp::AnyPointer::Reader getRecipient() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Provide::Builder { -public: - typedef Provide Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint32_t getQuestionId(); - inline void setQuestionId( ::uint32_t value); - - inline bool hasTarget(); - inline ::capnp::rpc::MessageTarget::Builder getTarget(); - inline void setTarget( ::capnp::rpc::MessageTarget::Reader value); - inline ::capnp::rpc::MessageTarget::Builder initTarget(); - inline void adoptTarget(::capnp::Orphan< ::capnp::rpc::MessageTarget>&& value); - inline ::capnp::Orphan< ::capnp::rpc::MessageTarget> disownTarget(); - - inline bool hasRecipient(); - inline ::capnp::AnyPointer::Builder getRecipient(); - inline ::capnp::AnyPointer::Builder initRecipient(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Provide::Pipeline { -public: - typedef Provide Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline ::capnp::rpc::MessageTarget::Pipeline getTarget(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Accept::Reader { -public: - typedef Accept Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint32_t getQuestionId() const; - - inline bool hasProvision() const; - inline ::capnp::AnyPointer::Reader getProvision() const; - - inline bool getEmbargo() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Accept::Builder { -public: - typedef Accept Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint32_t getQuestionId(); - inline void setQuestionId( ::uint32_t value); - - inline bool hasProvision(); - inline ::capnp::AnyPointer::Builder getProvision(); - inline ::capnp::AnyPointer::Builder initProvision(); - - inline bool getEmbargo(); - inline void setEmbargo(bool value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Accept::Pipeline { -public: - typedef Accept Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Join::Reader { -public: - typedef Join Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint32_t getQuestionId() const; - - inline bool hasTarget() const; - inline ::capnp::rpc::MessageTarget::Reader getTarget() const; - - inline bool hasKeyPart() const; - inline ::capnp::AnyPointer::Reader getKeyPart() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Join::Builder { -public: - typedef Join Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint32_t getQuestionId(); - inline void setQuestionId( ::uint32_t value); - - inline bool hasTarget(); - inline ::capnp::rpc::MessageTarget::Builder getTarget(); - inline void setTarget( ::capnp::rpc::MessageTarget::Reader value); - inline ::capnp::rpc::MessageTarget::Builder initTarget(); - inline void adoptTarget(::capnp::Orphan< ::capnp::rpc::MessageTarget>&& value); - inline ::capnp::Orphan< ::capnp::rpc::MessageTarget> disownTarget(); - - inline bool hasKeyPart(); - inline ::capnp::AnyPointer::Builder getKeyPart(); - inline ::capnp::AnyPointer::Builder initKeyPart(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Join::Pipeline { -public: - typedef Join Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline ::capnp::rpc::MessageTarget::Pipeline getTarget(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class MessageTarget::Reader { -public: - typedef MessageTarget Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline Which which() const; - inline bool isImportedCap() const; - inline ::uint32_t getImportedCap() const; - - inline bool isPromisedAnswer() const; - inline bool hasPromisedAnswer() const; - inline ::capnp::rpc::PromisedAnswer::Reader getPromisedAnswer() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class MessageTarget::Builder { -public: - typedef MessageTarget Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline Which which(); - inline bool isImportedCap(); - inline ::uint32_t getImportedCap(); - inline void setImportedCap( ::uint32_t value); - - inline bool isPromisedAnswer(); - inline bool hasPromisedAnswer(); - inline ::capnp::rpc::PromisedAnswer::Builder getPromisedAnswer(); - inline void setPromisedAnswer( ::capnp::rpc::PromisedAnswer::Reader value); - inline ::capnp::rpc::PromisedAnswer::Builder initPromisedAnswer(); - inline void adoptPromisedAnswer(::capnp::Orphan< ::capnp::rpc::PromisedAnswer>&& value); - inline ::capnp::Orphan< ::capnp::rpc::PromisedAnswer> disownPromisedAnswer(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class MessageTarget::Pipeline { -public: - typedef MessageTarget Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Payload::Reader { -public: - typedef Payload Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline bool hasContent() const; - inline ::capnp::AnyPointer::Reader getContent() const; - - inline bool hasCapTable() const; - inline ::capnp::List< ::capnp::rpc::CapDescriptor>::Reader getCapTable() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Payload::Builder { -public: - typedef Payload Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline bool hasContent(); - inline ::capnp::AnyPointer::Builder getContent(); - inline ::capnp::AnyPointer::Builder initContent(); - - inline bool hasCapTable(); - inline ::capnp::List< ::capnp::rpc::CapDescriptor>::Builder getCapTable(); - inline void setCapTable( ::capnp::List< ::capnp::rpc::CapDescriptor>::Reader value); - inline ::capnp::List< ::capnp::rpc::CapDescriptor>::Builder initCapTable(unsigned int size); - inline void adoptCapTable(::capnp::Orphan< ::capnp::List< ::capnp::rpc::CapDescriptor>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::rpc::CapDescriptor>> disownCapTable(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Payload::Pipeline { -public: - typedef Payload Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class CapDescriptor::Reader { -public: - typedef CapDescriptor Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline Which which() const; - inline bool isNone() const; - inline ::capnp::Void getNone() const; - - inline bool isSenderHosted() const; - inline ::uint32_t getSenderHosted() const; - - inline bool isSenderPromise() const; - inline ::uint32_t getSenderPromise() const; - - inline bool isReceiverHosted() const; - inline ::uint32_t getReceiverHosted() const; - - inline bool isReceiverAnswer() const; - inline bool hasReceiverAnswer() const; - inline ::capnp::rpc::PromisedAnswer::Reader getReceiverAnswer() const; - - inline bool isThirdPartyHosted() const; - inline bool hasThirdPartyHosted() const; - inline ::capnp::rpc::ThirdPartyCapDescriptor::Reader getThirdPartyHosted() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class CapDescriptor::Builder { -public: - typedef CapDescriptor Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline Which which(); - inline bool isNone(); - inline ::capnp::Void getNone(); - inline void setNone( ::capnp::Void value = ::capnp::VOID); - - inline bool isSenderHosted(); - inline ::uint32_t getSenderHosted(); - inline void setSenderHosted( ::uint32_t value); - - inline bool isSenderPromise(); - inline ::uint32_t getSenderPromise(); - inline void setSenderPromise( ::uint32_t value); - - inline bool isReceiverHosted(); - inline ::uint32_t getReceiverHosted(); - inline void setReceiverHosted( ::uint32_t value); - - inline bool isReceiverAnswer(); - inline bool hasReceiverAnswer(); - inline ::capnp::rpc::PromisedAnswer::Builder getReceiverAnswer(); - inline void setReceiverAnswer( ::capnp::rpc::PromisedAnswer::Reader value); - inline ::capnp::rpc::PromisedAnswer::Builder initReceiverAnswer(); - inline void adoptReceiverAnswer(::capnp::Orphan< ::capnp::rpc::PromisedAnswer>&& value); - inline ::capnp::Orphan< ::capnp::rpc::PromisedAnswer> disownReceiverAnswer(); - - inline bool isThirdPartyHosted(); - inline bool hasThirdPartyHosted(); - inline ::capnp::rpc::ThirdPartyCapDescriptor::Builder getThirdPartyHosted(); - inline void setThirdPartyHosted( ::capnp::rpc::ThirdPartyCapDescriptor::Reader value); - inline ::capnp::rpc::ThirdPartyCapDescriptor::Builder initThirdPartyHosted(); - inline void adoptThirdPartyHosted(::capnp::Orphan< ::capnp::rpc::ThirdPartyCapDescriptor>&& value); - inline ::capnp::Orphan< ::capnp::rpc::ThirdPartyCapDescriptor> disownThirdPartyHosted(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class CapDescriptor::Pipeline { -public: - typedef CapDescriptor Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class PromisedAnswer::Reader { -public: - typedef PromisedAnswer Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint32_t getQuestionId() const; - - inline bool hasTransform() const; - inline ::capnp::List< ::capnp::rpc::PromisedAnswer::Op>::Reader getTransform() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class PromisedAnswer::Builder { -public: - typedef PromisedAnswer Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint32_t getQuestionId(); - inline void setQuestionId( ::uint32_t value); - - inline bool hasTransform(); - inline ::capnp::List< ::capnp::rpc::PromisedAnswer::Op>::Builder getTransform(); - inline void setTransform( ::capnp::List< ::capnp::rpc::PromisedAnswer::Op>::Reader value); - inline ::capnp::List< ::capnp::rpc::PromisedAnswer::Op>::Builder initTransform(unsigned int size); - inline void adoptTransform(::capnp::Orphan< ::capnp::List< ::capnp::rpc::PromisedAnswer::Op>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::rpc::PromisedAnswer::Op>> disownTransform(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class PromisedAnswer::Pipeline { -public: - typedef PromisedAnswer Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class PromisedAnswer::Op::Reader { -public: - typedef Op Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline Which which() const; - inline bool isNoop() const; - inline ::capnp::Void getNoop() const; - - inline bool isGetPointerField() const; - inline ::uint16_t getGetPointerField() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class PromisedAnswer::Op::Builder { -public: - typedef Op Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline Which which(); - inline bool isNoop(); - inline ::capnp::Void getNoop(); - inline void setNoop( ::capnp::Void value = ::capnp::VOID); - - inline bool isGetPointerField(); - inline ::uint16_t getGetPointerField(); - inline void setGetPointerField( ::uint16_t value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class PromisedAnswer::Op::Pipeline { -public: - typedef Op Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class ThirdPartyCapDescriptor::Reader { -public: - typedef ThirdPartyCapDescriptor Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline bool hasId() const; - inline ::capnp::AnyPointer::Reader getId() const; - - inline ::uint32_t getVineId() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class ThirdPartyCapDescriptor::Builder { -public: - typedef ThirdPartyCapDescriptor Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline bool hasId(); - inline ::capnp::AnyPointer::Builder getId(); - inline ::capnp::AnyPointer::Builder initId(); - - inline ::uint32_t getVineId(); - inline void setVineId( ::uint32_t value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class ThirdPartyCapDescriptor::Pipeline { -public: - typedef ThirdPartyCapDescriptor Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Exception::Reader { -public: - typedef Exception Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline bool hasReason() const; - inline ::capnp::Text::Reader getReason() const; - - inline bool getObsoleteIsCallersFault() const; - - inline ::uint16_t getObsoleteDurability() const; - - inline ::capnp::rpc::Exception::Type getType() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Exception::Builder { -public: - typedef Exception Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline bool hasReason(); - inline ::capnp::Text::Builder getReason(); - inline void setReason( ::capnp::Text::Reader value); - inline ::capnp::Text::Builder initReason(unsigned int size); - inline void adoptReason(::capnp::Orphan< ::capnp::Text>&& value); - inline ::capnp::Orphan< ::capnp::Text> disownReason(); - - inline bool getObsoleteIsCallersFault(); - inline void setObsoleteIsCallersFault(bool value); - - inline ::uint16_t getObsoleteDurability(); - inline void setObsoleteDurability( ::uint16_t value); - - inline ::capnp::rpc::Exception::Type getType(); - inline void setType( ::capnp::rpc::Exception::Type value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Exception::Pipeline { -public: - typedef Exception Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -// ======================================================================================= - -inline ::capnp::rpc::Message::Which Message::Reader::which() const { - return _reader.getDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline ::capnp::rpc::Message::Which Message::Builder::which() { - return _builder.getDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline bool Message::Reader::isUnimplemented() const { - return which() == Message::UNIMPLEMENTED; -} -inline bool Message::Builder::isUnimplemented() { - return which() == Message::UNIMPLEMENTED; -} -inline bool Message::Reader::hasUnimplemented() const { - if (which() != Message::UNIMPLEMENTED) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Message::Builder::hasUnimplemented() { - if (which() != Message::UNIMPLEMENTED) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::Message::Reader Message::Reader::getUnimplemented() const { - KJ_IREQUIRE((which() == Message::UNIMPLEMENTED), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Message>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::Message::Builder Message::Builder::getUnimplemented() { - KJ_IREQUIRE((which() == Message::UNIMPLEMENTED), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Message>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::setUnimplemented( ::capnp::rpc::Message::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::UNIMPLEMENTED); - ::capnp::_::PointerHelpers< ::capnp::rpc::Message>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::Message::Builder Message::Builder::initUnimplemented() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::UNIMPLEMENTED); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Message>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::adoptUnimplemented( - ::capnp::Orphan< ::capnp::rpc::Message>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::UNIMPLEMENTED); - ::capnp::_::PointerHelpers< ::capnp::rpc::Message>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::Message> Message::Builder::disownUnimplemented() { - KJ_IREQUIRE((which() == Message::UNIMPLEMENTED), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Message>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Message::Reader::isAbort() const { - return which() == Message::ABORT; -} -inline bool Message::Builder::isAbort() { - return which() == Message::ABORT; -} -inline bool Message::Reader::hasAbort() const { - if (which() != Message::ABORT) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Message::Builder::hasAbort() { - if (which() != Message::ABORT) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::Exception::Reader Message::Reader::getAbort() const { - KJ_IREQUIRE((which() == Message::ABORT), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Exception>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::Exception::Builder Message::Builder::getAbort() { - KJ_IREQUIRE((which() == Message::ABORT), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Exception>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::setAbort( ::capnp::rpc::Exception::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::ABORT); - ::capnp::_::PointerHelpers< ::capnp::rpc::Exception>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::Exception::Builder Message::Builder::initAbort() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::ABORT); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Exception>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::adoptAbort( - ::capnp::Orphan< ::capnp::rpc::Exception>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::ABORT); - ::capnp::_::PointerHelpers< ::capnp::rpc::Exception>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::Exception> Message::Builder::disownAbort() { - KJ_IREQUIRE((which() == Message::ABORT), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Exception>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Message::Reader::isCall() const { - return which() == Message::CALL; -} -inline bool Message::Builder::isCall() { - return which() == Message::CALL; -} -inline bool Message::Reader::hasCall() const { - if (which() != Message::CALL) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Message::Builder::hasCall() { - if (which() != Message::CALL) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::Call::Reader Message::Reader::getCall() const { - KJ_IREQUIRE((which() == Message::CALL), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Call>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::Call::Builder Message::Builder::getCall() { - KJ_IREQUIRE((which() == Message::CALL), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Call>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::setCall( ::capnp::rpc::Call::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::CALL); - ::capnp::_::PointerHelpers< ::capnp::rpc::Call>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::Call::Builder Message::Builder::initCall() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::CALL); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Call>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::adoptCall( - ::capnp::Orphan< ::capnp::rpc::Call>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::CALL); - ::capnp::_::PointerHelpers< ::capnp::rpc::Call>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::Call> Message::Builder::disownCall() { - KJ_IREQUIRE((which() == Message::CALL), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Call>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Message::Reader::isReturn() const { - return which() == Message::RETURN; -} -inline bool Message::Builder::isReturn() { - return which() == Message::RETURN; -} -inline bool Message::Reader::hasReturn() const { - if (which() != Message::RETURN) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Message::Builder::hasReturn() { - if (which() != Message::RETURN) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::Return::Reader Message::Reader::getReturn() const { - KJ_IREQUIRE((which() == Message::RETURN), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Return>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::Return::Builder Message::Builder::getReturn() { - KJ_IREQUIRE((which() == Message::RETURN), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Return>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::setReturn( ::capnp::rpc::Return::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::RETURN); - ::capnp::_::PointerHelpers< ::capnp::rpc::Return>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::Return::Builder Message::Builder::initReturn() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::RETURN); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Return>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::adoptReturn( - ::capnp::Orphan< ::capnp::rpc::Return>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::RETURN); - ::capnp::_::PointerHelpers< ::capnp::rpc::Return>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::Return> Message::Builder::disownReturn() { - KJ_IREQUIRE((which() == Message::RETURN), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Return>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Message::Reader::isFinish() const { - return which() == Message::FINISH; -} -inline bool Message::Builder::isFinish() { - return which() == Message::FINISH; -} -inline bool Message::Reader::hasFinish() const { - if (which() != Message::FINISH) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Message::Builder::hasFinish() { - if (which() != Message::FINISH) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::Finish::Reader Message::Reader::getFinish() const { - KJ_IREQUIRE((which() == Message::FINISH), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Finish>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::Finish::Builder Message::Builder::getFinish() { - KJ_IREQUIRE((which() == Message::FINISH), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Finish>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::setFinish( ::capnp::rpc::Finish::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::FINISH); - ::capnp::_::PointerHelpers< ::capnp::rpc::Finish>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::Finish::Builder Message::Builder::initFinish() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::FINISH); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Finish>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::adoptFinish( - ::capnp::Orphan< ::capnp::rpc::Finish>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::FINISH); - ::capnp::_::PointerHelpers< ::capnp::rpc::Finish>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::Finish> Message::Builder::disownFinish() { - KJ_IREQUIRE((which() == Message::FINISH), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Finish>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Message::Reader::isResolve() const { - return which() == Message::RESOLVE; -} -inline bool Message::Builder::isResolve() { - return which() == Message::RESOLVE; -} -inline bool Message::Reader::hasResolve() const { - if (which() != Message::RESOLVE) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Message::Builder::hasResolve() { - if (which() != Message::RESOLVE) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::Resolve::Reader Message::Reader::getResolve() const { - KJ_IREQUIRE((which() == Message::RESOLVE), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Resolve>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::Resolve::Builder Message::Builder::getResolve() { - KJ_IREQUIRE((which() == Message::RESOLVE), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Resolve>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::setResolve( ::capnp::rpc::Resolve::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::RESOLVE); - ::capnp::_::PointerHelpers< ::capnp::rpc::Resolve>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::Resolve::Builder Message::Builder::initResolve() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::RESOLVE); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Resolve>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::adoptResolve( - ::capnp::Orphan< ::capnp::rpc::Resolve>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::RESOLVE); - ::capnp::_::PointerHelpers< ::capnp::rpc::Resolve>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::Resolve> Message::Builder::disownResolve() { - KJ_IREQUIRE((which() == Message::RESOLVE), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Resolve>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Message::Reader::isRelease() const { - return which() == Message::RELEASE; -} -inline bool Message::Builder::isRelease() { - return which() == Message::RELEASE; -} -inline bool Message::Reader::hasRelease() const { - if (which() != Message::RELEASE) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Message::Builder::hasRelease() { - if (which() != Message::RELEASE) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::Release::Reader Message::Reader::getRelease() const { - KJ_IREQUIRE((which() == Message::RELEASE), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Release>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::Release::Builder Message::Builder::getRelease() { - KJ_IREQUIRE((which() == Message::RELEASE), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Release>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::setRelease( ::capnp::rpc::Release::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::RELEASE); - ::capnp::_::PointerHelpers< ::capnp::rpc::Release>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::Release::Builder Message::Builder::initRelease() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::RELEASE); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Release>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::adoptRelease( - ::capnp::Orphan< ::capnp::rpc::Release>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::RELEASE); - ::capnp::_::PointerHelpers< ::capnp::rpc::Release>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::Release> Message::Builder::disownRelease() { - KJ_IREQUIRE((which() == Message::RELEASE), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Release>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Message::Reader::isObsoleteSave() const { - return which() == Message::OBSOLETE_SAVE; -} -inline bool Message::Builder::isObsoleteSave() { - return which() == Message::OBSOLETE_SAVE; -} -inline bool Message::Reader::hasObsoleteSave() const { - if (which() != Message::OBSOLETE_SAVE) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Message::Builder::hasObsoleteSave() { - if (which() != Message::OBSOLETE_SAVE) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::AnyPointer::Reader Message::Reader::getObsoleteSave() const { - KJ_IREQUIRE((which() == Message::OBSOLETE_SAVE), - "Must check which() before get()ing a union member."); - return ::capnp::AnyPointer::Reader(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Message::Builder::getObsoleteSave() { - KJ_IREQUIRE((which() == Message::OBSOLETE_SAVE), - "Must check which() before get()ing a union member."); - return ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Message::Builder::initObsoleteSave() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::OBSOLETE_SAVE); - auto result = ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); - result.clear(); - return result; -} - -inline bool Message::Reader::isBootstrap() const { - return which() == Message::BOOTSTRAP; -} -inline bool Message::Builder::isBootstrap() { - return which() == Message::BOOTSTRAP; -} -inline bool Message::Reader::hasBootstrap() const { - if (which() != Message::BOOTSTRAP) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Message::Builder::hasBootstrap() { - if (which() != Message::BOOTSTRAP) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::Bootstrap::Reader Message::Reader::getBootstrap() const { - KJ_IREQUIRE((which() == Message::BOOTSTRAP), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Bootstrap>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::Bootstrap::Builder Message::Builder::getBootstrap() { - KJ_IREQUIRE((which() == Message::BOOTSTRAP), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Bootstrap>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::setBootstrap( ::capnp::rpc::Bootstrap::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::BOOTSTRAP); - ::capnp::_::PointerHelpers< ::capnp::rpc::Bootstrap>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::Bootstrap::Builder Message::Builder::initBootstrap() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::BOOTSTRAP); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Bootstrap>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::adoptBootstrap( - ::capnp::Orphan< ::capnp::rpc::Bootstrap>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::BOOTSTRAP); - ::capnp::_::PointerHelpers< ::capnp::rpc::Bootstrap>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::Bootstrap> Message::Builder::disownBootstrap() { - KJ_IREQUIRE((which() == Message::BOOTSTRAP), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Bootstrap>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Message::Reader::isObsoleteDelete() const { - return which() == Message::OBSOLETE_DELETE; -} -inline bool Message::Builder::isObsoleteDelete() { - return which() == Message::OBSOLETE_DELETE; -} -inline bool Message::Reader::hasObsoleteDelete() const { - if (which() != Message::OBSOLETE_DELETE) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Message::Builder::hasObsoleteDelete() { - if (which() != Message::OBSOLETE_DELETE) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::AnyPointer::Reader Message::Reader::getObsoleteDelete() const { - KJ_IREQUIRE((which() == Message::OBSOLETE_DELETE), - "Must check which() before get()ing a union member."); - return ::capnp::AnyPointer::Reader(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Message::Builder::getObsoleteDelete() { - KJ_IREQUIRE((which() == Message::OBSOLETE_DELETE), - "Must check which() before get()ing a union member."); - return ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Message::Builder::initObsoleteDelete() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::OBSOLETE_DELETE); - auto result = ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); - result.clear(); - return result; -} - -inline bool Message::Reader::isProvide() const { - return which() == Message::PROVIDE; -} -inline bool Message::Builder::isProvide() { - return which() == Message::PROVIDE; -} -inline bool Message::Reader::hasProvide() const { - if (which() != Message::PROVIDE) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Message::Builder::hasProvide() { - if (which() != Message::PROVIDE) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::Provide::Reader Message::Reader::getProvide() const { - KJ_IREQUIRE((which() == Message::PROVIDE), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Provide>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::Provide::Builder Message::Builder::getProvide() { - KJ_IREQUIRE((which() == Message::PROVIDE), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Provide>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::setProvide( ::capnp::rpc::Provide::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::PROVIDE); - ::capnp::_::PointerHelpers< ::capnp::rpc::Provide>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::Provide::Builder Message::Builder::initProvide() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::PROVIDE); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Provide>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::adoptProvide( - ::capnp::Orphan< ::capnp::rpc::Provide>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::PROVIDE); - ::capnp::_::PointerHelpers< ::capnp::rpc::Provide>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::Provide> Message::Builder::disownProvide() { - KJ_IREQUIRE((which() == Message::PROVIDE), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Provide>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Message::Reader::isAccept() const { - return which() == Message::ACCEPT; -} -inline bool Message::Builder::isAccept() { - return which() == Message::ACCEPT; -} -inline bool Message::Reader::hasAccept() const { - if (which() != Message::ACCEPT) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Message::Builder::hasAccept() { - if (which() != Message::ACCEPT) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::Accept::Reader Message::Reader::getAccept() const { - KJ_IREQUIRE((which() == Message::ACCEPT), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Accept>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::Accept::Builder Message::Builder::getAccept() { - KJ_IREQUIRE((which() == Message::ACCEPT), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Accept>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::setAccept( ::capnp::rpc::Accept::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::ACCEPT); - ::capnp::_::PointerHelpers< ::capnp::rpc::Accept>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::Accept::Builder Message::Builder::initAccept() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::ACCEPT); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Accept>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::adoptAccept( - ::capnp::Orphan< ::capnp::rpc::Accept>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::ACCEPT); - ::capnp::_::PointerHelpers< ::capnp::rpc::Accept>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::Accept> Message::Builder::disownAccept() { - KJ_IREQUIRE((which() == Message::ACCEPT), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Accept>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Message::Reader::isJoin() const { - return which() == Message::JOIN; -} -inline bool Message::Builder::isJoin() { - return which() == Message::JOIN; -} -inline bool Message::Reader::hasJoin() const { - if (which() != Message::JOIN) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Message::Builder::hasJoin() { - if (which() != Message::JOIN) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::Join::Reader Message::Reader::getJoin() const { - KJ_IREQUIRE((which() == Message::JOIN), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Join>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::Join::Builder Message::Builder::getJoin() { - KJ_IREQUIRE((which() == Message::JOIN), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Join>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::setJoin( ::capnp::rpc::Join::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::JOIN); - ::capnp::_::PointerHelpers< ::capnp::rpc::Join>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::Join::Builder Message::Builder::initJoin() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::JOIN); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Join>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::adoptJoin( - ::capnp::Orphan< ::capnp::rpc::Join>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::JOIN); - ::capnp::_::PointerHelpers< ::capnp::rpc::Join>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::Join> Message::Builder::disownJoin() { - KJ_IREQUIRE((which() == Message::JOIN), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Join>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Message::Reader::isDisembargo() const { - return which() == Message::DISEMBARGO; -} -inline bool Message::Builder::isDisembargo() { - return which() == Message::DISEMBARGO; -} -inline bool Message::Reader::hasDisembargo() const { - if (which() != Message::DISEMBARGO) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Message::Builder::hasDisembargo() { - if (which() != Message::DISEMBARGO) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::Disembargo::Reader Message::Reader::getDisembargo() const { - KJ_IREQUIRE((which() == Message::DISEMBARGO), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Disembargo>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::Disembargo::Builder Message::Builder::getDisembargo() { - KJ_IREQUIRE((which() == Message::DISEMBARGO), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Disembargo>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::setDisembargo( ::capnp::rpc::Disembargo::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::DISEMBARGO); - ::capnp::_::PointerHelpers< ::capnp::rpc::Disembargo>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::Disembargo::Builder Message::Builder::initDisembargo() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::DISEMBARGO); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Disembargo>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Message::Builder::adoptDisembargo( - ::capnp::Orphan< ::capnp::rpc::Disembargo>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Message::DISEMBARGO); - ::capnp::_::PointerHelpers< ::capnp::rpc::Disembargo>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::Disembargo> Message::Builder::disownDisembargo() { - KJ_IREQUIRE((which() == Message::DISEMBARGO), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Disembargo>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline ::uint32_t Bootstrap::Reader::getQuestionId() const { - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Bootstrap::Builder::getQuestionId() { - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Bootstrap::Builder::setQuestionId( ::uint32_t value) { - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Bootstrap::Reader::hasDeprecatedObjectId() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Bootstrap::Builder::hasDeprecatedObjectId() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::AnyPointer::Reader Bootstrap::Reader::getDeprecatedObjectId() const { - return ::capnp::AnyPointer::Reader(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Bootstrap::Builder::getDeprecatedObjectId() { - return ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Bootstrap::Builder::initDeprecatedObjectId() { - auto result = ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); - result.clear(); - return result; -} - -inline ::uint32_t Call::Reader::getQuestionId() const { - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Call::Builder::getQuestionId() { - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Call::Builder::setQuestionId( ::uint32_t value) { - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Call::Reader::hasTarget() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Call::Builder::hasTarget() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::MessageTarget::Reader Call::Reader::getTarget() const { - return ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::MessageTarget::Builder Call::Builder::getTarget() { - return ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::rpc::MessageTarget::Pipeline Call::Pipeline::getTarget() { - return ::capnp::rpc::MessageTarget::Pipeline(_typeless.getPointerField(0)); -} -#endif // !CAPNP_LITE -inline void Call::Builder::setTarget( ::capnp::rpc::MessageTarget::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::MessageTarget::Builder Call::Builder::initTarget() { - return ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Call::Builder::adoptTarget( - ::capnp::Orphan< ::capnp::rpc::MessageTarget>&& value) { - ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::MessageTarget> Call::Builder::disownTarget() { - return ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline ::uint64_t Call::Reader::getInterfaceId() const { - return _reader.getDataField< ::uint64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline ::uint64_t Call::Builder::getInterfaceId() { - return _builder.getDataField< ::uint64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void Call::Builder::setInterfaceId( ::uint64_t value) { - _builder.setDataField< ::uint64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline ::uint16_t Call::Reader::getMethodId() const { - return _reader.getDataField< ::uint16_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} - -inline ::uint16_t Call::Builder::getMethodId() { - return _builder.getDataField< ::uint16_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} -inline void Call::Builder::setMethodId( ::uint16_t value) { - _builder.setDataField< ::uint16_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, value); -} - -inline bool Call::Reader::hasParams() const { - return !_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline bool Call::Builder::hasParams() { - return !_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::Payload::Reader Call::Reader::getParams() const { - return ::capnp::_::PointerHelpers< ::capnp::rpc::Payload>::get(_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::Payload::Builder Call::Builder::getParams() { - return ::capnp::_::PointerHelpers< ::capnp::rpc::Payload>::get(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::rpc::Payload::Pipeline Call::Pipeline::getParams() { - return ::capnp::rpc::Payload::Pipeline(_typeless.getPointerField(1)); -} -#endif // !CAPNP_LITE -inline void Call::Builder::setParams( ::capnp::rpc::Payload::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::rpc::Payload>::set(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::Payload::Builder Call::Builder::initParams() { - return ::capnp::_::PointerHelpers< ::capnp::rpc::Payload>::init(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline void Call::Builder::adoptParams( - ::capnp::Orphan< ::capnp::rpc::Payload>&& value) { - ::capnp::_::PointerHelpers< ::capnp::rpc::Payload>::adopt(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::Payload> Call::Builder::disownParams() { - return ::capnp::_::PointerHelpers< ::capnp::rpc::Payload>::disown(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} - -inline typename Call::SendResultsTo::Reader Call::Reader::getSendResultsTo() const { - return typename Call::SendResultsTo::Reader(_reader); -} -inline typename Call::SendResultsTo::Builder Call::Builder::getSendResultsTo() { - return typename Call::SendResultsTo::Builder(_builder); -} -#if !CAPNP_LITE -inline typename Call::SendResultsTo::Pipeline Call::Pipeline::getSendResultsTo() { - return typename Call::SendResultsTo::Pipeline(_typeless.noop()); -} -#endif // !CAPNP_LITE -inline typename Call::SendResultsTo::Builder Call::Builder::initSendResultsTo() { - _builder.setDataField< ::uint16_t>(::capnp::bounded<3>() * ::capnp::ELEMENTS, 0); - _builder.getPointerField(::capnp::bounded<2>() * ::capnp::POINTERS).clear(); - return typename Call::SendResultsTo::Builder(_builder); -} -inline bool Call::Reader::getAllowThirdPartyTailCall() const { - return _reader.getDataField( - ::capnp::bounded<128>() * ::capnp::ELEMENTS); -} - -inline bool Call::Builder::getAllowThirdPartyTailCall() { - return _builder.getDataField( - ::capnp::bounded<128>() * ::capnp::ELEMENTS); -} -inline void Call::Builder::setAllowThirdPartyTailCall(bool value) { - _builder.setDataField( - ::capnp::bounded<128>() * ::capnp::ELEMENTS, value); -} - -inline ::capnp::rpc::Call::SendResultsTo::Which Call::SendResultsTo::Reader::which() const { - return _reader.getDataField( - ::capnp::bounded<3>() * ::capnp::ELEMENTS); -} -inline ::capnp::rpc::Call::SendResultsTo::Which Call::SendResultsTo::Builder::which() { - return _builder.getDataField( - ::capnp::bounded<3>() * ::capnp::ELEMENTS); -} - -inline bool Call::SendResultsTo::Reader::isCaller() const { - return which() == Call::SendResultsTo::CALLER; -} -inline bool Call::SendResultsTo::Builder::isCaller() { - return which() == Call::SendResultsTo::CALLER; -} -inline ::capnp::Void Call::SendResultsTo::Reader::getCaller() const { - KJ_IREQUIRE((which() == Call::SendResultsTo::CALLER), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Call::SendResultsTo::Builder::getCaller() { - KJ_IREQUIRE((which() == Call::SendResultsTo::CALLER), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Call::SendResultsTo::Builder::setCaller( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<3>() * ::capnp::ELEMENTS, Call::SendResultsTo::CALLER); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Call::SendResultsTo::Reader::isYourself() const { - return which() == Call::SendResultsTo::YOURSELF; -} -inline bool Call::SendResultsTo::Builder::isYourself() { - return which() == Call::SendResultsTo::YOURSELF; -} -inline ::capnp::Void Call::SendResultsTo::Reader::getYourself() const { - KJ_IREQUIRE((which() == Call::SendResultsTo::YOURSELF), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Call::SendResultsTo::Builder::getYourself() { - KJ_IREQUIRE((which() == Call::SendResultsTo::YOURSELF), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Call::SendResultsTo::Builder::setYourself( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<3>() * ::capnp::ELEMENTS, Call::SendResultsTo::YOURSELF); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Call::SendResultsTo::Reader::isThirdParty() const { - return which() == Call::SendResultsTo::THIRD_PARTY; -} -inline bool Call::SendResultsTo::Builder::isThirdParty() { - return which() == Call::SendResultsTo::THIRD_PARTY; -} -inline bool Call::SendResultsTo::Reader::hasThirdParty() const { - if (which() != Call::SendResultsTo::THIRD_PARTY) return false; - return !_reader.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS).isNull(); -} -inline bool Call::SendResultsTo::Builder::hasThirdParty() { - if (which() != Call::SendResultsTo::THIRD_PARTY) return false; - return !_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::AnyPointer::Reader Call::SendResultsTo::Reader::getThirdParty() const { - KJ_IREQUIRE((which() == Call::SendResultsTo::THIRD_PARTY), - "Must check which() before get()ing a union member."); - return ::capnp::AnyPointer::Reader(_reader.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Call::SendResultsTo::Builder::getThirdParty() { - KJ_IREQUIRE((which() == Call::SendResultsTo::THIRD_PARTY), - "Must check which() before get()ing a union member."); - return ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Call::SendResultsTo::Builder::initThirdParty() { - _builder.setDataField( - ::capnp::bounded<3>() * ::capnp::ELEMENTS, Call::SendResultsTo::THIRD_PARTY); - auto result = ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS)); - result.clear(); - return result; -} - -inline ::capnp::rpc::Return::Which Return::Reader::which() const { - return _reader.getDataField( - ::capnp::bounded<3>() * ::capnp::ELEMENTS); -} -inline ::capnp::rpc::Return::Which Return::Builder::which() { - return _builder.getDataField( - ::capnp::bounded<3>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Return::Reader::getAnswerId() const { - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Return::Builder::getAnswerId() { - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Return::Builder::setAnswerId( ::uint32_t value) { - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Return::Reader::getReleaseParamCaps() const { - return _reader.getDataField( - ::capnp::bounded<32>() * ::capnp::ELEMENTS, true); -} - -inline bool Return::Builder::getReleaseParamCaps() { - return _builder.getDataField( - ::capnp::bounded<32>() * ::capnp::ELEMENTS, true); -} -inline void Return::Builder::setReleaseParamCaps(bool value) { - _builder.setDataField( - ::capnp::bounded<32>() * ::capnp::ELEMENTS, value, true); -} - -inline bool Return::Reader::isResults() const { - return which() == Return::RESULTS; -} -inline bool Return::Builder::isResults() { - return which() == Return::RESULTS; -} -inline bool Return::Reader::hasResults() const { - if (which() != Return::RESULTS) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Return::Builder::hasResults() { - if (which() != Return::RESULTS) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::Payload::Reader Return::Reader::getResults() const { - KJ_IREQUIRE((which() == Return::RESULTS), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Payload>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::Payload::Builder Return::Builder::getResults() { - KJ_IREQUIRE((which() == Return::RESULTS), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Payload>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Return::Builder::setResults( ::capnp::rpc::Payload::Reader value) { - _builder.setDataField( - ::capnp::bounded<3>() * ::capnp::ELEMENTS, Return::RESULTS); - ::capnp::_::PointerHelpers< ::capnp::rpc::Payload>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::Payload::Builder Return::Builder::initResults() { - _builder.setDataField( - ::capnp::bounded<3>() * ::capnp::ELEMENTS, Return::RESULTS); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Payload>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Return::Builder::adoptResults( - ::capnp::Orphan< ::capnp::rpc::Payload>&& value) { - _builder.setDataField( - ::capnp::bounded<3>() * ::capnp::ELEMENTS, Return::RESULTS); - ::capnp::_::PointerHelpers< ::capnp::rpc::Payload>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::Payload> Return::Builder::disownResults() { - KJ_IREQUIRE((which() == Return::RESULTS), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Payload>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Return::Reader::isException() const { - return which() == Return::EXCEPTION; -} -inline bool Return::Builder::isException() { - return which() == Return::EXCEPTION; -} -inline bool Return::Reader::hasException() const { - if (which() != Return::EXCEPTION) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Return::Builder::hasException() { - if (which() != Return::EXCEPTION) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::Exception::Reader Return::Reader::getException() const { - KJ_IREQUIRE((which() == Return::EXCEPTION), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Exception>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::Exception::Builder Return::Builder::getException() { - KJ_IREQUIRE((which() == Return::EXCEPTION), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Exception>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Return::Builder::setException( ::capnp::rpc::Exception::Reader value) { - _builder.setDataField( - ::capnp::bounded<3>() * ::capnp::ELEMENTS, Return::EXCEPTION); - ::capnp::_::PointerHelpers< ::capnp::rpc::Exception>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::Exception::Builder Return::Builder::initException() { - _builder.setDataField( - ::capnp::bounded<3>() * ::capnp::ELEMENTS, Return::EXCEPTION); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Exception>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Return::Builder::adoptException( - ::capnp::Orphan< ::capnp::rpc::Exception>&& value) { - _builder.setDataField( - ::capnp::bounded<3>() * ::capnp::ELEMENTS, Return::EXCEPTION); - ::capnp::_::PointerHelpers< ::capnp::rpc::Exception>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::Exception> Return::Builder::disownException() { - KJ_IREQUIRE((which() == Return::EXCEPTION), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Exception>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Return::Reader::isCanceled() const { - return which() == Return::CANCELED; -} -inline bool Return::Builder::isCanceled() { - return which() == Return::CANCELED; -} -inline ::capnp::Void Return::Reader::getCanceled() const { - KJ_IREQUIRE((which() == Return::CANCELED), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Return::Builder::getCanceled() { - KJ_IREQUIRE((which() == Return::CANCELED), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Return::Builder::setCanceled( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<3>() * ::capnp::ELEMENTS, Return::CANCELED); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Return::Reader::isResultsSentElsewhere() const { - return which() == Return::RESULTS_SENT_ELSEWHERE; -} -inline bool Return::Builder::isResultsSentElsewhere() { - return which() == Return::RESULTS_SENT_ELSEWHERE; -} -inline ::capnp::Void Return::Reader::getResultsSentElsewhere() const { - KJ_IREQUIRE((which() == Return::RESULTS_SENT_ELSEWHERE), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Return::Builder::getResultsSentElsewhere() { - KJ_IREQUIRE((which() == Return::RESULTS_SENT_ELSEWHERE), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Return::Builder::setResultsSentElsewhere( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<3>() * ::capnp::ELEMENTS, Return::RESULTS_SENT_ELSEWHERE); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Return::Reader::isTakeFromOtherQuestion() const { - return which() == Return::TAKE_FROM_OTHER_QUESTION; -} -inline bool Return::Builder::isTakeFromOtherQuestion() { - return which() == Return::TAKE_FROM_OTHER_QUESTION; -} -inline ::uint32_t Return::Reader::getTakeFromOtherQuestion() const { - KJ_IREQUIRE((which() == Return::TAKE_FROM_OTHER_QUESTION), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Return::Builder::getTakeFromOtherQuestion() { - KJ_IREQUIRE((which() == Return::TAKE_FROM_OTHER_QUESTION), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} -inline void Return::Builder::setTakeFromOtherQuestion( ::uint32_t value) { - _builder.setDataField( - ::capnp::bounded<3>() * ::capnp::ELEMENTS, Return::TAKE_FROM_OTHER_QUESTION); - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, value); -} - -inline bool Return::Reader::isAcceptFromThirdParty() const { - return which() == Return::ACCEPT_FROM_THIRD_PARTY; -} -inline bool Return::Builder::isAcceptFromThirdParty() { - return which() == Return::ACCEPT_FROM_THIRD_PARTY; -} -inline bool Return::Reader::hasAcceptFromThirdParty() const { - if (which() != Return::ACCEPT_FROM_THIRD_PARTY) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Return::Builder::hasAcceptFromThirdParty() { - if (which() != Return::ACCEPT_FROM_THIRD_PARTY) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::AnyPointer::Reader Return::Reader::getAcceptFromThirdParty() const { - KJ_IREQUIRE((which() == Return::ACCEPT_FROM_THIRD_PARTY), - "Must check which() before get()ing a union member."); - return ::capnp::AnyPointer::Reader(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Return::Builder::getAcceptFromThirdParty() { - KJ_IREQUIRE((which() == Return::ACCEPT_FROM_THIRD_PARTY), - "Must check which() before get()ing a union member."); - return ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Return::Builder::initAcceptFromThirdParty() { - _builder.setDataField( - ::capnp::bounded<3>() * ::capnp::ELEMENTS, Return::ACCEPT_FROM_THIRD_PARTY); - auto result = ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); - result.clear(); - return result; -} - -inline ::uint32_t Finish::Reader::getQuestionId() const { - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Finish::Builder::getQuestionId() { - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Finish::Builder::setQuestionId( ::uint32_t value) { - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Finish::Reader::getReleaseResultCaps() const { - return _reader.getDataField( - ::capnp::bounded<32>() * ::capnp::ELEMENTS, true); -} - -inline bool Finish::Builder::getReleaseResultCaps() { - return _builder.getDataField( - ::capnp::bounded<32>() * ::capnp::ELEMENTS, true); -} -inline void Finish::Builder::setReleaseResultCaps(bool value) { - _builder.setDataField( - ::capnp::bounded<32>() * ::capnp::ELEMENTS, value, true); -} - -inline ::capnp::rpc::Resolve::Which Resolve::Reader::which() const { - return _reader.getDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} -inline ::capnp::rpc::Resolve::Which Resolve::Builder::which() { - return _builder.getDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Resolve::Reader::getPromiseId() const { - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Resolve::Builder::getPromiseId() { - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Resolve::Builder::setPromiseId( ::uint32_t value) { - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Resolve::Reader::isCap() const { - return which() == Resolve::CAP; -} -inline bool Resolve::Builder::isCap() { - return which() == Resolve::CAP; -} -inline bool Resolve::Reader::hasCap() const { - if (which() != Resolve::CAP) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Resolve::Builder::hasCap() { - if (which() != Resolve::CAP) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::CapDescriptor::Reader Resolve::Reader::getCap() const { - KJ_IREQUIRE((which() == Resolve::CAP), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::CapDescriptor>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::CapDescriptor::Builder Resolve::Builder::getCap() { - KJ_IREQUIRE((which() == Resolve::CAP), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::CapDescriptor>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Resolve::Builder::setCap( ::capnp::rpc::CapDescriptor::Reader value) { - _builder.setDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, Resolve::CAP); - ::capnp::_::PointerHelpers< ::capnp::rpc::CapDescriptor>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::CapDescriptor::Builder Resolve::Builder::initCap() { - _builder.setDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, Resolve::CAP); - return ::capnp::_::PointerHelpers< ::capnp::rpc::CapDescriptor>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Resolve::Builder::adoptCap( - ::capnp::Orphan< ::capnp::rpc::CapDescriptor>&& value) { - _builder.setDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, Resolve::CAP); - ::capnp::_::PointerHelpers< ::capnp::rpc::CapDescriptor>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::CapDescriptor> Resolve::Builder::disownCap() { - KJ_IREQUIRE((which() == Resolve::CAP), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::CapDescriptor>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Resolve::Reader::isException() const { - return which() == Resolve::EXCEPTION; -} -inline bool Resolve::Builder::isException() { - return which() == Resolve::EXCEPTION; -} -inline bool Resolve::Reader::hasException() const { - if (which() != Resolve::EXCEPTION) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Resolve::Builder::hasException() { - if (which() != Resolve::EXCEPTION) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::Exception::Reader Resolve::Reader::getException() const { - KJ_IREQUIRE((which() == Resolve::EXCEPTION), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Exception>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::Exception::Builder Resolve::Builder::getException() { - KJ_IREQUIRE((which() == Resolve::EXCEPTION), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Exception>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Resolve::Builder::setException( ::capnp::rpc::Exception::Reader value) { - _builder.setDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, Resolve::EXCEPTION); - ::capnp::_::PointerHelpers< ::capnp::rpc::Exception>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::Exception::Builder Resolve::Builder::initException() { - _builder.setDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, Resolve::EXCEPTION); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Exception>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Resolve::Builder::adoptException( - ::capnp::Orphan< ::capnp::rpc::Exception>&& value) { - _builder.setDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, Resolve::EXCEPTION); - ::capnp::_::PointerHelpers< ::capnp::rpc::Exception>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::Exception> Resolve::Builder::disownException() { - KJ_IREQUIRE((which() == Resolve::EXCEPTION), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::Exception>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline ::uint32_t Release::Reader::getId() const { - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Release::Builder::getId() { - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Release::Builder::setId( ::uint32_t value) { - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline ::uint32_t Release::Reader::getReferenceCount() const { - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Release::Builder::getReferenceCount() { - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void Release::Builder::setReferenceCount( ::uint32_t value) { - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline bool Disembargo::Reader::hasTarget() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Disembargo::Builder::hasTarget() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::MessageTarget::Reader Disembargo::Reader::getTarget() const { - return ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::MessageTarget::Builder Disembargo::Builder::getTarget() { - return ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::rpc::MessageTarget::Pipeline Disembargo::Pipeline::getTarget() { - return ::capnp::rpc::MessageTarget::Pipeline(_typeless.getPointerField(0)); -} -#endif // !CAPNP_LITE -inline void Disembargo::Builder::setTarget( ::capnp::rpc::MessageTarget::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::MessageTarget::Builder Disembargo::Builder::initTarget() { - return ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Disembargo::Builder::adoptTarget( - ::capnp::Orphan< ::capnp::rpc::MessageTarget>&& value) { - ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::MessageTarget> Disembargo::Builder::disownTarget() { - return ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline typename Disembargo::Context::Reader Disembargo::Reader::getContext() const { - return typename Disembargo::Context::Reader(_reader); -} -inline typename Disembargo::Context::Builder Disembargo::Builder::getContext() { - return typename Disembargo::Context::Builder(_builder); -} -#if !CAPNP_LITE -inline typename Disembargo::Context::Pipeline Disembargo::Pipeline::getContext() { - return typename Disembargo::Context::Pipeline(_typeless.noop()); -} -#endif // !CAPNP_LITE -inline typename Disembargo::Context::Builder Disembargo::Builder::initContext() { - _builder.setDataField< ::uint32_t>(::capnp::bounded<0>() * ::capnp::ELEMENTS, 0); - _builder.setDataField< ::uint16_t>(::capnp::bounded<2>() * ::capnp::ELEMENTS, 0); - return typename Disembargo::Context::Builder(_builder); -} -inline ::capnp::rpc::Disembargo::Context::Which Disembargo::Context::Reader::which() const { - return _reader.getDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} -inline ::capnp::rpc::Disembargo::Context::Which Disembargo::Context::Builder::which() { - return _builder.getDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} - -inline bool Disembargo::Context::Reader::isSenderLoopback() const { - return which() == Disembargo::Context::SENDER_LOOPBACK; -} -inline bool Disembargo::Context::Builder::isSenderLoopback() { - return which() == Disembargo::Context::SENDER_LOOPBACK; -} -inline ::uint32_t Disembargo::Context::Reader::getSenderLoopback() const { - KJ_IREQUIRE((which() == Disembargo::Context::SENDER_LOOPBACK), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Disembargo::Context::Builder::getSenderLoopback() { - KJ_IREQUIRE((which() == Disembargo::Context::SENDER_LOOPBACK), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Disembargo::Context::Builder::setSenderLoopback( ::uint32_t value) { - _builder.setDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, Disembargo::Context::SENDER_LOOPBACK); - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Disembargo::Context::Reader::isReceiverLoopback() const { - return which() == Disembargo::Context::RECEIVER_LOOPBACK; -} -inline bool Disembargo::Context::Builder::isReceiverLoopback() { - return which() == Disembargo::Context::RECEIVER_LOOPBACK; -} -inline ::uint32_t Disembargo::Context::Reader::getReceiverLoopback() const { - KJ_IREQUIRE((which() == Disembargo::Context::RECEIVER_LOOPBACK), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Disembargo::Context::Builder::getReceiverLoopback() { - KJ_IREQUIRE((which() == Disembargo::Context::RECEIVER_LOOPBACK), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Disembargo::Context::Builder::setReceiverLoopback( ::uint32_t value) { - _builder.setDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, Disembargo::Context::RECEIVER_LOOPBACK); - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Disembargo::Context::Reader::isAccept() const { - return which() == Disembargo::Context::ACCEPT; -} -inline bool Disembargo::Context::Builder::isAccept() { - return which() == Disembargo::Context::ACCEPT; -} -inline ::capnp::Void Disembargo::Context::Reader::getAccept() const { - KJ_IREQUIRE((which() == Disembargo::Context::ACCEPT), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Disembargo::Context::Builder::getAccept() { - KJ_IREQUIRE((which() == Disembargo::Context::ACCEPT), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Disembargo::Context::Builder::setAccept( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, Disembargo::Context::ACCEPT); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Disembargo::Context::Reader::isProvide() const { - return which() == Disembargo::Context::PROVIDE; -} -inline bool Disembargo::Context::Builder::isProvide() { - return which() == Disembargo::Context::PROVIDE; -} -inline ::uint32_t Disembargo::Context::Reader::getProvide() const { - KJ_IREQUIRE((which() == Disembargo::Context::PROVIDE), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Disembargo::Context::Builder::getProvide() { - KJ_IREQUIRE((which() == Disembargo::Context::PROVIDE), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Disembargo::Context::Builder::setProvide( ::uint32_t value) { - _builder.setDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, Disembargo::Context::PROVIDE); - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline ::uint32_t Provide::Reader::getQuestionId() const { - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Provide::Builder::getQuestionId() { - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Provide::Builder::setQuestionId( ::uint32_t value) { - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Provide::Reader::hasTarget() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Provide::Builder::hasTarget() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::MessageTarget::Reader Provide::Reader::getTarget() const { - return ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::MessageTarget::Builder Provide::Builder::getTarget() { - return ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::rpc::MessageTarget::Pipeline Provide::Pipeline::getTarget() { - return ::capnp::rpc::MessageTarget::Pipeline(_typeless.getPointerField(0)); -} -#endif // !CAPNP_LITE -inline void Provide::Builder::setTarget( ::capnp::rpc::MessageTarget::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::MessageTarget::Builder Provide::Builder::initTarget() { - return ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Provide::Builder::adoptTarget( - ::capnp::Orphan< ::capnp::rpc::MessageTarget>&& value) { - ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::MessageTarget> Provide::Builder::disownTarget() { - return ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Provide::Reader::hasRecipient() const { - return !_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline bool Provide::Builder::hasRecipient() { - return !_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::AnyPointer::Reader Provide::Reader::getRecipient() const { - return ::capnp::AnyPointer::Reader(_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Provide::Builder::getRecipient() { - return ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Provide::Builder::initRecipient() { - auto result = ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); - result.clear(); - return result; -} - -inline ::uint32_t Accept::Reader::getQuestionId() const { - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Accept::Builder::getQuestionId() { - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Accept::Builder::setQuestionId( ::uint32_t value) { - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Accept::Reader::hasProvision() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Accept::Builder::hasProvision() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::AnyPointer::Reader Accept::Reader::getProvision() const { - return ::capnp::AnyPointer::Reader(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Accept::Builder::getProvision() { - return ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Accept::Builder::initProvision() { - auto result = ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); - result.clear(); - return result; -} - -inline bool Accept::Reader::getEmbargo() const { - return _reader.getDataField( - ::capnp::bounded<32>() * ::capnp::ELEMENTS); -} - -inline bool Accept::Builder::getEmbargo() { - return _builder.getDataField( - ::capnp::bounded<32>() * ::capnp::ELEMENTS); -} -inline void Accept::Builder::setEmbargo(bool value) { - _builder.setDataField( - ::capnp::bounded<32>() * ::capnp::ELEMENTS, value); -} - -inline ::uint32_t Join::Reader::getQuestionId() const { - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Join::Builder::getQuestionId() { - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Join::Builder::setQuestionId( ::uint32_t value) { - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Join::Reader::hasTarget() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Join::Builder::hasTarget() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::MessageTarget::Reader Join::Reader::getTarget() const { - return ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::MessageTarget::Builder Join::Builder::getTarget() { - return ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::rpc::MessageTarget::Pipeline Join::Pipeline::getTarget() { - return ::capnp::rpc::MessageTarget::Pipeline(_typeless.getPointerField(0)); -} -#endif // !CAPNP_LITE -inline void Join::Builder::setTarget( ::capnp::rpc::MessageTarget::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::MessageTarget::Builder Join::Builder::initTarget() { - return ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Join::Builder::adoptTarget( - ::capnp::Orphan< ::capnp::rpc::MessageTarget>&& value) { - ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::MessageTarget> Join::Builder::disownTarget() { - return ::capnp::_::PointerHelpers< ::capnp::rpc::MessageTarget>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Join::Reader::hasKeyPart() const { - return !_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline bool Join::Builder::hasKeyPart() { - return !_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::AnyPointer::Reader Join::Reader::getKeyPart() const { - return ::capnp::AnyPointer::Reader(_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Join::Builder::getKeyPart() { - return ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Join::Builder::initKeyPart() { - auto result = ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); - result.clear(); - return result; -} - -inline ::capnp::rpc::MessageTarget::Which MessageTarget::Reader::which() const { - return _reader.getDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} -inline ::capnp::rpc::MessageTarget::Which MessageTarget::Builder::which() { - return _builder.getDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} - -inline bool MessageTarget::Reader::isImportedCap() const { - return which() == MessageTarget::IMPORTED_CAP; -} -inline bool MessageTarget::Builder::isImportedCap() { - return which() == MessageTarget::IMPORTED_CAP; -} -inline ::uint32_t MessageTarget::Reader::getImportedCap() const { - KJ_IREQUIRE((which() == MessageTarget::IMPORTED_CAP), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t MessageTarget::Builder::getImportedCap() { - KJ_IREQUIRE((which() == MessageTarget::IMPORTED_CAP), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void MessageTarget::Builder::setImportedCap( ::uint32_t value) { - _builder.setDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, MessageTarget::IMPORTED_CAP); - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool MessageTarget::Reader::isPromisedAnswer() const { - return which() == MessageTarget::PROMISED_ANSWER; -} -inline bool MessageTarget::Builder::isPromisedAnswer() { - return which() == MessageTarget::PROMISED_ANSWER; -} -inline bool MessageTarget::Reader::hasPromisedAnswer() const { - if (which() != MessageTarget::PROMISED_ANSWER) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool MessageTarget::Builder::hasPromisedAnswer() { - if (which() != MessageTarget::PROMISED_ANSWER) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::PromisedAnswer::Reader MessageTarget::Reader::getPromisedAnswer() const { - KJ_IREQUIRE((which() == MessageTarget::PROMISED_ANSWER), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::PromisedAnswer>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::PromisedAnswer::Builder MessageTarget::Builder::getPromisedAnswer() { - KJ_IREQUIRE((which() == MessageTarget::PROMISED_ANSWER), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::PromisedAnswer>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void MessageTarget::Builder::setPromisedAnswer( ::capnp::rpc::PromisedAnswer::Reader value) { - _builder.setDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, MessageTarget::PROMISED_ANSWER); - ::capnp::_::PointerHelpers< ::capnp::rpc::PromisedAnswer>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::PromisedAnswer::Builder MessageTarget::Builder::initPromisedAnswer() { - _builder.setDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, MessageTarget::PROMISED_ANSWER); - return ::capnp::_::PointerHelpers< ::capnp::rpc::PromisedAnswer>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void MessageTarget::Builder::adoptPromisedAnswer( - ::capnp::Orphan< ::capnp::rpc::PromisedAnswer>&& value) { - _builder.setDataField( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, MessageTarget::PROMISED_ANSWER); - ::capnp::_::PointerHelpers< ::capnp::rpc::PromisedAnswer>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::PromisedAnswer> MessageTarget::Builder::disownPromisedAnswer() { - KJ_IREQUIRE((which() == MessageTarget::PROMISED_ANSWER), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::PromisedAnswer>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Payload::Reader::hasContent() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Payload::Builder::hasContent() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::AnyPointer::Reader Payload::Reader::getContent() const { - return ::capnp::AnyPointer::Reader(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Payload::Builder::getContent() { - return ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Payload::Builder::initContent() { - auto result = ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); - result.clear(); - return result; -} - -inline bool Payload::Reader::hasCapTable() const { - return !_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline bool Payload::Builder::hasCapTable() { - return !_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::rpc::CapDescriptor>::Reader Payload::Reader::getCapTable() const { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::rpc::CapDescriptor>>::get(_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::rpc::CapDescriptor>::Builder Payload::Builder::getCapTable() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::rpc::CapDescriptor>>::get(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline void Payload::Builder::setCapTable( ::capnp::List< ::capnp::rpc::CapDescriptor>::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::rpc::CapDescriptor>>::set(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::rpc::CapDescriptor>::Builder Payload::Builder::initCapTable(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::rpc::CapDescriptor>>::init(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), size); -} -inline void Payload::Builder::adoptCapTable( - ::capnp::Orphan< ::capnp::List< ::capnp::rpc::CapDescriptor>>&& value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::rpc::CapDescriptor>>::adopt(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::rpc::CapDescriptor>> Payload::Builder::disownCapTable() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::rpc::CapDescriptor>>::disown(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} - -inline ::capnp::rpc::CapDescriptor::Which CapDescriptor::Reader::which() const { - return _reader.getDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline ::capnp::rpc::CapDescriptor::Which CapDescriptor::Builder::which() { - return _builder.getDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline bool CapDescriptor::Reader::isNone() const { - return which() == CapDescriptor::NONE; -} -inline bool CapDescriptor::Builder::isNone() { - return which() == CapDescriptor::NONE; -} -inline ::capnp::Void CapDescriptor::Reader::getNone() const { - KJ_IREQUIRE((which() == CapDescriptor::NONE), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void CapDescriptor::Builder::getNone() { - KJ_IREQUIRE((which() == CapDescriptor::NONE), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void CapDescriptor::Builder::setNone( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, CapDescriptor::NONE); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool CapDescriptor::Reader::isSenderHosted() const { - return which() == CapDescriptor::SENDER_HOSTED; -} -inline bool CapDescriptor::Builder::isSenderHosted() { - return which() == CapDescriptor::SENDER_HOSTED; -} -inline ::uint32_t CapDescriptor::Reader::getSenderHosted() const { - KJ_IREQUIRE((which() == CapDescriptor::SENDER_HOSTED), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t CapDescriptor::Builder::getSenderHosted() { - KJ_IREQUIRE((which() == CapDescriptor::SENDER_HOSTED), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void CapDescriptor::Builder::setSenderHosted( ::uint32_t value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, CapDescriptor::SENDER_HOSTED); - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline bool CapDescriptor::Reader::isSenderPromise() const { - return which() == CapDescriptor::SENDER_PROMISE; -} -inline bool CapDescriptor::Builder::isSenderPromise() { - return which() == CapDescriptor::SENDER_PROMISE; -} -inline ::uint32_t CapDescriptor::Reader::getSenderPromise() const { - KJ_IREQUIRE((which() == CapDescriptor::SENDER_PROMISE), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t CapDescriptor::Builder::getSenderPromise() { - KJ_IREQUIRE((which() == CapDescriptor::SENDER_PROMISE), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void CapDescriptor::Builder::setSenderPromise( ::uint32_t value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, CapDescriptor::SENDER_PROMISE); - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline bool CapDescriptor::Reader::isReceiverHosted() const { - return which() == CapDescriptor::RECEIVER_HOSTED; -} -inline bool CapDescriptor::Builder::isReceiverHosted() { - return which() == CapDescriptor::RECEIVER_HOSTED; -} -inline ::uint32_t CapDescriptor::Reader::getReceiverHosted() const { - KJ_IREQUIRE((which() == CapDescriptor::RECEIVER_HOSTED), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t CapDescriptor::Builder::getReceiverHosted() { - KJ_IREQUIRE((which() == CapDescriptor::RECEIVER_HOSTED), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void CapDescriptor::Builder::setReceiverHosted( ::uint32_t value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, CapDescriptor::RECEIVER_HOSTED); - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline bool CapDescriptor::Reader::isReceiverAnswer() const { - return which() == CapDescriptor::RECEIVER_ANSWER; -} -inline bool CapDescriptor::Builder::isReceiverAnswer() { - return which() == CapDescriptor::RECEIVER_ANSWER; -} -inline bool CapDescriptor::Reader::hasReceiverAnswer() const { - if (which() != CapDescriptor::RECEIVER_ANSWER) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool CapDescriptor::Builder::hasReceiverAnswer() { - if (which() != CapDescriptor::RECEIVER_ANSWER) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::PromisedAnswer::Reader CapDescriptor::Reader::getReceiverAnswer() const { - KJ_IREQUIRE((which() == CapDescriptor::RECEIVER_ANSWER), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::PromisedAnswer>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::PromisedAnswer::Builder CapDescriptor::Builder::getReceiverAnswer() { - KJ_IREQUIRE((which() == CapDescriptor::RECEIVER_ANSWER), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::PromisedAnswer>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void CapDescriptor::Builder::setReceiverAnswer( ::capnp::rpc::PromisedAnswer::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, CapDescriptor::RECEIVER_ANSWER); - ::capnp::_::PointerHelpers< ::capnp::rpc::PromisedAnswer>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::PromisedAnswer::Builder CapDescriptor::Builder::initReceiverAnswer() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, CapDescriptor::RECEIVER_ANSWER); - return ::capnp::_::PointerHelpers< ::capnp::rpc::PromisedAnswer>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void CapDescriptor::Builder::adoptReceiverAnswer( - ::capnp::Orphan< ::capnp::rpc::PromisedAnswer>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, CapDescriptor::RECEIVER_ANSWER); - ::capnp::_::PointerHelpers< ::capnp::rpc::PromisedAnswer>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::PromisedAnswer> CapDescriptor::Builder::disownReceiverAnswer() { - KJ_IREQUIRE((which() == CapDescriptor::RECEIVER_ANSWER), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::PromisedAnswer>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool CapDescriptor::Reader::isThirdPartyHosted() const { - return which() == CapDescriptor::THIRD_PARTY_HOSTED; -} -inline bool CapDescriptor::Builder::isThirdPartyHosted() { - return which() == CapDescriptor::THIRD_PARTY_HOSTED; -} -inline bool CapDescriptor::Reader::hasThirdPartyHosted() const { - if (which() != CapDescriptor::THIRD_PARTY_HOSTED) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool CapDescriptor::Builder::hasThirdPartyHosted() { - if (which() != CapDescriptor::THIRD_PARTY_HOSTED) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::rpc::ThirdPartyCapDescriptor::Reader CapDescriptor::Reader::getThirdPartyHosted() const { - KJ_IREQUIRE((which() == CapDescriptor::THIRD_PARTY_HOSTED), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::ThirdPartyCapDescriptor>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::rpc::ThirdPartyCapDescriptor::Builder CapDescriptor::Builder::getThirdPartyHosted() { - KJ_IREQUIRE((which() == CapDescriptor::THIRD_PARTY_HOSTED), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::ThirdPartyCapDescriptor>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void CapDescriptor::Builder::setThirdPartyHosted( ::capnp::rpc::ThirdPartyCapDescriptor::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, CapDescriptor::THIRD_PARTY_HOSTED); - ::capnp::_::PointerHelpers< ::capnp::rpc::ThirdPartyCapDescriptor>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::rpc::ThirdPartyCapDescriptor::Builder CapDescriptor::Builder::initThirdPartyHosted() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, CapDescriptor::THIRD_PARTY_HOSTED); - return ::capnp::_::PointerHelpers< ::capnp::rpc::ThirdPartyCapDescriptor>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void CapDescriptor::Builder::adoptThirdPartyHosted( - ::capnp::Orphan< ::capnp::rpc::ThirdPartyCapDescriptor>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, CapDescriptor::THIRD_PARTY_HOSTED); - ::capnp::_::PointerHelpers< ::capnp::rpc::ThirdPartyCapDescriptor>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::rpc::ThirdPartyCapDescriptor> CapDescriptor::Builder::disownThirdPartyHosted() { - KJ_IREQUIRE((which() == CapDescriptor::THIRD_PARTY_HOSTED), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::rpc::ThirdPartyCapDescriptor>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline ::uint32_t PromisedAnswer::Reader::getQuestionId() const { - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t PromisedAnswer::Builder::getQuestionId() { - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void PromisedAnswer::Builder::setQuestionId( ::uint32_t value) { - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool PromisedAnswer::Reader::hasTransform() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool PromisedAnswer::Builder::hasTransform() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::rpc::PromisedAnswer::Op>::Reader PromisedAnswer::Reader::getTransform() const { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::rpc::PromisedAnswer::Op>>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::rpc::PromisedAnswer::Op>::Builder PromisedAnswer::Builder::getTransform() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::rpc::PromisedAnswer::Op>>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void PromisedAnswer::Builder::setTransform( ::capnp::List< ::capnp::rpc::PromisedAnswer::Op>::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::rpc::PromisedAnswer::Op>>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::rpc::PromisedAnswer::Op>::Builder PromisedAnswer::Builder::initTransform(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::rpc::PromisedAnswer::Op>>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void PromisedAnswer::Builder::adoptTransform( - ::capnp::Orphan< ::capnp::List< ::capnp::rpc::PromisedAnswer::Op>>&& value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::rpc::PromisedAnswer::Op>>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::rpc::PromisedAnswer::Op>> PromisedAnswer::Builder::disownTransform() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::rpc::PromisedAnswer::Op>>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline ::capnp::rpc::PromisedAnswer::Op::Which PromisedAnswer::Op::Reader::which() const { - return _reader.getDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline ::capnp::rpc::PromisedAnswer::Op::Which PromisedAnswer::Op::Builder::which() { - return _builder.getDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline bool PromisedAnswer::Op::Reader::isNoop() const { - return which() == PromisedAnswer::Op::NOOP; -} -inline bool PromisedAnswer::Op::Builder::isNoop() { - return which() == PromisedAnswer::Op::NOOP; -} -inline ::capnp::Void PromisedAnswer::Op::Reader::getNoop() const { - KJ_IREQUIRE((which() == PromisedAnswer::Op::NOOP), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void PromisedAnswer::Op::Builder::getNoop() { - KJ_IREQUIRE((which() == PromisedAnswer::Op::NOOP), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void PromisedAnswer::Op::Builder::setNoop( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, PromisedAnswer::Op::NOOP); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool PromisedAnswer::Op::Reader::isGetPointerField() const { - return which() == PromisedAnswer::Op::GET_POINTER_FIELD; -} -inline bool PromisedAnswer::Op::Builder::isGetPointerField() { - return which() == PromisedAnswer::Op::GET_POINTER_FIELD; -} -inline ::uint16_t PromisedAnswer::Op::Reader::getGetPointerField() const { - KJ_IREQUIRE((which() == PromisedAnswer::Op::GET_POINTER_FIELD), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::uint16_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline ::uint16_t PromisedAnswer::Op::Builder::getGetPointerField() { - KJ_IREQUIRE((which() == PromisedAnswer::Op::GET_POINTER_FIELD), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::uint16_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void PromisedAnswer::Op::Builder::setGetPointerField( ::uint16_t value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, PromisedAnswer::Op::GET_POINTER_FIELD); - _builder.setDataField< ::uint16_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline bool ThirdPartyCapDescriptor::Reader::hasId() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool ThirdPartyCapDescriptor::Builder::hasId() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::AnyPointer::Reader ThirdPartyCapDescriptor::Reader::getId() const { - return ::capnp::AnyPointer::Reader(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder ThirdPartyCapDescriptor::Builder::getId() { - return ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder ThirdPartyCapDescriptor::Builder::initId() { - auto result = ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); - result.clear(); - return result; -} - -inline ::uint32_t ThirdPartyCapDescriptor::Reader::getVineId() const { - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t ThirdPartyCapDescriptor::Builder::getVineId() { - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void ThirdPartyCapDescriptor::Builder::setVineId( ::uint32_t value) { - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Exception::Reader::hasReason() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Exception::Builder::hasReason() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::Text::Reader Exception::Reader::getReason() const { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::Text::Builder Exception::Builder::getReason() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Exception::Builder::setReason( ::capnp::Text::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::Text::Builder Exception::Builder::initReason(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void Exception::Builder::adoptReason( - ::capnp::Orphan< ::capnp::Text>&& value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::Text> Exception::Builder::disownReason() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Exception::Reader::getObsoleteIsCallersFault() const { - return _reader.getDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline bool Exception::Builder::getObsoleteIsCallersFault() { - return _builder.getDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Exception::Builder::setObsoleteIsCallersFault(bool value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline ::uint16_t Exception::Reader::getObsoleteDurability() const { - return _reader.getDataField< ::uint16_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline ::uint16_t Exception::Builder::getObsoleteDurability() { - return _builder.getDataField< ::uint16_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void Exception::Builder::setObsoleteDurability( ::uint16_t value) { - _builder.setDataField< ::uint16_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline ::capnp::rpc::Exception::Type Exception::Reader::getType() const { - return _reader.getDataField< ::capnp::rpc::Exception::Type>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} - -inline ::capnp::rpc::Exception::Type Exception::Builder::getType() { - return _builder.getDataField< ::capnp::rpc::Exception::Type>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} -inline void Exception::Builder::setType( ::capnp::rpc::Exception::Type value) { - _builder.setDataField< ::capnp::rpc::Exception::Type>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, value); -} - -} // namespace -} // namespace - -#endif // CAPNP_INCLUDED_b312981b2552a250_ diff --git a/phonelibs/capnp-cpp/include/capnp/rpc.h b/phonelibs/capnp-cpp/include/capnp/rpc.h deleted file mode 100644 index d84ed982e7..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/rpc.h +++ /dev/null @@ -1,537 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_RPC_H_ -#define CAPNP_RPC_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include "capability.h" -#include "rpc-prelude.h" - -namespace capnp { - -template -class VatNetwork; -template -class SturdyRefRestorer; - -template -class BootstrapFactory: public _::BootstrapFactoryBase { - // Interface that constructs per-client bootstrap interfaces. Use this if you want each client - // who connects to see a different bootstrap interface based on their (authenticated) VatId. - // This allows an application to bootstrap off of the authentication performed at the VatNetwork - // level. (Typically VatId is some sort of public key.) - // - // This is only useful for multi-party networks. For TwoPartyVatNetwork, there's no reason to - // use a BootstrapFactory; just specify a single bootstrap capability in this case. - -public: - virtual Capability::Client createFor(typename VatId::Reader clientId) = 0; - // Create a bootstrap capability appropriate for exposing to the given client. VatNetwork will - // have authenticated the client VatId before this is called. - -private: - Capability::Client baseCreateFor(AnyStruct::Reader clientId) override; -}; - -template -class RpcSystem: public _::RpcSystemBase { - // Represents the RPC system, which is the portal to objects available on the network. - // - // The RPC implementation sits on top of an implementation of `VatNetwork`. The `VatNetwork` - // determines how to form connections between vats -- specifically, two-way, private, reliable, - // sequenced datagram connections. The RPC implementation determines how to use such connections - // to manage object references and make method calls. - // - // See `makeRpcServer()` and `makeRpcClient()` below for convenient syntax for setting up an - // `RpcSystem` given a `VatNetwork`. - // - // See `ez-rpc.h` for an even simpler interface for setting up RPC in a typical two-party - // client/server scenario. - -public: - template - RpcSystem( - VatNetwork& network, - kj::Maybe bootstrapInterface, - kj::Maybe::Client> gateway = nullptr); - - template - RpcSystem( - VatNetwork& network, - BootstrapFactory& bootstrapFactory, - kj::Maybe::Client> gateway = nullptr); - - template - RpcSystem( - VatNetwork& network, - SturdyRefRestorer& restorer); - - RpcSystem(RpcSystem&& other) = default; - - Capability::Client bootstrap(typename VatId::Reader vatId); - // Connect to the given vat and return its bootstrap interface. - - Capability::Client restore(typename VatId::Reader hostId, AnyPointer::Reader objectId) - KJ_DEPRECATED("Please transition to using a bootstrap interface instead."); - // ** DEPRECATED ** - // - // Restores the given SturdyRef from the network and return the capability representing it. - // - // `hostId` identifies the host from which to request the ref, in the format specified by the - // `VatNetwork` in use. `objectId` is the object ID in whatever format is expected by said host. - // - // This method will be removed in a future version of Cap'n Proto. Instead, please transition - // to using bootstrap(), which is equivalent to calling restore() with a null `objectId`. - // You may emulate the old concept of object IDs by exporting a bootstrap interface which has - // methods that can be used to obtain other capabilities by ID. - - void setFlowLimit(size_t words); - // Sets the incoming call flow limit. If more than `words` worth of call messages have not yet - // received responses, the RpcSystem will not read further messages from the stream. This can be - // used as a crude way to prevent a resource exhaustion attack (or bug) in which a peer makes an - // excessive number of simultaneous calls that consume the receiver's RAM. - // - // There are some caveats. When over the flow limit, all messages are blocked, including returns. - // If the outstanding calls are themselves waiting on calls going in the opposite direction, the - // flow limit may prevent those calls from completing, leading to deadlock. However, a - // sufficiently high limit should make this unlikely. - // - // Note that a call's parameter size counts against the flow limit until the call returns, even - // if the recipient calls releaseParams() to free the parameter memory early. This is because - // releaseParams() may simply indicate that the parameters have been forwarded to another - // machine, but are still in-memory there. For illustration, say that Alice made a call to Bob - // who forwarded the call to Carol. Bob has imposed a flow limit on Alice. Alice's calls are - // being forwarded to Carol, so Bob never keeps the parameters in-memory for more than a brief - // period. However, the flow limit counts all calls that haven't returned, even if Bob has - // already freed the memory they consumed. You might argue that the right solution here is - // instead for Carol to impose her own flow limit on Bob. This has a serious problem, though: - // Bob might be forwarding requests to Carol on behalf of many different parties, not just Alice. - // If Alice can pump enough data to hit the Bob -> Carol flow limit, then those other parties - // will be disrupted. Thus, we can only really impose the limit on the Alice -> Bob link, which - // only affects Alice. We need that one flow limit to limit Alice's impact on the whole system, - // so it has to count all in-flight calls. - // - // In Sandstorm, flow limits are imposed by the supervisor on calls coming out of a grain, in - // order to prevent a grain from inundating the system with in-flight calls. In practice, the - // main time this happens is when a grain is pushing a large file download and doesn't implement - // proper cooperative flow control. -}; - -template -RpcSystem makeRpcServer( - VatNetwork& network, - Capability::Client bootstrapInterface); -// Make an RPC server. Typical usage (e.g. in a main() function): -// -// MyEventLoop eventLoop; -// kj::WaitScope waitScope(eventLoop); -// MyNetwork network; -// MyMainInterface::Client bootstrap = makeMain(); -// auto server = makeRpcServer(network, bootstrap); -// kj::NEVER_DONE.wait(waitScope); // run forever -// -// See also ez-rpc.h, which has simpler instructions for the common case of a two-party -// client-server RPC connection. - -template , - typename ExternalRef = _::ExternalRefFromRealmGatewayClient> -RpcSystem makeRpcServer( - VatNetwork& network, - Capability::Client bootstrapInterface, RealmGatewayClient gateway); -// Make an RPC server for a VatNetwork that resides in a different realm from the application. -// The given RealmGateway is used to translate SturdyRefs between the app's ("internal") format -// and the network's ("external") format. - -template -RpcSystem makeRpcServer( - VatNetwork& network, - BootstrapFactory& bootstrapFactory); -// Make an RPC server that can serve different bootstrap interfaces to different clients via a -// BootstrapInterface. - -template , - typename ExternalRef = _::ExternalRefFromRealmGatewayClient> -RpcSystem makeRpcServer( - VatNetwork& network, - BootstrapFactory& bootstrapFactory, RealmGatewayClient gateway); -// Make an RPC server that can serve different bootstrap interfaces to different clients via a -// BootstrapInterface and communicates with a different realm than the application is in via a -// RealmGateway. - -template -RpcSystem makeRpcServer( - VatNetwork& network, - SturdyRefRestorer& restorer) - KJ_DEPRECATED("Please transition to using a bootstrap interface instead."); -// ** DEPRECATED ** -// -// Create an RPC server which exports multiple main interfaces by object ID. The `restorer` object -// can be used to look up objects by ID. -// -// Please transition to exporting only one interface, which is known as the "bootstrap" interface. -// For backwards-compatibility with old clients, continue to implement SturdyRefRestorer, but -// return the new bootstrap interface when the request object ID is null. When new clients connect -// and request the bootstrap interface, they will get that interface. Eventually, once all clients -// are updated to request only the bootstrap interface, stop implementing SturdyRefRestorer and -// switch to passing the bootstrap capability itself as the second parameter to `makeRpcServer()`. - -template -RpcSystem makeRpcClient( - VatNetwork& network); -// Make an RPC client. Typical usage (e.g. in a main() function): -// -// MyEventLoop eventLoop; -// kj::WaitScope waitScope(eventLoop); -// MyNetwork network; -// auto client = makeRpcClient(network); -// MyCapability::Client cap = client.restore(hostId, objId).castAs(); -// auto response = cap.fooRequest().send().wait(waitScope); -// handleMyResponse(response); -// -// See also ez-rpc.h, which has simpler instructions for the common case of a two-party -// client-server RPC connection. - -template , - typename ExternalRef = _::ExternalRefFromRealmGatewayClient> -RpcSystem makeRpcClient( - VatNetwork& network, - RealmGatewayClient gateway); -// Make an RPC client for a VatNetwork that resides in a different realm from the application. -// The given RealmGateway is used to translate SturdyRefs between the app's ("internal") format -// and the network's ("external") format. - -template -class SturdyRefRestorer: public _::SturdyRefRestorerBase { - // ** DEPRECATED ** - // - // In Cap'n Proto 0.4.x, applications could export multiple main interfaces identified by - // object IDs. The callback used to map object IDs to objects was `SturdyRefRestorer`, as we - // imagined this would eventually be used for restoring SturdyRefs as well. In practice, it was - // never used for real SturdyRefs, only for exporting singleton objects under well-known names. - // - // The new preferred strategy is to export only a _single_ such interface, called the - // "bootstrap interface". That interface can itself have methods for obtaining other objects, of - // course, but that is up to the app. `SturdyRefRestorer` exists for backwards-compatibility. - // - // Hint: Use SturdyRefRestorer to define a server that exports services under - // string names. - -public: - virtual Capability::Client restore(typename SturdyRefObjectId::Reader ref) - KJ_DEPRECATED( - "Please transition to using bootstrap interfaces instead of SturdyRefRestorer.") = 0; - // Restore the given object, returning a capability representing it. - -private: - Capability::Client baseRestore(AnyPointer::Reader ref) override final; -}; - -// ======================================================================================= -// VatNetwork - -class OutgoingRpcMessage { - // A message to be sent by a `VatNetwork`. - -public: - virtual AnyPointer::Builder getBody() = 0; - // Get the message body, which the caller may fill in any way it wants. (The standard RPC - // implementation initializes it as a Message as defined in rpc.capnp.) - - virtual void send() = 0; - // Send the message, or at least put it in a queue to be sent later. Note that the builder - // returned by `getBody()` remains valid at least until the `OutgoingRpcMessage` is destroyed. -}; - -class IncomingRpcMessage { - // A message received from a `VatNetwork`. - -public: - virtual AnyPointer::Reader getBody() = 0; - // Get the message body, to be interpreted by the caller. (The standard RPC implementation - // interprets it as a Message as defined in rpc.capnp.) -}; - -template -class VatNetwork: public _::VatNetworkBase { - // Cap'n Proto RPC operates between vats, where a "vat" is some sort of host of objects. - // Typically one Cap'n Proto process (in the Unix sense) is one vat. The RPC system is what - // allows calls between objects hosted in different vats. - // - // The RPC implementation sits on top of an implementation of `VatNetwork`. The `VatNetwork` - // determines how to form connections between vats -- specifically, two-way, private, reliable, - // sequenced datagram connections. The RPC implementation determines how to use such connections - // to manage object references and make method calls. - // - // The most common implementation of VatNetwork is TwoPartyVatNetwork (rpc-twoparty.h). Most - // simple client-server apps will want to use it. (You may even want to use the EZ RPC - // interfaces in `ez-rpc.h` and avoid all of this.) - // - // TODO(someday): Provide a standard implementation for the public internet. - -public: - class Connection; - - struct ConnectionAndProvisionId { - // Result of connecting to a vat introduced by another vat. - - kj::Own connection; - // Connection to the new vat. - - kj::Own firstMessage; - // An already-allocated `OutgoingRpcMessage` associated with `connection`. The RPC system will - // construct this as an `Accept` message and send it. - - Orphan provisionId; - // A `ProvisionId` already allocated inside `firstMessage`, which the RPC system will use to - // build the `Accept` message. - }; - - class Connection: public _::VatNetworkBase::Connection { - // A two-way RPC connection. - // - // This object may represent a connection that doesn't exist yet, but is expected to exist - // in the future. In this case, sent messages will automatically be queued and sent once the - // connection is ready, so that the caller doesn't need to know the difference. - - public: - // Level 0 features ---------------------------------------------- - - virtual typename VatId::Reader getPeerVatId() = 0; - // Returns the connected vat's authenticated VatId. It is the VatNetwork's responsibility to - // authenticate this, so that the caller can be assured that they are really talking to the - // identified vat and not an imposter. - - virtual kj::Own newOutgoingMessage(uint firstSegmentWordSize) override = 0; - // Allocate a new message to be sent on this connection. - // - // If `firstSegmentWordSize` is non-zero, it should be treated as a hint suggesting how large - // to make the first segment. This is entirely a hint and the connection may adjust it up or - // down. If it is zero, the connection should choose the size itself. - - virtual kj::Promise>> receiveIncomingMessage() override = 0; - // Wait for a message to be received and return it. If the read stream cleanly terminates, - // return null. If any other problem occurs, throw an exception. - - virtual kj::Promise shutdown() override KJ_WARN_UNUSED_RESULT = 0; - // Waits until all outgoing messages have been sent, then shuts down the outgoing stream. The - // returned promise resolves after shutdown is complete. - - private: - AnyStruct::Reader baseGetPeerVatId() override; - }; - - // Level 0 features ------------------------------------------------ - - virtual kj::Maybe> connect(typename VatId::Reader hostId) = 0; - // Connect to a VatId. Note that this method immediately returns a `Connection`, even - // if the network connection has not yet been established. Messages can be queued to this - // connection and will be delivered once it is open. The caller must attempt to read from the - // connection to verify that it actually succeeded; the read will fail if the connection - // couldn't be opened. Some network implementations may actually start sending messages before - // hearing back from the server at all, to avoid a round trip. - // - // Returns nullptr if `hostId` refers to the local host. - - virtual kj::Promise> accept() = 0; - // Wait for the next incoming connection and return it. - - // Level 4 features ------------------------------------------------ - // TODO(someday) - -private: - kj::Maybe> - baseConnect(AnyStruct::Reader hostId) override final; - kj::Promise> baseAccept() override final; -}; - -// ======================================================================================= -// *************************************************************************************** -// Inline implementation details start here -// *************************************************************************************** -// ======================================================================================= - -template -Capability::Client BootstrapFactory::baseCreateFor(AnyStruct::Reader clientId) { - return createFor(clientId.as()); -} - -template -kj::Maybe> - VatNetwork:: - baseConnect(AnyStruct::Reader ref) { - auto maybe = connect(ref.as()); - return maybe.map([](kj::Own& conn) -> kj::Own<_::VatNetworkBase::Connection> { - return kj::mv(conn); - }); -} - -template -kj::Promise> - VatNetwork::baseAccept() { - return accept().then( - [](kj::Own&& connection) -> kj::Own<_::VatNetworkBase::Connection> { - return kj::mv(connection); - }); -} - -template -AnyStruct::Reader VatNetwork< - SturdyRef, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>:: - Connection::baseGetPeerVatId() { - return getPeerVatId(); -} - -template -Capability::Client SturdyRefRestorer::baseRestore(AnyPointer::Reader ref) { -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wdeprecated-declarations" - return restore(ref.getAs()); -#pragma GCC diagnostic pop -} - -template -template -RpcSystem::RpcSystem( - VatNetwork& network, - kj::Maybe bootstrap, - kj::Maybe::Client> gateway) - : _::RpcSystemBase(network, kj::mv(bootstrap), kj::mv(gateway)) {} - -template -template -RpcSystem::RpcSystem( - VatNetwork& network, - BootstrapFactory& bootstrapFactory, - kj::Maybe::Client> gateway) - : _::RpcSystemBase(network, bootstrapFactory, kj::mv(gateway)) {} - -template -template -RpcSystem::RpcSystem( - VatNetwork& network, - SturdyRefRestorer& restorer) - : _::RpcSystemBase(network, restorer) {} - -template -Capability::Client RpcSystem::bootstrap(typename VatId::Reader vatId) { - return baseBootstrap(_::PointerHelpers::getInternalReader(vatId)); -} - -template -Capability::Client RpcSystem::restore( - typename VatId::Reader hostId, AnyPointer::Reader objectId) { - return baseRestore(_::PointerHelpers::getInternalReader(hostId), objectId); -} - -template -inline void RpcSystem::setFlowLimit(size_t words) { - baseSetFlowLimit(words); -} - -template -RpcSystem makeRpcServer( - VatNetwork& network, - Capability::Client bootstrapInterface) { - return RpcSystem(network, kj::mv(bootstrapInterface)); -} - -template -RpcSystem makeRpcServer( - VatNetwork& network, - Capability::Client bootstrapInterface, RealmGatewayClient gateway) { - return RpcSystem(network, kj::mv(bootstrapInterface), - gateway.template castAs>()); -} - -template -RpcSystem makeRpcServer( - VatNetwork& network, - BootstrapFactory& bootstrapFactory) { - return RpcSystem(network, bootstrapFactory); -} - -template -RpcSystem makeRpcServer( - VatNetwork& network, - BootstrapFactory& bootstrapFactory, RealmGatewayClient gateway) { - return RpcSystem(network, bootstrapFactory, gateway.template castAs>()); -} - -template -RpcSystem makeRpcServer( - VatNetwork& network, - SturdyRefRestorer& restorer) { - return RpcSystem(network, restorer); -} - -template -RpcSystem makeRpcClient( - VatNetwork& network) { - return RpcSystem(network, nullptr); -} - -template -RpcSystem makeRpcClient( - VatNetwork& network, - RealmGatewayClient gateway) { - return RpcSystem(network, nullptr, gateway.template castAs>()); -} - -} // namespace capnp - -#endif // CAPNP_RPC_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/schema-lite.h b/phonelibs/capnp-cpp/include/capnp/schema-lite.h deleted file mode 100644 index 58a8c14c05..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/schema-lite.h +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_SCHEMA_LITE_H_ -#define CAPNP_SCHEMA_LITE_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include -#include "message.h" - -namespace capnp { - -template -inline schema::Node::Reader schemaProto() { - // Get the schema::Node for this type's schema. This function works even in lite mode. - return readMessageUnchecked(CapnpPrivate::encodedSchema()); -} - -template ::typeId> -inline schema::Node::Reader schemaProto() { - // Get the schema::Node for this type's schema. This function works even in lite mode. - return readMessageUnchecked(schemas::EnumInfo::encodedSchema()); -} - -} // namespace capnp - -#endif // CAPNP_SCHEMA_LITE_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/schema-loader.h b/phonelibs/capnp-cpp/include/capnp/schema-loader.h deleted file mode 100644 index 0e34cba77f..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/schema-loader.h +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_SCHEMA_LOADER_H_ -#define CAPNP_SCHEMA_LOADER_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include "schema.h" -#include -#include - -namespace capnp { - -class SchemaLoader { - // Class which can be used to construct Schema objects from schema::Nodes as defined in - // schema.capnp. - // - // It is a bad idea to use this class on untrusted input with exceptions disabled -- you may - // be exposing yourself to denial-of-service attacks, as attackers can easily construct schemas - // that are subtly inconsistent in a way that causes exceptions to be thrown either by - // SchemaLoader or by the dynamic API when the schemas are subsequently used. If you enable and - // properly catch exceptions, you should be OK -- assuming no bugs in the Cap'n Proto - // implementation, of course. - -public: - class LazyLoadCallback { - public: - virtual void load(const SchemaLoader& loader, uint64_t id) const = 0; - // Request that the schema node with the given ID be loaded into the given SchemaLoader. If - // the callback is able to find a schema for this ID, it should invoke `loadOnce()` on - // `loader` to load it. If no such node exists, it should simply do nothing and return. - // - // The callback is allowed to load schema nodes other than the one requested, e.g. because it - // expects they will be needed soon. - // - // If the `SchemaLoader` is used from multiple threads, the callback must be thread-safe. - // In particular, it's possible for multiple threads to invoke `load()` with the same ID. - // If the callback performs a large amount of work to look up IDs, it should be sure to - // de-dup these requests. - }; - - SchemaLoader(); - - SchemaLoader(const LazyLoadCallback& callback); - // Construct a SchemaLoader which will invoke the given callback when a schema node is requested - // that isn't already loaded. - - ~SchemaLoader() noexcept(false); - KJ_DISALLOW_COPY(SchemaLoader); - - Schema get(uint64_t id, schema::Brand::Reader brand = schema::Brand::Reader(), - Schema scope = Schema()) const; - // Gets the schema for the given ID, throwing an exception if it isn't present. - // - // The returned schema may be invalidated if load() is called with a new schema for the same ID. - // In general, you should not call load() while a schema from this loader is in-use. - // - // `brand` and `scope` are used to determine brand bindings where relevant. `brand` gives - // parameter bindings for the target type's brand parameters that were specified at the reference - // site. `scope` specifies the scope in which the type ID appeared -- if `brand` itself contains - // parameter references or indicates that some parameters will be inherited, these will be - // interpreted within / inherited from `scope`. - - kj::Maybe tryGet(uint64_t id, schema::Brand::Reader bindings = schema::Brand::Reader(), - Schema scope = Schema()) const; - // Like get() but doesn't throw. - - Schema getUnbound(uint64_t id) const; - // Gets a special version of the schema in which all brand parameters are "unbound". This means - // that if you look up a type via the Schema API, and it resolves to a brand parameter, the - // returned Type's getBrandParameter() method will return info about that parameter. Otherwise, - // normally, all brand parameters that aren't otherwise bound are assumed to simply be - // "AnyPointer". - - Type getType(schema::Type::Reader type, Schema scope = Schema()) const; - // Convenience method which interprets a schema::Type to produce a Type object. Implemented in - // terms of get(). - - Schema load(const schema::Node::Reader& reader); - // Loads the given schema node. Validates the node and throws an exception if invalid. This - // makes a copy of the schema, so the object passed in can be destroyed after this returns. - // - // If the node has any dependencies which are not already loaded, they will be initialized as - // stubs -- empty schemas of whichever kind is expected. - // - // If another schema for the given reader has already been seen, the loader will inspect both - // schemas to determine which one is newer, and use that that one. If the two versions are - // found to be incompatible, an exception is thrown. If the two versions differ but are - // compatible and the loader cannot determine which is newer (e.g., the only changes are renames), - // the existing schema will be preferred. Note that in any case, the loader will end up keeping - // around copies of both schemas, so you shouldn't repeatedly reload schemas into the same loader. - // - // The following properties of the schema node are validated: - // - Struct size and preferred list encoding are valid and consistent. - // - Struct members are fields or unions. - // - Union members are fields. - // - Field offsets are in-bounds. - // - Ordinals and codeOrders are sequential starting from zero. - // - Values are of the right union case to match their types. - // - // You should assume anything not listed above is NOT validated. In particular, things that are - // not validated now, but could be in the future, include but are not limited to: - // - Names. - // - Annotation values. (This is hard because the annotation declaration is not always - // available.) - // - Content of default/constant values of pointer type. (Validating these would require knowing - // their schema, but even if the schemas are available at validation time, they could be - // updated by a subsequent load(), invalidating existing values. Instead, these values are - // validated at the time they are used, as usual for Cap'n Proto objects.) - // - // Also note that unknown types are not considered invalid. Instead, the dynamic API returns - // a DynamicValue with type UNKNOWN for these. - - Schema loadOnce(const schema::Node::Reader& reader) const; - // Like `load()` but does nothing if a schema with the same ID is already loaded. In contrast, - // `load()` would attempt to compare the schemas and take the newer one. `loadOnce()` is safe - // to call even while concurrently using schemas from this loader. It should be considered an - // error to call `loadOnce()` with two non-identical schemas that share the same ID, although - // this error may or may not actually be detected by the implementation. - - template - void loadCompiledTypeAndDependencies(); - // Load the schema for the given compiled-in type and all of its dependencies. - // - // If you want to be able to cast a DynamicValue built from this SchemaLoader to the compiled-in - // type using as(), you must call this method before constructing the DynamicValue. Otherwise, - // as() will throw an exception complaining about type mismatch. - - kj::Array getAllLoaded() const; - // Get a complete list of all loaded schema nodes. It is particularly useful to call this after - // loadCompiledTypeAndDependencies() in order to get a flat list of all of T's transitive - // dependencies. - -private: - class Validator; - class CompatibilityChecker; - class Impl; - class InitializerImpl; - class BrandedInitializerImpl; - kj::MutexGuarded> impl; - - void loadNative(const _::RawSchema* nativeSchema); -}; - -template -inline void SchemaLoader::loadCompiledTypeAndDependencies() { - loadNative(&_::rawSchema()); -} - -} // namespace capnp - -#endif // CAPNP_SCHEMA_LOADER_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/schema-parser.h b/phonelibs/capnp-cpp/include/capnp/schema-parser.h deleted file mode 100644 index 3322bbfbfb..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/schema-parser.h +++ /dev/null @@ -1,207 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_SCHEMA_PARSER_H_ -#define CAPNP_SCHEMA_PARSER_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include "schema-loader.h" -#include - -namespace capnp { - -class ParsedSchema; -class SchemaFile; - -class SchemaParser { - // Parses `.capnp` files to produce `Schema` objects. - // - // This class is thread-safe, hence all its methods are const. - -public: - SchemaParser(); - ~SchemaParser() noexcept(false); - - ParsedSchema parseDiskFile(kj::StringPtr displayName, kj::StringPtr diskPath, - kj::ArrayPtr importPath) const; - // Parse a file located on disk. Throws an exception if the file dosen't exist. - // - // Parameters: - // * `displayName`: The name that will appear in the file's schema node. (If the file has - // already been parsed, this will be ignored and the display name from the first time it was - // parsed will be kept.) - // * `diskPath`: The path to the file on disk. - // * `importPath`: Directories to search when resolving absolute imports within this file - // (imports that start with a `/`). Must remain valid until the SchemaParser is destroyed. - // (If the file has already been parsed, this will be ignored and the import path from the - // first time it was parsed will be kept.) - // - // This method is a shortcut, equivalent to: - // parser.parseFile(SchemaFile::newDiskFile(displayName, diskPath, importPath))`; - // - // This method throws an exception if any errors are encountered in the file or in anything the - // file depends on. Note that merely importing another file does not count as a dependency on - // anything in the imported file -- only the imported types which are actually used are - // "dependencies". - - ParsedSchema parseFile(kj::Own&& file) const; - // Advanced interface for parsing a file that may or may not be located in any global namespace. - // Most users will prefer `parseDiskFile()`. - // - // If the file has already been parsed (that is, a SchemaFile that compares equal to this one - // was parsed previously), the existing schema will be returned again. - // - // This method reports errors by calling SchemaFile::reportError() on the file where the error - // is located. If that call does not throw an exception, `parseFile()` may in fact return - // normally. In this case, the result is a best-effort attempt to compile the schema, but it - // may be invalid or corrupt, and using it for anything may cause exceptions to be thrown. - - template - inline void loadCompiledTypeAndDependencies() { - // See SchemaLoader::loadCompiledTypeAndDependencies(). - getLoader().loadCompiledTypeAndDependencies(); - } - -private: - struct Impl; - class ModuleImpl; - kj::Own impl; - mutable bool hadErrors = false; - - ModuleImpl& getModuleImpl(kj::Own&& file) const; - SchemaLoader& getLoader(); - - friend class ParsedSchema; -}; - -class ParsedSchema: public Schema { - // ParsedSchema is an extension of Schema which also has the ability to look up nested nodes - // by name. See `SchemaParser`. - -public: - inline ParsedSchema(): parser(nullptr) {} - - kj::Maybe findNested(kj::StringPtr name) const; - // Gets the nested node with the given name, or returns null if there is no such nested - // declaration. - - ParsedSchema getNested(kj::StringPtr name) const; - // Gets the nested node with the given name, or throws an exception if there is no such nested - // declaration. - -private: - inline ParsedSchema(Schema inner, const SchemaParser& parser): Schema(inner), parser(&parser) {} - - const SchemaParser* parser; - friend class SchemaParser; -}; - -// ======================================================================================= -// Advanced API - -class SchemaFile { - // Abstract interface representing a schema file. You can implement this yourself in order to - // gain more control over how the compiler resolves imports and reads files. For the - // common case of files on disk or other global filesystem-like namespaces, use - // `SchemaFile::newDiskFile()`. - -public: - class FileReader { - public: - virtual bool exists(kj::StringPtr path) const = 0; - virtual kj::Array read(kj::StringPtr path) const = 0; - }; - - class DiskFileReader final: public FileReader { - // Implementation of FileReader that uses the local disk. Files are read using mmap() if - // possible. - - public: - static const DiskFileReader instance; - - bool exists(kj::StringPtr path) const override; - kj::Array read(kj::StringPtr path) const override; - }; - - static kj::Own newDiskFile( - kj::StringPtr displayName, kj::StringPtr diskPath, - kj::ArrayPtr importPath, - const FileReader& fileReader = DiskFileReader::instance); - // Construct a SchemaFile representing a file on disk (or located in the filesystem-like - // namespace represented by `fileReader`). - // - // Parameters: - // * `displayName`: The name that will appear in the file's schema node. - // * `diskPath`: The path to the file on disk. - // * `importPath`: Directories to search when resolving absolute imports within this file - // (imports that start with a `/`). The array content must remain valid as long as the - // SchemaFile exists (which is at least as long as the SchemaParser that parses it exists). - // * `fileReader`: Allows you to use a filesystem other than the actual local disk. Although, - // if you find yourself using this, it may make more sense for you to implement SchemaFile - // yourself. - // - // The SchemaFile compares equal to any other SchemaFile that has exactly the same disk path, - // after canonicalization. - // - // The SchemaFile will throw an exception if any errors are reported. - - // ----------------------------------------------------------------- - // For more control, you can implement this interface. - - virtual kj::StringPtr getDisplayName() const = 0; - // Get the file's name, as it should appear in the schema. - - virtual kj::Array readContent() const = 0; - // Read the file's entire content and return it as a byte array. - - virtual kj::Maybe> import(kj::StringPtr path) const = 0; - // Resolve an import, relative to this file. - // - // `path` is exactly what appears between quotes after the `import` keyword in the source code. - // It is entirely up to the `SchemaFile` to decide how to map this to another file. Typically, - // a leading '/' means that the file is an "absolute" path and is searched for in some list of - // schema file repositories. On the other hand, a path that doesn't start with '/' is relative - // to the importing file. - - virtual bool operator==(const SchemaFile& other) const = 0; - virtual bool operator!=(const SchemaFile& other) const = 0; - virtual size_t hashCode() const = 0; - // Compare two SchemaFiles to see if they refer to the same underlying file. This is an - // optimization used to avoid the need to re-parse a file to check its ID. - - struct SourcePos { - uint byte; - uint line; - uint column; - }; - virtual void reportError(SourcePos start, SourcePos end, kj::StringPtr message) const = 0; - // Report that the file contains an error at the given interval. - -private: - class DiskSchemaFile; -}; - -} // namespace capnp - -#endif // CAPNP_SCHEMA_PARSER_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/schema.capnp b/phonelibs/capnp-cpp/include/capnp/schema.capnp deleted file mode 100644 index 4bef693f6c..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/schema.capnp +++ /dev/null @@ -1,498 +0,0 @@ -# Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -# Licensed under the MIT License: -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -using Cxx = import "/capnp/c++.capnp"; - -@0xa93fc509624c72d9; -$Cxx.namespace("capnp::schema"); - -using Id = UInt64; -# The globally-unique ID of a file, type, or annotation. - -struct Node { - id @0 :Id; - - displayName @1 :Text; - # Name to present to humans to identify this Node. You should not attempt to parse this. Its - # format could change. It is not guaranteed to be unique. - # - # (On Zooko's triangle, this is the node's nickname.) - - displayNamePrefixLength @2 :UInt32; - # If you want a shorter version of `displayName` (just naming this node, without its surrounding - # scope), chop off this many characters from the beginning of `displayName`. - - scopeId @3 :Id; - # ID of the lexical parent node. Typically, the scope node will have a NestedNode pointing back - # at this node, but robust code should avoid relying on this (and, in fact, group nodes are not - # listed in the outer struct's nestedNodes, since they are listed in the fields). `scopeId` is - # zero if the node has no parent, which is normally only the case with files, but should be - # allowed for any kind of node (in order to make runtime type generation easier). - - parameters @32 :List(Parameter); - # If this node is parameterized (generic), the list of parameters. Empty for non-generic types. - - isGeneric @33 :Bool; - # True if this node is generic, meaning that it or one of its parent scopes has a non-empty - # `parameters`. - - struct Parameter { - # Information about one of the node's parameters. - - name @0 :Text; - } - - nestedNodes @4 :List(NestedNode); - # List of nodes nested within this node, along with the names under which they were declared. - - struct NestedNode { - name @0 :Text; - # Unqualified symbol name. Unlike Node.displayName, this *can* be used programmatically. - # - # (On Zooko's triangle, this is the node's petname according to its parent scope.) - - id @1 :Id; - # ID of the nested node. Typically, the target node's scopeId points back to this node, but - # robust code should avoid relying on this. - } - - annotations @5 :List(Annotation); - # Annotations applied to this node. - - union { - # Info specific to each kind of node. - - file @6 :Void; - - struct :group { - dataWordCount @7 :UInt16; - # Size of the data section, in words. - - pointerCount @8 :UInt16; - # Size of the pointer section, in pointers (which are one word each). - - preferredListEncoding @9 :ElementSize; - # The preferred element size to use when encoding a list of this struct. If this is anything - # other than `inlineComposite` then the struct is one word or less in size and is a candidate - # for list packing optimization. - - isGroup @10 :Bool; - # If true, then this "struct" node is actually not an independent node, but merely represents - # some named union or group within a particular parent struct. This node's scopeId refers - # to the parent struct, which may itself be a union/group in yet another struct. - # - # All group nodes share the same dataWordCount and pointerCount as the top-level - # struct, and their fields live in the same ordinal and offset spaces as all other fields in - # the struct. - # - # Note that a named union is considered a special kind of group -- in fact, a named union - # is exactly equivalent to a group that contains nothing but an unnamed union. - - discriminantCount @11 :UInt16; - # Number of fields in this struct which are members of an anonymous union, and thus may - # overlap. If this is non-zero, then a 16-bit discriminant is present indicating which - # of the overlapping fields is active. This can never be 1 -- if it is non-zero, it must be - # two or more. - # - # Note that the fields of an unnamed union are considered fields of the scope containing the - # union -- an unnamed union is not its own group. So, a top-level struct may contain a - # non-zero discriminant count. Named unions, on the other hand, are equivalent to groups - # containing unnamed unions. So, a named union has its own independent schema node, with - # `isGroup` = true. - - discriminantOffset @12 :UInt32; - # If `discriminantCount` is non-zero, this is the offset of the union discriminant, in - # multiples of 16 bits. - - fields @13 :List(Field); - # Fields defined within this scope (either the struct's top-level fields, or the fields of - # a particular group; see `isGroup`). - # - # The fields are sorted by ordinal number, but note that because groups share the same - # ordinal space, the field's index in this list is not necessarily exactly its ordinal. - # On the other hand, the field's position in this list does remain the same even as the - # protocol evolves, since it is not possible to insert or remove an earlier ordinal. - # Therefore, for most use cases, if you want to identify a field by number, it may make the - # most sense to use the field's index in this list rather than its ordinal. - } - - enum :group { - enumerants@14 :List(Enumerant); - # Enumerants ordered by numeric value (ordinal). - } - - interface :group { - methods @15 :List(Method); - # Methods ordered by ordinal. - - superclasses @31 :List(Superclass); - # Superclasses of this interface. - } - - const :group { - type @16 :Type; - value @17 :Value; - } - - annotation :group { - type @18 :Type; - - targetsFile @19 :Bool; - targetsConst @20 :Bool; - targetsEnum @21 :Bool; - targetsEnumerant @22 :Bool; - targetsStruct @23 :Bool; - targetsField @24 :Bool; - targetsUnion @25 :Bool; - targetsGroup @26 :Bool; - targetsInterface @27 :Bool; - targetsMethod @28 :Bool; - targetsParam @29 :Bool; - targetsAnnotation @30 :Bool; - } - } -} - -struct Field { - # Schema for a field of a struct. - - name @0 :Text; - - codeOrder @1 :UInt16; - # Indicates where this member appeared in the code, relative to other members. - # Code ordering may have semantic relevance -- programmers tend to place related fields - # together. So, using code ordering makes sense in human-readable formats where ordering is - # otherwise irrelevant, like JSON. The values of codeOrder are tightly-packed, so the maximum - # value is count(members) - 1. Fields that are members of a union are only ordered relative to - # the other members of that union, so the maximum value there is count(union.members). - - annotations @2 :List(Annotation); - - const noDiscriminant :UInt16 = 0xffff; - - discriminantValue @3 :UInt16 = Field.noDiscriminant; - # If the field is in a union, this is the value which the union's discriminant should take when - # the field is active. If the field is not in a union, this is 0xffff. - - union { - slot :group { - # A regular, non-group, non-fixed-list field. - - offset @4 :UInt32; - # Offset, in units of the field's size, from the beginning of the section in which the field - # resides. E.g. for a UInt32 field, multiply this by 4 to get the byte offset from the - # beginning of the data section. - - type @5 :Type; - defaultValue @6 :Value; - - hadExplicitDefault @10 :Bool; - # Whether the default value was specified explicitly. Non-explicit default values are always - # zero or empty values. Usually, whether the default value was explicit shouldn't matter. - # The main use case for this flag is for structs representing method parameters: - # explicitly-defaulted parameters may be allowed to be omitted when calling the method. - } - - group :group { - # A group. - - typeId @7 :Id; - # The ID of the group's node. - } - } - - ordinal :union { - implicit @8 :Void; - explicit @9 :UInt16; - # The original ordinal number given to the field. You probably should NOT use this; if you need - # a numeric identifier for a field, use its position within the field array for its scope. - # The ordinal is given here mainly just so that the original schema text can be reproduced given - # the compiled version -- i.e. so that `capnp compile -ocapnp` can do its job. - } -} - -struct Enumerant { - # Schema for member of an enum. - - name @0 :Text; - - codeOrder @1 :UInt16; - # Specifies order in which the enumerants were declared in the code. - # Like Struct.Field.codeOrder. - - annotations @2 :List(Annotation); -} - -struct Superclass { - id @0 :Id; - brand @1 :Brand; -} - -struct Method { - # Schema for method of an interface. - - name @0 :Text; - - codeOrder @1 :UInt16; - # Specifies order in which the methods were declared in the code. - # Like Struct.Field.codeOrder. - - implicitParameters @7 :List(Node.Parameter); - # The parameters listed in [] (typically, type / generic parameters), whose bindings are intended - # to be inferred rather than specified explicitly, although not all languages support this. - - paramStructType @2 :Id; - # ID of the parameter struct type. If a named parameter list was specified in the method - # declaration (rather than a single struct parameter type) then a corresponding struct type is - # auto-generated. Such an auto-generated type will not be listed in the interface's - # `nestedNodes` and its `scopeId` will be zero -- it is completely detached from the namespace. - # (Awkwardly, it does of course inherit generic parameters from the method's scope, which makes - # this a situation where you can't just climb the scope chain to find where a particular - # generic parameter was introduced. Making the `scopeId` zero was a mistake.) - - paramBrand @5 :Brand; - # Brand of param struct type. - - resultStructType @3 :Id; - # ID of the return struct type; similar to `paramStructType`. - - resultBrand @6 :Brand; - # Brand of result struct type. - - annotations @4 :List(Annotation); -} - -struct Type { - # Represents a type expression. - - union { - # The ordinals intentionally match those of Value. - - void @0 :Void; - bool @1 :Void; - int8 @2 :Void; - int16 @3 :Void; - int32 @4 :Void; - int64 @5 :Void; - uint8 @6 :Void; - uint16 @7 :Void; - uint32 @8 :Void; - uint64 @9 :Void; - float32 @10 :Void; - float64 @11 :Void; - text @12 :Void; - data @13 :Void; - - list :group { - elementType @14 :Type; - } - - enum :group { - typeId @15 :Id; - brand @21 :Brand; - } - struct :group { - typeId @16 :Id; - brand @22 :Brand; - } - interface :group { - typeId @17 :Id; - brand @23 :Brand; - } - - anyPointer :union { - unconstrained :union { - # A regular AnyPointer. - # - # The name "unconstrained" means as opposed to constraining it to match a type parameter. - # In retrospect this name is probably a poor choice given that it may still be constrained - # to be a struct, list, or capability. - - anyKind @18 :Void; # truly AnyPointer - struct @25 :Void; # AnyStruct - list @26 :Void; # AnyList - capability @27 :Void; # Capability - } - - parameter :group { - # This is actually a reference to a type parameter defined within this scope. - - scopeId @19 :Id; - # ID of the generic type whose parameter we're referencing. This should be a parent of the - # current scope. - - parameterIndex @20 :UInt16; - # Index of the parameter within the generic type's parameter list. - } - - implicitMethodParameter :group { - # This is actually a reference to an implicit (generic) parameter of a method. The only - # legal context for this type to appear is inside Method.paramBrand or Method.resultBrand. - - parameterIndex @24 :UInt16; - } - } - } -} - -struct Brand { - # Specifies bindings for parameters of generics. Since these bindings turn a generic into a - # non-generic, we call it the "brand". - - scopes @0 :List(Scope); - # For each of the target type and each of its parent scopes, a parameterization may be included - # in this list. If no parameterization is included for a particular relevant scope, then either - # that scope has no parameters or all parameters should be considered to be `AnyPointer`. - - struct Scope { - scopeId @0 :Id; - # ID of the scope to which these params apply. - - union { - bind @1 :List(Binding); - # List of parameter bindings. - - inherit @2 :Void; - # The place where this Brand appears is actually within this scope or a sub-scope, - # and the bindings for this scope should be inherited from the reference point. - } - } - - struct Binding { - union { - unbound @0 :Void; - type @1 :Type; - - # TODO(someday): Allow non-type parameters? Unsure if useful. - } - } -} - -struct Value { - # Represents a value, e.g. a field default value, constant value, or annotation value. - - union { - # The ordinals intentionally match those of Type. - - void @0 :Void; - bool @1 :Bool; - int8 @2 :Int8; - int16 @3 :Int16; - int32 @4 :Int32; - int64 @5 :Int64; - uint8 @6 :UInt8; - uint16 @7 :UInt16; - uint32 @8 :UInt32; - uint64 @9 :UInt64; - float32 @10 :Float32; - float64 @11 :Float64; - text @12 :Text; - data @13 :Data; - - list @14 :AnyPointer; - - enum @15 :UInt16; - struct @16 :AnyPointer; - - interface @17 :Void; - # The only interface value that can be represented statically is "null", whose methods always - # throw exceptions. - - anyPointer @18 :AnyPointer; - } -} - -struct Annotation { - # Describes an annotation applied to a declaration. Note AnnotationNode describes the - # annotation's declaration, while this describes a use of the annotation. - - id @0 :Id; - # ID of the annotation node. - - brand @2 :Brand; - # Brand of the annotation. - # - # Note that the annotation itself is not allowed to be parameterized, but its scope might be. - - value @1 :Value; -} - -enum ElementSize { - # Possible element sizes for encoded lists. These correspond exactly to the possible values of - # the 3-bit element size component of a list pointer. - - empty @0; # aka "void", but that's a keyword. - bit @1; - byte @2; - twoBytes @3; - fourBytes @4; - eightBytes @5; - pointer @6; - inlineComposite @7; -} - -struct CapnpVersion { - major @0 :UInt16; - minor @1 :UInt8; - micro @2 :UInt8; -} - -struct CodeGeneratorRequest { - capnpVersion @2 :CapnpVersion; - # Version of the `capnp` executable. Generally, code generators should ignore this, but the code - # generators that ship with `capnp` itself will print a warning if this mismatches since that - # probably indicates something is misconfigured. - # - # The first version of 'capnp' to set this was 0.6.0. So, if it's missing, the compiler version - # is older than that. - - nodes @0 :List(Node); - # All nodes parsed by the compiler, including for the files on the command line and their - # imports. - - requestedFiles @1 :List(RequestedFile); - # Files which were listed on the command line. - - struct RequestedFile { - id @0 :Id; - # ID of the file. - - filename @1 :Text; - # Name of the file as it appeared on the command-line (minus the src-prefix). You may use - # this to decide where to write the output. - - imports @2 :List(Import); - # List of all imported paths seen in this file. - - struct Import { - id @0 :Id; - # ID of the imported file. - - name @1 :Text; - # Name which *this* file used to refer to the foreign file. This may be a relative name. - # This information is provided because it might be useful for code generation, e.g. to - # generate #include directives in C++. We don't put this in Node.file because this - # information is only meaningful at compile time anyway. - # - # (On Zooko's triangle, this is the import's petname according to the importing file.) - } - } -} diff --git a/phonelibs/capnp-cpp/include/capnp/schema.capnp.h b/phonelibs/capnp-cpp/include/capnp/schema.capnp.h deleted file mode 100644 index 1f116c9f8f..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/schema.capnp.h +++ /dev/null @@ -1,7861 +0,0 @@ -// Generated by Cap'n Proto compiler, DO NOT EDIT -// source: schema.capnp - -#ifndef CAPNP_INCLUDED_a93fc509624c72d9_ -#define CAPNP_INCLUDED_a93fc509624c72d9_ - -#include - -#if CAPNP_VERSION != 6001 -#error "Version mismatch between generated code and library headers. You must use the same version of the Cap'n Proto compiler and library." -#endif - - -namespace capnp { -namespace schemas { - -CAPNP_DECLARE_SCHEMA(e682ab4cf923a417); -CAPNP_DECLARE_SCHEMA(b9521bccf10fa3b1); -CAPNP_DECLARE_SCHEMA(debf55bbfa0fc242); -CAPNP_DECLARE_SCHEMA(9ea0b19b37fb4435); -CAPNP_DECLARE_SCHEMA(b54ab3364333f598); -CAPNP_DECLARE_SCHEMA(e82753cff0c2218f); -CAPNP_DECLARE_SCHEMA(b18aa5ac7a0d9420); -CAPNP_DECLARE_SCHEMA(ec1619d4400a0290); -CAPNP_DECLARE_SCHEMA(9aad50a41f4af45f); -CAPNP_DECLARE_SCHEMA(97b14cbe7cfec712); -CAPNP_DECLARE_SCHEMA(c42305476bb4746f); -CAPNP_DECLARE_SCHEMA(cafccddb68db1d11); -CAPNP_DECLARE_SCHEMA(bb90d5c287870be6); -CAPNP_DECLARE_SCHEMA(978a7cebdc549a4d); -CAPNP_DECLARE_SCHEMA(a9962a9ed0a4d7f8); -CAPNP_DECLARE_SCHEMA(9500cce23b334d80); -CAPNP_DECLARE_SCHEMA(d07378ede1f9cc60); -CAPNP_DECLARE_SCHEMA(87e739250a60ea97); -CAPNP_DECLARE_SCHEMA(9e0e78711a7f87a9); -CAPNP_DECLARE_SCHEMA(ac3a6f60ef4cc6d3); -CAPNP_DECLARE_SCHEMA(ed8bca69f7fb0cbf); -CAPNP_DECLARE_SCHEMA(c2573fe8a23e49f1); -CAPNP_DECLARE_SCHEMA(8e3b5f79fe593656); -CAPNP_DECLARE_SCHEMA(9dd1f724f4614a85); -CAPNP_DECLARE_SCHEMA(baefc9120c56e274); -CAPNP_DECLARE_SCHEMA(903455f06065422b); -CAPNP_DECLARE_SCHEMA(abd73485a9636bc9); -CAPNP_DECLARE_SCHEMA(c863cd16969ee7fc); -CAPNP_DECLARE_SCHEMA(ce23dcd2d7b00c9b); -CAPNP_DECLARE_SCHEMA(f1c8950dab257542); -CAPNP_DECLARE_SCHEMA(d1958f7dba521926); -enum class ElementSize_d1958f7dba521926: uint16_t { - EMPTY, - BIT, - BYTE, - TWO_BYTES, - FOUR_BYTES, - EIGHT_BYTES, - POINTER, - INLINE_COMPOSITE, -}; -CAPNP_DECLARE_ENUM(ElementSize, d1958f7dba521926); -CAPNP_DECLARE_SCHEMA(d85d305b7d839963); -CAPNP_DECLARE_SCHEMA(bfc546f6210ad7ce); -CAPNP_DECLARE_SCHEMA(cfea0eb02e810062); -CAPNP_DECLARE_SCHEMA(ae504193122357e5); - -} // namespace schemas -} // namespace capnp - -namespace capnp { -namespace schema { - -struct Node { - Node() = delete; - - class Reader; - class Builder; - class Pipeline; - enum Which: uint16_t { - FILE, - STRUCT, - ENUM, - INTERFACE, - CONST, - ANNOTATION, - }; - struct Parameter; - struct NestedNode; - struct Struct; - struct Enum; - struct Interface; - struct Const; - struct Annotation; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(e682ab4cf923a417, 5, 6) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Node::Parameter { - Parameter() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(b9521bccf10fa3b1, 0, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Node::NestedNode { - NestedNode() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(debf55bbfa0fc242, 1, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Node::Struct { - Struct() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(9ea0b19b37fb4435, 5, 6) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Node::Enum { - Enum() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(b54ab3364333f598, 5, 6) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Node::Interface { - Interface() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(e82753cff0c2218f, 5, 6) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Node::Const { - Const() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(b18aa5ac7a0d9420, 5, 6) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Node::Annotation { - Annotation() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(ec1619d4400a0290, 5, 6) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Field { - Field() = delete; - - class Reader; - class Builder; - class Pipeline; - enum Which: uint16_t { - SLOT, - GROUP, - }; - static constexpr ::uint16_t NO_DISCRIMINANT = 65535u; - struct Slot; - struct Group; - struct Ordinal; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(9aad50a41f4af45f, 3, 4) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Field::Slot { - Slot() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(c42305476bb4746f, 3, 4) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Field::Group { - Group() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(cafccddb68db1d11, 3, 4) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Field::Ordinal { - Ordinal() = delete; - - class Reader; - class Builder; - class Pipeline; - enum Which: uint16_t { - IMPLICIT, - EXPLICIT, - }; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(bb90d5c287870be6, 3, 4) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Enumerant { - Enumerant() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(978a7cebdc549a4d, 1, 2) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Superclass { - Superclass() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(a9962a9ed0a4d7f8, 1, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Method { - Method() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(9500cce23b334d80, 3, 5) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Type { - Type() = delete; - - class Reader; - class Builder; - class Pipeline; - enum Which: uint16_t { - VOID, - BOOL, - INT8, - INT16, - INT32, - INT64, - UINT8, - UINT16, - UINT32, - UINT64, - FLOAT32, - FLOAT64, - TEXT, - DATA, - LIST, - ENUM, - STRUCT, - INTERFACE, - ANY_POINTER, - }; - struct List; - struct Enum; - struct Struct; - struct Interface; - struct AnyPointer; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(d07378ede1f9cc60, 3, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Type::List { - List() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(87e739250a60ea97, 3, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Type::Enum { - Enum() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(9e0e78711a7f87a9, 3, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Type::Struct { - Struct() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(ac3a6f60ef4cc6d3, 3, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Type::Interface { - Interface() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(ed8bca69f7fb0cbf, 3, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Type::AnyPointer { - AnyPointer() = delete; - - class Reader; - class Builder; - class Pipeline; - enum Which: uint16_t { - UNCONSTRAINED, - PARAMETER, - IMPLICIT_METHOD_PARAMETER, - }; - struct Unconstrained; - struct Parameter; - struct ImplicitMethodParameter; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(c2573fe8a23e49f1, 3, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Type::AnyPointer::Unconstrained { - Unconstrained() = delete; - - class Reader; - class Builder; - class Pipeline; - enum Which: uint16_t { - ANY_KIND, - STRUCT, - LIST, - CAPABILITY, - }; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(8e3b5f79fe593656, 3, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Type::AnyPointer::Parameter { - Parameter() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(9dd1f724f4614a85, 3, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Type::AnyPointer::ImplicitMethodParameter { - ImplicitMethodParameter() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(baefc9120c56e274, 3, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Brand { - Brand() = delete; - - class Reader; - class Builder; - class Pipeline; - struct Scope; - struct Binding; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(903455f06065422b, 0, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Brand::Scope { - Scope() = delete; - - class Reader; - class Builder; - class Pipeline; - enum Which: uint16_t { - BIND, - INHERIT, - }; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(abd73485a9636bc9, 2, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Brand::Binding { - Binding() = delete; - - class Reader; - class Builder; - class Pipeline; - enum Which: uint16_t { - UNBOUND, - TYPE, - }; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(c863cd16969ee7fc, 1, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Value { - Value() = delete; - - class Reader; - class Builder; - class Pipeline; - enum Which: uint16_t { - VOID, - BOOL, - INT8, - INT16, - INT32, - INT64, - UINT8, - UINT16, - UINT32, - UINT64, - FLOAT32, - FLOAT64, - TEXT, - DATA, - LIST, - ENUM, - STRUCT, - INTERFACE, - ANY_POINTER, - }; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(ce23dcd2d7b00c9b, 2, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct Annotation { - Annotation() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(f1c8950dab257542, 1, 2) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -typedef ::capnp::schemas::ElementSize_d1958f7dba521926 ElementSize; - -struct CapnpVersion { - CapnpVersion() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(d85d305b7d839963, 1, 0) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct CodeGeneratorRequest { - CodeGeneratorRequest() = delete; - - class Reader; - class Builder; - class Pipeline; - struct RequestedFile; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(bfc546f6210ad7ce, 0, 3) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct CodeGeneratorRequest::RequestedFile { - RequestedFile() = delete; - - class Reader; - class Builder; - class Pipeline; - struct Import; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(cfea0eb02e810062, 1, 2) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -struct CodeGeneratorRequest::RequestedFile::Import { - Import() = delete; - - class Reader; - class Builder; - class Pipeline; - - struct _capnpPrivate { - CAPNP_DECLARE_STRUCT_HEADER(ae504193122357e5, 1, 1) - #if !CAPNP_LITE - static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } - #endif // !CAPNP_LITE - }; -}; - -// ======================================================================================= - -class Node::Reader { -public: - typedef Node Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline Which which() const; - inline ::uint64_t getId() const; - - inline bool hasDisplayName() const; - inline ::capnp::Text::Reader getDisplayName() const; - - inline ::uint32_t getDisplayNamePrefixLength() const; - - inline ::uint64_t getScopeId() const; - - inline bool hasNestedNodes() const; - inline ::capnp::List< ::capnp::schema::Node::NestedNode>::Reader getNestedNodes() const; - - inline bool hasAnnotations() const; - inline ::capnp::List< ::capnp::schema::Annotation>::Reader getAnnotations() const; - - inline bool isFile() const; - inline ::capnp::Void getFile() const; - - inline bool isStruct() const; - inline typename Struct::Reader getStruct() const; - - inline bool isEnum() const; - inline typename Enum::Reader getEnum() const; - - inline bool isInterface() const; - inline typename Interface::Reader getInterface() const; - - inline bool isConst() const; - inline typename Const::Reader getConst() const; - - inline bool isAnnotation() const; - inline typename Annotation::Reader getAnnotation() const; - - inline bool hasParameters() const; - inline ::capnp::List< ::capnp::schema::Node::Parameter>::Reader getParameters() const; - - inline bool getIsGeneric() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Node::Builder { -public: - typedef Node Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline Which which(); - inline ::uint64_t getId(); - inline void setId( ::uint64_t value); - - inline bool hasDisplayName(); - inline ::capnp::Text::Builder getDisplayName(); - inline void setDisplayName( ::capnp::Text::Reader value); - inline ::capnp::Text::Builder initDisplayName(unsigned int size); - inline void adoptDisplayName(::capnp::Orphan< ::capnp::Text>&& value); - inline ::capnp::Orphan< ::capnp::Text> disownDisplayName(); - - inline ::uint32_t getDisplayNamePrefixLength(); - inline void setDisplayNamePrefixLength( ::uint32_t value); - - inline ::uint64_t getScopeId(); - inline void setScopeId( ::uint64_t value); - - inline bool hasNestedNodes(); - inline ::capnp::List< ::capnp::schema::Node::NestedNode>::Builder getNestedNodes(); - inline void setNestedNodes( ::capnp::List< ::capnp::schema::Node::NestedNode>::Reader value); - inline ::capnp::List< ::capnp::schema::Node::NestedNode>::Builder initNestedNodes(unsigned int size); - inline void adoptNestedNodes(::capnp::Orphan< ::capnp::List< ::capnp::schema::Node::NestedNode>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Node::NestedNode>> disownNestedNodes(); - - inline bool hasAnnotations(); - inline ::capnp::List< ::capnp::schema::Annotation>::Builder getAnnotations(); - inline void setAnnotations( ::capnp::List< ::capnp::schema::Annotation>::Reader value); - inline ::capnp::List< ::capnp::schema::Annotation>::Builder initAnnotations(unsigned int size); - inline void adoptAnnotations(::capnp::Orphan< ::capnp::List< ::capnp::schema::Annotation>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Annotation>> disownAnnotations(); - - inline bool isFile(); - inline ::capnp::Void getFile(); - inline void setFile( ::capnp::Void value = ::capnp::VOID); - - inline bool isStruct(); - inline typename Struct::Builder getStruct(); - inline typename Struct::Builder initStruct(); - - inline bool isEnum(); - inline typename Enum::Builder getEnum(); - inline typename Enum::Builder initEnum(); - - inline bool isInterface(); - inline typename Interface::Builder getInterface(); - inline typename Interface::Builder initInterface(); - - inline bool isConst(); - inline typename Const::Builder getConst(); - inline typename Const::Builder initConst(); - - inline bool isAnnotation(); - inline typename Annotation::Builder getAnnotation(); - inline typename Annotation::Builder initAnnotation(); - - inline bool hasParameters(); - inline ::capnp::List< ::capnp::schema::Node::Parameter>::Builder getParameters(); - inline void setParameters( ::capnp::List< ::capnp::schema::Node::Parameter>::Reader value); - inline ::capnp::List< ::capnp::schema::Node::Parameter>::Builder initParameters(unsigned int size); - inline void adoptParameters(::capnp::Orphan< ::capnp::List< ::capnp::schema::Node::Parameter>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Node::Parameter>> disownParameters(); - - inline bool getIsGeneric(); - inline void setIsGeneric(bool value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Node::Pipeline { -public: - typedef Node Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Node::Parameter::Reader { -public: - typedef Parameter Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline bool hasName() const; - inline ::capnp::Text::Reader getName() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Node::Parameter::Builder { -public: - typedef Parameter Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline bool hasName(); - inline ::capnp::Text::Builder getName(); - inline void setName( ::capnp::Text::Reader value); - inline ::capnp::Text::Builder initName(unsigned int size); - inline void adoptName(::capnp::Orphan< ::capnp::Text>&& value); - inline ::capnp::Orphan< ::capnp::Text> disownName(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Node::Parameter::Pipeline { -public: - typedef Parameter Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Node::NestedNode::Reader { -public: - typedef NestedNode Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline bool hasName() const; - inline ::capnp::Text::Reader getName() const; - - inline ::uint64_t getId() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Node::NestedNode::Builder { -public: - typedef NestedNode Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline bool hasName(); - inline ::capnp::Text::Builder getName(); - inline void setName( ::capnp::Text::Reader value); - inline ::capnp::Text::Builder initName(unsigned int size); - inline void adoptName(::capnp::Orphan< ::capnp::Text>&& value); - inline ::capnp::Orphan< ::capnp::Text> disownName(); - - inline ::uint64_t getId(); - inline void setId( ::uint64_t value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Node::NestedNode::Pipeline { -public: - typedef NestedNode Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Node::Struct::Reader { -public: - typedef Struct Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint16_t getDataWordCount() const; - - inline ::uint16_t getPointerCount() const; - - inline ::capnp::schema::ElementSize getPreferredListEncoding() const; - - inline bool getIsGroup() const; - - inline ::uint16_t getDiscriminantCount() const; - - inline ::uint32_t getDiscriminantOffset() const; - - inline bool hasFields() const; - inline ::capnp::List< ::capnp::schema::Field>::Reader getFields() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Node::Struct::Builder { -public: - typedef Struct Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint16_t getDataWordCount(); - inline void setDataWordCount( ::uint16_t value); - - inline ::uint16_t getPointerCount(); - inline void setPointerCount( ::uint16_t value); - - inline ::capnp::schema::ElementSize getPreferredListEncoding(); - inline void setPreferredListEncoding( ::capnp::schema::ElementSize value); - - inline bool getIsGroup(); - inline void setIsGroup(bool value); - - inline ::uint16_t getDiscriminantCount(); - inline void setDiscriminantCount( ::uint16_t value); - - inline ::uint32_t getDiscriminantOffset(); - inline void setDiscriminantOffset( ::uint32_t value); - - inline bool hasFields(); - inline ::capnp::List< ::capnp::schema::Field>::Builder getFields(); - inline void setFields( ::capnp::List< ::capnp::schema::Field>::Reader value); - inline ::capnp::List< ::capnp::schema::Field>::Builder initFields(unsigned int size); - inline void adoptFields(::capnp::Orphan< ::capnp::List< ::capnp::schema::Field>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Field>> disownFields(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Node::Struct::Pipeline { -public: - typedef Struct Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Node::Enum::Reader { -public: - typedef Enum Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline bool hasEnumerants() const; - inline ::capnp::List< ::capnp::schema::Enumerant>::Reader getEnumerants() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Node::Enum::Builder { -public: - typedef Enum Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline bool hasEnumerants(); - inline ::capnp::List< ::capnp::schema::Enumerant>::Builder getEnumerants(); - inline void setEnumerants( ::capnp::List< ::capnp::schema::Enumerant>::Reader value); - inline ::capnp::List< ::capnp::schema::Enumerant>::Builder initEnumerants(unsigned int size); - inline void adoptEnumerants(::capnp::Orphan< ::capnp::List< ::capnp::schema::Enumerant>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Enumerant>> disownEnumerants(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Node::Enum::Pipeline { -public: - typedef Enum Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Node::Interface::Reader { -public: - typedef Interface Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline bool hasMethods() const; - inline ::capnp::List< ::capnp::schema::Method>::Reader getMethods() const; - - inline bool hasSuperclasses() const; - inline ::capnp::List< ::capnp::schema::Superclass>::Reader getSuperclasses() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Node::Interface::Builder { -public: - typedef Interface Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline bool hasMethods(); - inline ::capnp::List< ::capnp::schema::Method>::Builder getMethods(); - inline void setMethods( ::capnp::List< ::capnp::schema::Method>::Reader value); - inline ::capnp::List< ::capnp::schema::Method>::Builder initMethods(unsigned int size); - inline void adoptMethods(::capnp::Orphan< ::capnp::List< ::capnp::schema::Method>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Method>> disownMethods(); - - inline bool hasSuperclasses(); - inline ::capnp::List< ::capnp::schema::Superclass>::Builder getSuperclasses(); - inline void setSuperclasses( ::capnp::List< ::capnp::schema::Superclass>::Reader value); - inline ::capnp::List< ::capnp::schema::Superclass>::Builder initSuperclasses(unsigned int size); - inline void adoptSuperclasses(::capnp::Orphan< ::capnp::List< ::capnp::schema::Superclass>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Superclass>> disownSuperclasses(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Node::Interface::Pipeline { -public: - typedef Interface Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Node::Const::Reader { -public: - typedef Const Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline bool hasType() const; - inline ::capnp::schema::Type::Reader getType() const; - - inline bool hasValue() const; - inline ::capnp::schema::Value::Reader getValue() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Node::Const::Builder { -public: - typedef Const Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline bool hasType(); - inline ::capnp::schema::Type::Builder getType(); - inline void setType( ::capnp::schema::Type::Reader value); - inline ::capnp::schema::Type::Builder initType(); - inline void adoptType(::capnp::Orphan< ::capnp::schema::Type>&& value); - inline ::capnp::Orphan< ::capnp::schema::Type> disownType(); - - inline bool hasValue(); - inline ::capnp::schema::Value::Builder getValue(); - inline void setValue( ::capnp::schema::Value::Reader value); - inline ::capnp::schema::Value::Builder initValue(); - inline void adoptValue(::capnp::Orphan< ::capnp::schema::Value>&& value); - inline ::capnp::Orphan< ::capnp::schema::Value> disownValue(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Node::Const::Pipeline { -public: - typedef Const Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline ::capnp::schema::Type::Pipeline getType(); - inline ::capnp::schema::Value::Pipeline getValue(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Node::Annotation::Reader { -public: - typedef Annotation Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline bool hasType() const; - inline ::capnp::schema::Type::Reader getType() const; - - inline bool getTargetsFile() const; - - inline bool getTargetsConst() const; - - inline bool getTargetsEnum() const; - - inline bool getTargetsEnumerant() const; - - inline bool getTargetsStruct() const; - - inline bool getTargetsField() const; - - inline bool getTargetsUnion() const; - - inline bool getTargetsGroup() const; - - inline bool getTargetsInterface() const; - - inline bool getTargetsMethod() const; - - inline bool getTargetsParam() const; - - inline bool getTargetsAnnotation() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Node::Annotation::Builder { -public: - typedef Annotation Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline bool hasType(); - inline ::capnp::schema::Type::Builder getType(); - inline void setType( ::capnp::schema::Type::Reader value); - inline ::capnp::schema::Type::Builder initType(); - inline void adoptType(::capnp::Orphan< ::capnp::schema::Type>&& value); - inline ::capnp::Orphan< ::capnp::schema::Type> disownType(); - - inline bool getTargetsFile(); - inline void setTargetsFile(bool value); - - inline bool getTargetsConst(); - inline void setTargetsConst(bool value); - - inline bool getTargetsEnum(); - inline void setTargetsEnum(bool value); - - inline bool getTargetsEnumerant(); - inline void setTargetsEnumerant(bool value); - - inline bool getTargetsStruct(); - inline void setTargetsStruct(bool value); - - inline bool getTargetsField(); - inline void setTargetsField(bool value); - - inline bool getTargetsUnion(); - inline void setTargetsUnion(bool value); - - inline bool getTargetsGroup(); - inline void setTargetsGroup(bool value); - - inline bool getTargetsInterface(); - inline void setTargetsInterface(bool value); - - inline bool getTargetsMethod(); - inline void setTargetsMethod(bool value); - - inline bool getTargetsParam(); - inline void setTargetsParam(bool value); - - inline bool getTargetsAnnotation(); - inline void setTargetsAnnotation(bool value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Node::Annotation::Pipeline { -public: - typedef Annotation Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline ::capnp::schema::Type::Pipeline getType(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Field::Reader { -public: - typedef Field Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline Which which() const; - inline bool hasName() const; - inline ::capnp::Text::Reader getName() const; - - inline ::uint16_t getCodeOrder() const; - - inline bool hasAnnotations() const; - inline ::capnp::List< ::capnp::schema::Annotation>::Reader getAnnotations() const; - - inline ::uint16_t getDiscriminantValue() const; - - inline bool isSlot() const; - inline typename Slot::Reader getSlot() const; - - inline bool isGroup() const; - inline typename Group::Reader getGroup() const; - - inline typename Ordinal::Reader getOrdinal() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Field::Builder { -public: - typedef Field Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline Which which(); - inline bool hasName(); - inline ::capnp::Text::Builder getName(); - inline void setName( ::capnp::Text::Reader value); - inline ::capnp::Text::Builder initName(unsigned int size); - inline void adoptName(::capnp::Orphan< ::capnp::Text>&& value); - inline ::capnp::Orphan< ::capnp::Text> disownName(); - - inline ::uint16_t getCodeOrder(); - inline void setCodeOrder( ::uint16_t value); - - inline bool hasAnnotations(); - inline ::capnp::List< ::capnp::schema::Annotation>::Builder getAnnotations(); - inline void setAnnotations( ::capnp::List< ::capnp::schema::Annotation>::Reader value); - inline ::capnp::List< ::capnp::schema::Annotation>::Builder initAnnotations(unsigned int size); - inline void adoptAnnotations(::capnp::Orphan< ::capnp::List< ::capnp::schema::Annotation>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Annotation>> disownAnnotations(); - - inline ::uint16_t getDiscriminantValue(); - inline void setDiscriminantValue( ::uint16_t value); - - inline bool isSlot(); - inline typename Slot::Builder getSlot(); - inline typename Slot::Builder initSlot(); - - inline bool isGroup(); - inline typename Group::Builder getGroup(); - inline typename Group::Builder initGroup(); - - inline typename Ordinal::Builder getOrdinal(); - inline typename Ordinal::Builder initOrdinal(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Field::Pipeline { -public: - typedef Field Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline typename Ordinal::Pipeline getOrdinal(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Field::Slot::Reader { -public: - typedef Slot Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint32_t getOffset() const; - - inline bool hasType() const; - inline ::capnp::schema::Type::Reader getType() const; - - inline bool hasDefaultValue() const; - inline ::capnp::schema::Value::Reader getDefaultValue() const; - - inline bool getHadExplicitDefault() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Field::Slot::Builder { -public: - typedef Slot Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint32_t getOffset(); - inline void setOffset( ::uint32_t value); - - inline bool hasType(); - inline ::capnp::schema::Type::Builder getType(); - inline void setType( ::capnp::schema::Type::Reader value); - inline ::capnp::schema::Type::Builder initType(); - inline void adoptType(::capnp::Orphan< ::capnp::schema::Type>&& value); - inline ::capnp::Orphan< ::capnp::schema::Type> disownType(); - - inline bool hasDefaultValue(); - inline ::capnp::schema::Value::Builder getDefaultValue(); - inline void setDefaultValue( ::capnp::schema::Value::Reader value); - inline ::capnp::schema::Value::Builder initDefaultValue(); - inline void adoptDefaultValue(::capnp::Orphan< ::capnp::schema::Value>&& value); - inline ::capnp::Orphan< ::capnp::schema::Value> disownDefaultValue(); - - inline bool getHadExplicitDefault(); - inline void setHadExplicitDefault(bool value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Field::Slot::Pipeline { -public: - typedef Slot Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline ::capnp::schema::Type::Pipeline getType(); - inline ::capnp::schema::Value::Pipeline getDefaultValue(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Field::Group::Reader { -public: - typedef Group Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint64_t getTypeId() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Field::Group::Builder { -public: - typedef Group Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint64_t getTypeId(); - inline void setTypeId( ::uint64_t value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Field::Group::Pipeline { -public: - typedef Group Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Field::Ordinal::Reader { -public: - typedef Ordinal Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline Which which() const; - inline bool isImplicit() const; - inline ::capnp::Void getImplicit() const; - - inline bool isExplicit() const; - inline ::uint16_t getExplicit() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Field::Ordinal::Builder { -public: - typedef Ordinal Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline Which which(); - inline bool isImplicit(); - inline ::capnp::Void getImplicit(); - inline void setImplicit( ::capnp::Void value = ::capnp::VOID); - - inline bool isExplicit(); - inline ::uint16_t getExplicit(); - inline void setExplicit( ::uint16_t value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Field::Ordinal::Pipeline { -public: - typedef Ordinal Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Enumerant::Reader { -public: - typedef Enumerant Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline bool hasName() const; - inline ::capnp::Text::Reader getName() const; - - inline ::uint16_t getCodeOrder() const; - - inline bool hasAnnotations() const; - inline ::capnp::List< ::capnp::schema::Annotation>::Reader getAnnotations() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Enumerant::Builder { -public: - typedef Enumerant Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline bool hasName(); - inline ::capnp::Text::Builder getName(); - inline void setName( ::capnp::Text::Reader value); - inline ::capnp::Text::Builder initName(unsigned int size); - inline void adoptName(::capnp::Orphan< ::capnp::Text>&& value); - inline ::capnp::Orphan< ::capnp::Text> disownName(); - - inline ::uint16_t getCodeOrder(); - inline void setCodeOrder( ::uint16_t value); - - inline bool hasAnnotations(); - inline ::capnp::List< ::capnp::schema::Annotation>::Builder getAnnotations(); - inline void setAnnotations( ::capnp::List< ::capnp::schema::Annotation>::Reader value); - inline ::capnp::List< ::capnp::schema::Annotation>::Builder initAnnotations(unsigned int size); - inline void adoptAnnotations(::capnp::Orphan< ::capnp::List< ::capnp::schema::Annotation>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Annotation>> disownAnnotations(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Enumerant::Pipeline { -public: - typedef Enumerant Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Superclass::Reader { -public: - typedef Superclass Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint64_t getId() const; - - inline bool hasBrand() const; - inline ::capnp::schema::Brand::Reader getBrand() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Superclass::Builder { -public: - typedef Superclass Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint64_t getId(); - inline void setId( ::uint64_t value); - - inline bool hasBrand(); - inline ::capnp::schema::Brand::Builder getBrand(); - inline void setBrand( ::capnp::schema::Brand::Reader value); - inline ::capnp::schema::Brand::Builder initBrand(); - inline void adoptBrand(::capnp::Orphan< ::capnp::schema::Brand>&& value); - inline ::capnp::Orphan< ::capnp::schema::Brand> disownBrand(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Superclass::Pipeline { -public: - typedef Superclass Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline ::capnp::schema::Brand::Pipeline getBrand(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Method::Reader { -public: - typedef Method Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline bool hasName() const; - inline ::capnp::Text::Reader getName() const; - - inline ::uint16_t getCodeOrder() const; - - inline ::uint64_t getParamStructType() const; - - inline ::uint64_t getResultStructType() const; - - inline bool hasAnnotations() const; - inline ::capnp::List< ::capnp::schema::Annotation>::Reader getAnnotations() const; - - inline bool hasParamBrand() const; - inline ::capnp::schema::Brand::Reader getParamBrand() const; - - inline bool hasResultBrand() const; - inline ::capnp::schema::Brand::Reader getResultBrand() const; - - inline bool hasImplicitParameters() const; - inline ::capnp::List< ::capnp::schema::Node::Parameter>::Reader getImplicitParameters() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Method::Builder { -public: - typedef Method Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline bool hasName(); - inline ::capnp::Text::Builder getName(); - inline void setName( ::capnp::Text::Reader value); - inline ::capnp::Text::Builder initName(unsigned int size); - inline void adoptName(::capnp::Orphan< ::capnp::Text>&& value); - inline ::capnp::Orphan< ::capnp::Text> disownName(); - - inline ::uint16_t getCodeOrder(); - inline void setCodeOrder( ::uint16_t value); - - inline ::uint64_t getParamStructType(); - inline void setParamStructType( ::uint64_t value); - - inline ::uint64_t getResultStructType(); - inline void setResultStructType( ::uint64_t value); - - inline bool hasAnnotations(); - inline ::capnp::List< ::capnp::schema::Annotation>::Builder getAnnotations(); - inline void setAnnotations( ::capnp::List< ::capnp::schema::Annotation>::Reader value); - inline ::capnp::List< ::capnp::schema::Annotation>::Builder initAnnotations(unsigned int size); - inline void adoptAnnotations(::capnp::Orphan< ::capnp::List< ::capnp::schema::Annotation>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Annotation>> disownAnnotations(); - - inline bool hasParamBrand(); - inline ::capnp::schema::Brand::Builder getParamBrand(); - inline void setParamBrand( ::capnp::schema::Brand::Reader value); - inline ::capnp::schema::Brand::Builder initParamBrand(); - inline void adoptParamBrand(::capnp::Orphan< ::capnp::schema::Brand>&& value); - inline ::capnp::Orphan< ::capnp::schema::Brand> disownParamBrand(); - - inline bool hasResultBrand(); - inline ::capnp::schema::Brand::Builder getResultBrand(); - inline void setResultBrand( ::capnp::schema::Brand::Reader value); - inline ::capnp::schema::Brand::Builder initResultBrand(); - inline void adoptResultBrand(::capnp::Orphan< ::capnp::schema::Brand>&& value); - inline ::capnp::Orphan< ::capnp::schema::Brand> disownResultBrand(); - - inline bool hasImplicitParameters(); - inline ::capnp::List< ::capnp::schema::Node::Parameter>::Builder getImplicitParameters(); - inline void setImplicitParameters( ::capnp::List< ::capnp::schema::Node::Parameter>::Reader value); - inline ::capnp::List< ::capnp::schema::Node::Parameter>::Builder initImplicitParameters(unsigned int size); - inline void adoptImplicitParameters(::capnp::Orphan< ::capnp::List< ::capnp::schema::Node::Parameter>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Node::Parameter>> disownImplicitParameters(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Method::Pipeline { -public: - typedef Method Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline ::capnp::schema::Brand::Pipeline getParamBrand(); - inline ::capnp::schema::Brand::Pipeline getResultBrand(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Type::Reader { -public: - typedef Type Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline Which which() const; - inline bool isVoid() const; - inline ::capnp::Void getVoid() const; - - inline bool isBool() const; - inline ::capnp::Void getBool() const; - - inline bool isInt8() const; - inline ::capnp::Void getInt8() const; - - inline bool isInt16() const; - inline ::capnp::Void getInt16() const; - - inline bool isInt32() const; - inline ::capnp::Void getInt32() const; - - inline bool isInt64() const; - inline ::capnp::Void getInt64() const; - - inline bool isUint8() const; - inline ::capnp::Void getUint8() const; - - inline bool isUint16() const; - inline ::capnp::Void getUint16() const; - - inline bool isUint32() const; - inline ::capnp::Void getUint32() const; - - inline bool isUint64() const; - inline ::capnp::Void getUint64() const; - - inline bool isFloat32() const; - inline ::capnp::Void getFloat32() const; - - inline bool isFloat64() const; - inline ::capnp::Void getFloat64() const; - - inline bool isText() const; - inline ::capnp::Void getText() const; - - inline bool isData() const; - inline ::capnp::Void getData() const; - - inline bool isList() const; - inline typename List::Reader getList() const; - - inline bool isEnum() const; - inline typename Enum::Reader getEnum() const; - - inline bool isStruct() const; - inline typename Struct::Reader getStruct() const; - - inline bool isInterface() const; - inline typename Interface::Reader getInterface() const; - - inline bool isAnyPointer() const; - inline typename AnyPointer::Reader getAnyPointer() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Type::Builder { -public: - typedef Type Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline Which which(); - inline bool isVoid(); - inline ::capnp::Void getVoid(); - inline void setVoid( ::capnp::Void value = ::capnp::VOID); - - inline bool isBool(); - inline ::capnp::Void getBool(); - inline void setBool( ::capnp::Void value = ::capnp::VOID); - - inline bool isInt8(); - inline ::capnp::Void getInt8(); - inline void setInt8( ::capnp::Void value = ::capnp::VOID); - - inline bool isInt16(); - inline ::capnp::Void getInt16(); - inline void setInt16( ::capnp::Void value = ::capnp::VOID); - - inline bool isInt32(); - inline ::capnp::Void getInt32(); - inline void setInt32( ::capnp::Void value = ::capnp::VOID); - - inline bool isInt64(); - inline ::capnp::Void getInt64(); - inline void setInt64( ::capnp::Void value = ::capnp::VOID); - - inline bool isUint8(); - inline ::capnp::Void getUint8(); - inline void setUint8( ::capnp::Void value = ::capnp::VOID); - - inline bool isUint16(); - inline ::capnp::Void getUint16(); - inline void setUint16( ::capnp::Void value = ::capnp::VOID); - - inline bool isUint32(); - inline ::capnp::Void getUint32(); - inline void setUint32( ::capnp::Void value = ::capnp::VOID); - - inline bool isUint64(); - inline ::capnp::Void getUint64(); - inline void setUint64( ::capnp::Void value = ::capnp::VOID); - - inline bool isFloat32(); - inline ::capnp::Void getFloat32(); - inline void setFloat32( ::capnp::Void value = ::capnp::VOID); - - inline bool isFloat64(); - inline ::capnp::Void getFloat64(); - inline void setFloat64( ::capnp::Void value = ::capnp::VOID); - - inline bool isText(); - inline ::capnp::Void getText(); - inline void setText( ::capnp::Void value = ::capnp::VOID); - - inline bool isData(); - inline ::capnp::Void getData(); - inline void setData( ::capnp::Void value = ::capnp::VOID); - - inline bool isList(); - inline typename List::Builder getList(); - inline typename List::Builder initList(); - - inline bool isEnum(); - inline typename Enum::Builder getEnum(); - inline typename Enum::Builder initEnum(); - - inline bool isStruct(); - inline typename Struct::Builder getStruct(); - inline typename Struct::Builder initStruct(); - - inline bool isInterface(); - inline typename Interface::Builder getInterface(); - inline typename Interface::Builder initInterface(); - - inline bool isAnyPointer(); - inline typename AnyPointer::Builder getAnyPointer(); - inline typename AnyPointer::Builder initAnyPointer(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Type::Pipeline { -public: - typedef Type Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Type::List::Reader { -public: - typedef List Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline bool hasElementType() const; - inline ::capnp::schema::Type::Reader getElementType() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Type::List::Builder { -public: - typedef List Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline bool hasElementType(); - inline ::capnp::schema::Type::Builder getElementType(); - inline void setElementType( ::capnp::schema::Type::Reader value); - inline ::capnp::schema::Type::Builder initElementType(); - inline void adoptElementType(::capnp::Orphan< ::capnp::schema::Type>&& value); - inline ::capnp::Orphan< ::capnp::schema::Type> disownElementType(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Type::List::Pipeline { -public: - typedef List Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline ::capnp::schema::Type::Pipeline getElementType(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Type::Enum::Reader { -public: - typedef Enum Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint64_t getTypeId() const; - - inline bool hasBrand() const; - inline ::capnp::schema::Brand::Reader getBrand() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Type::Enum::Builder { -public: - typedef Enum Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint64_t getTypeId(); - inline void setTypeId( ::uint64_t value); - - inline bool hasBrand(); - inline ::capnp::schema::Brand::Builder getBrand(); - inline void setBrand( ::capnp::schema::Brand::Reader value); - inline ::capnp::schema::Brand::Builder initBrand(); - inline void adoptBrand(::capnp::Orphan< ::capnp::schema::Brand>&& value); - inline ::capnp::Orphan< ::capnp::schema::Brand> disownBrand(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Type::Enum::Pipeline { -public: - typedef Enum Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline ::capnp::schema::Brand::Pipeline getBrand(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Type::Struct::Reader { -public: - typedef Struct Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint64_t getTypeId() const; - - inline bool hasBrand() const; - inline ::capnp::schema::Brand::Reader getBrand() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Type::Struct::Builder { -public: - typedef Struct Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint64_t getTypeId(); - inline void setTypeId( ::uint64_t value); - - inline bool hasBrand(); - inline ::capnp::schema::Brand::Builder getBrand(); - inline void setBrand( ::capnp::schema::Brand::Reader value); - inline ::capnp::schema::Brand::Builder initBrand(); - inline void adoptBrand(::capnp::Orphan< ::capnp::schema::Brand>&& value); - inline ::capnp::Orphan< ::capnp::schema::Brand> disownBrand(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Type::Struct::Pipeline { -public: - typedef Struct Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline ::capnp::schema::Brand::Pipeline getBrand(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Type::Interface::Reader { -public: - typedef Interface Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint64_t getTypeId() const; - - inline bool hasBrand() const; - inline ::capnp::schema::Brand::Reader getBrand() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Type::Interface::Builder { -public: - typedef Interface Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint64_t getTypeId(); - inline void setTypeId( ::uint64_t value); - - inline bool hasBrand(); - inline ::capnp::schema::Brand::Builder getBrand(); - inline void setBrand( ::capnp::schema::Brand::Reader value); - inline ::capnp::schema::Brand::Builder initBrand(); - inline void adoptBrand(::capnp::Orphan< ::capnp::schema::Brand>&& value); - inline ::capnp::Orphan< ::capnp::schema::Brand> disownBrand(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Type::Interface::Pipeline { -public: - typedef Interface Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline ::capnp::schema::Brand::Pipeline getBrand(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Type::AnyPointer::Reader { -public: - typedef AnyPointer Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline Which which() const; - inline bool isUnconstrained() const; - inline typename Unconstrained::Reader getUnconstrained() const; - - inline bool isParameter() const; - inline typename Parameter::Reader getParameter() const; - - inline bool isImplicitMethodParameter() const; - inline typename ImplicitMethodParameter::Reader getImplicitMethodParameter() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Type::AnyPointer::Builder { -public: - typedef AnyPointer Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline Which which(); - inline bool isUnconstrained(); - inline typename Unconstrained::Builder getUnconstrained(); - inline typename Unconstrained::Builder initUnconstrained(); - - inline bool isParameter(); - inline typename Parameter::Builder getParameter(); - inline typename Parameter::Builder initParameter(); - - inline bool isImplicitMethodParameter(); - inline typename ImplicitMethodParameter::Builder getImplicitMethodParameter(); - inline typename ImplicitMethodParameter::Builder initImplicitMethodParameter(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Type::AnyPointer::Pipeline { -public: - typedef AnyPointer Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Type::AnyPointer::Unconstrained::Reader { -public: - typedef Unconstrained Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline Which which() const; - inline bool isAnyKind() const; - inline ::capnp::Void getAnyKind() const; - - inline bool isStruct() const; - inline ::capnp::Void getStruct() const; - - inline bool isList() const; - inline ::capnp::Void getList() const; - - inline bool isCapability() const; - inline ::capnp::Void getCapability() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Type::AnyPointer::Unconstrained::Builder { -public: - typedef Unconstrained Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline Which which(); - inline bool isAnyKind(); - inline ::capnp::Void getAnyKind(); - inline void setAnyKind( ::capnp::Void value = ::capnp::VOID); - - inline bool isStruct(); - inline ::capnp::Void getStruct(); - inline void setStruct( ::capnp::Void value = ::capnp::VOID); - - inline bool isList(); - inline ::capnp::Void getList(); - inline void setList( ::capnp::Void value = ::capnp::VOID); - - inline bool isCapability(); - inline ::capnp::Void getCapability(); - inline void setCapability( ::capnp::Void value = ::capnp::VOID); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Type::AnyPointer::Unconstrained::Pipeline { -public: - typedef Unconstrained Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Type::AnyPointer::Parameter::Reader { -public: - typedef Parameter Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint64_t getScopeId() const; - - inline ::uint16_t getParameterIndex() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Type::AnyPointer::Parameter::Builder { -public: - typedef Parameter Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint64_t getScopeId(); - inline void setScopeId( ::uint64_t value); - - inline ::uint16_t getParameterIndex(); - inline void setParameterIndex( ::uint16_t value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Type::AnyPointer::Parameter::Pipeline { -public: - typedef Parameter Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Type::AnyPointer::ImplicitMethodParameter::Reader { -public: - typedef ImplicitMethodParameter Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint16_t getParameterIndex() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Type::AnyPointer::ImplicitMethodParameter::Builder { -public: - typedef ImplicitMethodParameter Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint16_t getParameterIndex(); - inline void setParameterIndex( ::uint16_t value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Type::AnyPointer::ImplicitMethodParameter::Pipeline { -public: - typedef ImplicitMethodParameter Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Brand::Reader { -public: - typedef Brand Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline bool hasScopes() const; - inline ::capnp::List< ::capnp::schema::Brand::Scope>::Reader getScopes() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Brand::Builder { -public: - typedef Brand Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline bool hasScopes(); - inline ::capnp::List< ::capnp::schema::Brand::Scope>::Builder getScopes(); - inline void setScopes( ::capnp::List< ::capnp::schema::Brand::Scope>::Reader value); - inline ::capnp::List< ::capnp::schema::Brand::Scope>::Builder initScopes(unsigned int size); - inline void adoptScopes(::capnp::Orphan< ::capnp::List< ::capnp::schema::Brand::Scope>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Brand::Scope>> disownScopes(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Brand::Pipeline { -public: - typedef Brand Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Brand::Scope::Reader { -public: - typedef Scope Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline Which which() const; - inline ::uint64_t getScopeId() const; - - inline bool isBind() const; - inline bool hasBind() const; - inline ::capnp::List< ::capnp::schema::Brand::Binding>::Reader getBind() const; - - inline bool isInherit() const; - inline ::capnp::Void getInherit() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Brand::Scope::Builder { -public: - typedef Scope Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline Which which(); - inline ::uint64_t getScopeId(); - inline void setScopeId( ::uint64_t value); - - inline bool isBind(); - inline bool hasBind(); - inline ::capnp::List< ::capnp::schema::Brand::Binding>::Builder getBind(); - inline void setBind( ::capnp::List< ::capnp::schema::Brand::Binding>::Reader value); - inline ::capnp::List< ::capnp::schema::Brand::Binding>::Builder initBind(unsigned int size); - inline void adoptBind(::capnp::Orphan< ::capnp::List< ::capnp::schema::Brand::Binding>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Brand::Binding>> disownBind(); - - inline bool isInherit(); - inline ::capnp::Void getInherit(); - inline void setInherit( ::capnp::Void value = ::capnp::VOID); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Brand::Scope::Pipeline { -public: - typedef Scope Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Brand::Binding::Reader { -public: - typedef Binding Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline Which which() const; - inline bool isUnbound() const; - inline ::capnp::Void getUnbound() const; - - inline bool isType() const; - inline bool hasType() const; - inline ::capnp::schema::Type::Reader getType() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Brand::Binding::Builder { -public: - typedef Binding Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline Which which(); - inline bool isUnbound(); - inline ::capnp::Void getUnbound(); - inline void setUnbound( ::capnp::Void value = ::capnp::VOID); - - inline bool isType(); - inline bool hasType(); - inline ::capnp::schema::Type::Builder getType(); - inline void setType( ::capnp::schema::Type::Reader value); - inline ::capnp::schema::Type::Builder initType(); - inline void adoptType(::capnp::Orphan< ::capnp::schema::Type>&& value); - inline ::capnp::Orphan< ::capnp::schema::Type> disownType(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Brand::Binding::Pipeline { -public: - typedef Binding Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Value::Reader { -public: - typedef Value Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline Which which() const; - inline bool isVoid() const; - inline ::capnp::Void getVoid() const; - - inline bool isBool() const; - inline bool getBool() const; - - inline bool isInt8() const; - inline ::int8_t getInt8() const; - - inline bool isInt16() const; - inline ::int16_t getInt16() const; - - inline bool isInt32() const; - inline ::int32_t getInt32() const; - - inline bool isInt64() const; - inline ::int64_t getInt64() const; - - inline bool isUint8() const; - inline ::uint8_t getUint8() const; - - inline bool isUint16() const; - inline ::uint16_t getUint16() const; - - inline bool isUint32() const; - inline ::uint32_t getUint32() const; - - inline bool isUint64() const; - inline ::uint64_t getUint64() const; - - inline bool isFloat32() const; - inline float getFloat32() const; - - inline bool isFloat64() const; - inline double getFloat64() const; - - inline bool isText() const; - inline bool hasText() const; - inline ::capnp::Text::Reader getText() const; - - inline bool isData() const; - inline bool hasData() const; - inline ::capnp::Data::Reader getData() const; - - inline bool isList() const; - inline bool hasList() const; - inline ::capnp::AnyPointer::Reader getList() const; - - inline bool isEnum() const; - inline ::uint16_t getEnum() const; - - inline bool isStruct() const; - inline bool hasStruct() const; - inline ::capnp::AnyPointer::Reader getStruct() const; - - inline bool isInterface() const; - inline ::capnp::Void getInterface() const; - - inline bool isAnyPointer() const; - inline bool hasAnyPointer() const; - inline ::capnp::AnyPointer::Reader getAnyPointer() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Value::Builder { -public: - typedef Value Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline Which which(); - inline bool isVoid(); - inline ::capnp::Void getVoid(); - inline void setVoid( ::capnp::Void value = ::capnp::VOID); - - inline bool isBool(); - inline bool getBool(); - inline void setBool(bool value); - - inline bool isInt8(); - inline ::int8_t getInt8(); - inline void setInt8( ::int8_t value); - - inline bool isInt16(); - inline ::int16_t getInt16(); - inline void setInt16( ::int16_t value); - - inline bool isInt32(); - inline ::int32_t getInt32(); - inline void setInt32( ::int32_t value); - - inline bool isInt64(); - inline ::int64_t getInt64(); - inline void setInt64( ::int64_t value); - - inline bool isUint8(); - inline ::uint8_t getUint8(); - inline void setUint8( ::uint8_t value); - - inline bool isUint16(); - inline ::uint16_t getUint16(); - inline void setUint16( ::uint16_t value); - - inline bool isUint32(); - inline ::uint32_t getUint32(); - inline void setUint32( ::uint32_t value); - - inline bool isUint64(); - inline ::uint64_t getUint64(); - inline void setUint64( ::uint64_t value); - - inline bool isFloat32(); - inline float getFloat32(); - inline void setFloat32(float value); - - inline bool isFloat64(); - inline double getFloat64(); - inline void setFloat64(double value); - - inline bool isText(); - inline bool hasText(); - inline ::capnp::Text::Builder getText(); - inline void setText( ::capnp::Text::Reader value); - inline ::capnp::Text::Builder initText(unsigned int size); - inline void adoptText(::capnp::Orphan< ::capnp::Text>&& value); - inline ::capnp::Orphan< ::capnp::Text> disownText(); - - inline bool isData(); - inline bool hasData(); - inline ::capnp::Data::Builder getData(); - inline void setData( ::capnp::Data::Reader value); - inline ::capnp::Data::Builder initData(unsigned int size); - inline void adoptData(::capnp::Orphan< ::capnp::Data>&& value); - inline ::capnp::Orphan< ::capnp::Data> disownData(); - - inline bool isList(); - inline bool hasList(); - inline ::capnp::AnyPointer::Builder getList(); - inline ::capnp::AnyPointer::Builder initList(); - - inline bool isEnum(); - inline ::uint16_t getEnum(); - inline void setEnum( ::uint16_t value); - - inline bool isStruct(); - inline bool hasStruct(); - inline ::capnp::AnyPointer::Builder getStruct(); - inline ::capnp::AnyPointer::Builder initStruct(); - - inline bool isInterface(); - inline ::capnp::Void getInterface(); - inline void setInterface( ::capnp::Void value = ::capnp::VOID); - - inline bool isAnyPointer(); - inline bool hasAnyPointer(); - inline ::capnp::AnyPointer::Builder getAnyPointer(); - inline ::capnp::AnyPointer::Builder initAnyPointer(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Value::Pipeline { -public: - typedef Value Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class Annotation::Reader { -public: - typedef Annotation Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint64_t getId() const; - - inline bool hasValue() const; - inline ::capnp::schema::Value::Reader getValue() const; - - inline bool hasBrand() const; - inline ::capnp::schema::Brand::Reader getBrand() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class Annotation::Builder { -public: - typedef Annotation Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint64_t getId(); - inline void setId( ::uint64_t value); - - inline bool hasValue(); - inline ::capnp::schema::Value::Builder getValue(); - inline void setValue( ::capnp::schema::Value::Reader value); - inline ::capnp::schema::Value::Builder initValue(); - inline void adoptValue(::capnp::Orphan< ::capnp::schema::Value>&& value); - inline ::capnp::Orphan< ::capnp::schema::Value> disownValue(); - - inline bool hasBrand(); - inline ::capnp::schema::Brand::Builder getBrand(); - inline void setBrand( ::capnp::schema::Brand::Reader value); - inline ::capnp::schema::Brand::Builder initBrand(); - inline void adoptBrand(::capnp::Orphan< ::capnp::schema::Brand>&& value); - inline ::capnp::Orphan< ::capnp::schema::Brand> disownBrand(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class Annotation::Pipeline { -public: - typedef Annotation Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline ::capnp::schema::Value::Pipeline getValue(); - inline ::capnp::schema::Brand::Pipeline getBrand(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class CapnpVersion::Reader { -public: - typedef CapnpVersion Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint16_t getMajor() const; - - inline ::uint8_t getMinor() const; - - inline ::uint8_t getMicro() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class CapnpVersion::Builder { -public: - typedef CapnpVersion Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint16_t getMajor(); - inline void setMajor( ::uint16_t value); - - inline ::uint8_t getMinor(); - inline void setMinor( ::uint8_t value); - - inline ::uint8_t getMicro(); - inline void setMicro( ::uint8_t value); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class CapnpVersion::Pipeline { -public: - typedef CapnpVersion Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class CodeGeneratorRequest::Reader { -public: - typedef CodeGeneratorRequest Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline bool hasNodes() const; - inline ::capnp::List< ::capnp::schema::Node>::Reader getNodes() const; - - inline bool hasRequestedFiles() const; - inline ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile>::Reader getRequestedFiles() const; - - inline bool hasCapnpVersion() const; - inline ::capnp::schema::CapnpVersion::Reader getCapnpVersion() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class CodeGeneratorRequest::Builder { -public: - typedef CodeGeneratorRequest Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline bool hasNodes(); - inline ::capnp::List< ::capnp::schema::Node>::Builder getNodes(); - inline void setNodes( ::capnp::List< ::capnp::schema::Node>::Reader value); - inline ::capnp::List< ::capnp::schema::Node>::Builder initNodes(unsigned int size); - inline void adoptNodes(::capnp::Orphan< ::capnp::List< ::capnp::schema::Node>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Node>> disownNodes(); - - inline bool hasRequestedFiles(); - inline ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile>::Builder getRequestedFiles(); - inline void setRequestedFiles( ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile>::Reader value); - inline ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile>::Builder initRequestedFiles(unsigned int size); - inline void adoptRequestedFiles(::capnp::Orphan< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile>> disownRequestedFiles(); - - inline bool hasCapnpVersion(); - inline ::capnp::schema::CapnpVersion::Builder getCapnpVersion(); - inline void setCapnpVersion( ::capnp::schema::CapnpVersion::Reader value); - inline ::capnp::schema::CapnpVersion::Builder initCapnpVersion(); - inline void adoptCapnpVersion(::capnp::Orphan< ::capnp::schema::CapnpVersion>&& value); - inline ::capnp::Orphan< ::capnp::schema::CapnpVersion> disownCapnpVersion(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class CodeGeneratorRequest::Pipeline { -public: - typedef CodeGeneratorRequest Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - - inline ::capnp::schema::CapnpVersion::Pipeline getCapnpVersion(); -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class CodeGeneratorRequest::RequestedFile::Reader { -public: - typedef RequestedFile Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint64_t getId() const; - - inline bool hasFilename() const; - inline ::capnp::Text::Reader getFilename() const; - - inline bool hasImports() const; - inline ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile::Import>::Reader getImports() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class CodeGeneratorRequest::RequestedFile::Builder { -public: - typedef RequestedFile Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint64_t getId(); - inline void setId( ::uint64_t value); - - inline bool hasFilename(); - inline ::capnp::Text::Builder getFilename(); - inline void setFilename( ::capnp::Text::Reader value); - inline ::capnp::Text::Builder initFilename(unsigned int size); - inline void adoptFilename(::capnp::Orphan< ::capnp::Text>&& value); - inline ::capnp::Orphan< ::capnp::Text> disownFilename(); - - inline bool hasImports(); - inline ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile::Import>::Builder getImports(); - inline void setImports( ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile::Import>::Reader value); - inline ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile::Import>::Builder initImports(unsigned int size); - inline void adoptImports(::capnp::Orphan< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile::Import>>&& value); - inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile::Import>> disownImports(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class CodeGeneratorRequest::RequestedFile::Pipeline { -public: - typedef RequestedFile Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -class CodeGeneratorRequest::RequestedFile::Import::Reader { -public: - typedef Import Reads; - - Reader() = default; - inline explicit Reader(::capnp::_::StructReader base): _reader(base) {} - - inline ::capnp::MessageSize totalSize() const { - return _reader.totalSize().asPublic(); - } - -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { - return ::capnp::_::structString(_reader, *_capnpPrivate::brand()); - } -#endif // !CAPNP_LITE - - inline ::uint64_t getId() const; - - inline bool hasName() const; - inline ::capnp::Text::Reader getName() const; - -private: - ::capnp::_::StructReader _reader; - template - friend struct ::capnp::ToDynamic_; - template - friend struct ::capnp::_::PointerHelpers; - template - friend struct ::capnp::List; - friend class ::capnp::MessageBuilder; - friend class ::capnp::Orphanage; -}; - -class CodeGeneratorRequest::RequestedFile::Import::Builder { -public: - typedef Import Builds; - - Builder() = delete; // Deleted to discourage incorrect usage. - // You can explicitly initialize to nullptr instead. - inline Builder(decltype(nullptr)) {} - inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {} - inline operator Reader() const { return Reader(_builder.asReader()); } - inline Reader asReader() const { return *this; } - - inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); } -#if !CAPNP_LITE - inline ::kj::StringTree toString() const { return asReader().toString(); } -#endif // !CAPNP_LITE - - inline ::uint64_t getId(); - inline void setId( ::uint64_t value); - - inline bool hasName(); - inline ::capnp::Text::Builder getName(); - inline void setName( ::capnp::Text::Reader value); - inline ::capnp::Text::Builder initName(unsigned int size); - inline void adoptName(::capnp::Orphan< ::capnp::Text>&& value); - inline ::capnp::Orphan< ::capnp::Text> disownName(); - -private: - ::capnp::_::StructBuilder _builder; - template - friend struct ::capnp::ToDynamic_; - friend class ::capnp::Orphanage; - template - friend struct ::capnp::_::PointerHelpers; -}; - -#if !CAPNP_LITE -class CodeGeneratorRequest::RequestedFile::Import::Pipeline { -public: - typedef Import Pipelines; - - inline Pipeline(decltype(nullptr)): _typeless(nullptr) {} - inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless) - : _typeless(kj::mv(typeless)) {} - -private: - ::capnp::AnyPointer::Pipeline _typeless; - friend class ::capnp::PipelineHook; - template - friend struct ::capnp::ToDynamic_; -}; -#endif // !CAPNP_LITE - -// ======================================================================================= - -inline ::capnp::schema::Node::Which Node::Reader::which() const { - return _reader.getDataField( - ::capnp::bounded<6>() * ::capnp::ELEMENTS); -} -inline ::capnp::schema::Node::Which Node::Builder::which() { - return _builder.getDataField( - ::capnp::bounded<6>() * ::capnp::ELEMENTS); -} - -inline ::uint64_t Node::Reader::getId() const { - return _reader.getDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint64_t Node::Builder::getId() { - return _builder.getDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Node::Builder::setId( ::uint64_t value) { - _builder.setDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Node::Reader::hasDisplayName() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Node::Builder::hasDisplayName() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::Text::Reader Node::Reader::getDisplayName() const { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::Text::Builder Node::Builder::getDisplayName() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Node::Builder::setDisplayName( ::capnp::Text::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::Text::Builder Node::Builder::initDisplayName(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void Node::Builder::adoptDisplayName( - ::capnp::Orphan< ::capnp::Text>&& value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::Text> Node::Builder::disownDisplayName() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline ::uint32_t Node::Reader::getDisplayNamePrefixLength() const { - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Node::Builder::getDisplayNamePrefixLength() { - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} -inline void Node::Builder::setDisplayNamePrefixLength( ::uint32_t value) { - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, value); -} - -inline ::uint64_t Node::Reader::getScopeId() const { - return _reader.getDataField< ::uint64_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} - -inline ::uint64_t Node::Builder::getScopeId() { - return _builder.getDataField< ::uint64_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} -inline void Node::Builder::setScopeId( ::uint64_t value) { - _builder.setDataField< ::uint64_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, value); -} - -inline bool Node::Reader::hasNestedNodes() const { - return !_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline bool Node::Builder::hasNestedNodes() { - return !_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::schema::Node::NestedNode>::Reader Node::Reader::getNestedNodes() const { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node::NestedNode>>::get(_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::schema::Node::NestedNode>::Builder Node::Builder::getNestedNodes() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node::NestedNode>>::get(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline void Node::Builder::setNestedNodes( ::capnp::List< ::capnp::schema::Node::NestedNode>::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node::NestedNode>>::set(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::schema::Node::NestedNode>::Builder Node::Builder::initNestedNodes(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node::NestedNode>>::init(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), size); -} -inline void Node::Builder::adoptNestedNodes( - ::capnp::Orphan< ::capnp::List< ::capnp::schema::Node::NestedNode>>&& value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node::NestedNode>>::adopt(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Node::NestedNode>> Node::Builder::disownNestedNodes() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node::NestedNode>>::disown(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} - -inline bool Node::Reader::hasAnnotations() const { - return !_reader.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS).isNull(); -} -inline bool Node::Builder::hasAnnotations() { - return !_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::schema::Annotation>::Reader Node::Reader::getAnnotations() const { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::get(_reader.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::schema::Annotation>::Builder Node::Builder::getAnnotations() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::get(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS)); -} -inline void Node::Builder::setAnnotations( ::capnp::List< ::capnp::schema::Annotation>::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::set(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::schema::Annotation>::Builder Node::Builder::initAnnotations(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::init(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS), size); -} -inline void Node::Builder::adoptAnnotations( - ::capnp::Orphan< ::capnp::List< ::capnp::schema::Annotation>>&& value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::adopt(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Annotation>> Node::Builder::disownAnnotations() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::disown(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS)); -} - -inline bool Node::Reader::isFile() const { - return which() == Node::FILE; -} -inline bool Node::Builder::isFile() { - return which() == Node::FILE; -} -inline ::capnp::Void Node::Reader::getFile() const { - KJ_IREQUIRE((which() == Node::FILE), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Node::Builder::getFile() { - KJ_IREQUIRE((which() == Node::FILE), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Node::Builder::setFile( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<6>() * ::capnp::ELEMENTS, Node::FILE); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Node::Reader::isStruct() const { - return which() == Node::STRUCT; -} -inline bool Node::Builder::isStruct() { - return which() == Node::STRUCT; -} -inline typename Node::Struct::Reader Node::Reader::getStruct() const { - KJ_IREQUIRE((which() == Node::STRUCT), - "Must check which() before get()ing a union member."); - return typename Node::Struct::Reader(_reader); -} -inline typename Node::Struct::Builder Node::Builder::getStruct() { - KJ_IREQUIRE((which() == Node::STRUCT), - "Must check which() before get()ing a union member."); - return typename Node::Struct::Builder(_builder); -} -inline typename Node::Struct::Builder Node::Builder::initStruct() { - _builder.setDataField( - ::capnp::bounded<6>() * ::capnp::ELEMENTS, Node::STRUCT); - _builder.setDataField< ::uint16_t>(::capnp::bounded<7>() * ::capnp::ELEMENTS, 0); - _builder.setDataField< ::uint16_t>(::capnp::bounded<12>() * ::capnp::ELEMENTS, 0); - _builder.setDataField< ::uint16_t>(::capnp::bounded<13>() * ::capnp::ELEMENTS, 0); - _builder.setDataField(::capnp::bounded<224>() * ::capnp::ELEMENTS, 0); - _builder.setDataField< ::uint16_t>(::capnp::bounded<15>() * ::capnp::ELEMENTS, 0); - _builder.setDataField< ::uint32_t>(::capnp::bounded<8>() * ::capnp::ELEMENTS, 0); - _builder.getPointerField(::capnp::bounded<3>() * ::capnp::POINTERS).clear(); - return typename Node::Struct::Builder(_builder); -} -inline bool Node::Reader::isEnum() const { - return which() == Node::ENUM; -} -inline bool Node::Builder::isEnum() { - return which() == Node::ENUM; -} -inline typename Node::Enum::Reader Node::Reader::getEnum() const { - KJ_IREQUIRE((which() == Node::ENUM), - "Must check which() before get()ing a union member."); - return typename Node::Enum::Reader(_reader); -} -inline typename Node::Enum::Builder Node::Builder::getEnum() { - KJ_IREQUIRE((which() == Node::ENUM), - "Must check which() before get()ing a union member."); - return typename Node::Enum::Builder(_builder); -} -inline typename Node::Enum::Builder Node::Builder::initEnum() { - _builder.setDataField( - ::capnp::bounded<6>() * ::capnp::ELEMENTS, Node::ENUM); - _builder.getPointerField(::capnp::bounded<3>() * ::capnp::POINTERS).clear(); - return typename Node::Enum::Builder(_builder); -} -inline bool Node::Reader::isInterface() const { - return which() == Node::INTERFACE; -} -inline bool Node::Builder::isInterface() { - return which() == Node::INTERFACE; -} -inline typename Node::Interface::Reader Node::Reader::getInterface() const { - KJ_IREQUIRE((which() == Node::INTERFACE), - "Must check which() before get()ing a union member."); - return typename Node::Interface::Reader(_reader); -} -inline typename Node::Interface::Builder Node::Builder::getInterface() { - KJ_IREQUIRE((which() == Node::INTERFACE), - "Must check which() before get()ing a union member."); - return typename Node::Interface::Builder(_builder); -} -inline typename Node::Interface::Builder Node::Builder::initInterface() { - _builder.setDataField( - ::capnp::bounded<6>() * ::capnp::ELEMENTS, Node::INTERFACE); - _builder.getPointerField(::capnp::bounded<3>() * ::capnp::POINTERS).clear(); - _builder.getPointerField(::capnp::bounded<4>() * ::capnp::POINTERS).clear(); - return typename Node::Interface::Builder(_builder); -} -inline bool Node::Reader::isConst() const { - return which() == Node::CONST; -} -inline bool Node::Builder::isConst() { - return which() == Node::CONST; -} -inline typename Node::Const::Reader Node::Reader::getConst() const { - KJ_IREQUIRE((which() == Node::CONST), - "Must check which() before get()ing a union member."); - return typename Node::Const::Reader(_reader); -} -inline typename Node::Const::Builder Node::Builder::getConst() { - KJ_IREQUIRE((which() == Node::CONST), - "Must check which() before get()ing a union member."); - return typename Node::Const::Builder(_builder); -} -inline typename Node::Const::Builder Node::Builder::initConst() { - _builder.setDataField( - ::capnp::bounded<6>() * ::capnp::ELEMENTS, Node::CONST); - _builder.getPointerField(::capnp::bounded<3>() * ::capnp::POINTERS).clear(); - _builder.getPointerField(::capnp::bounded<4>() * ::capnp::POINTERS).clear(); - return typename Node::Const::Builder(_builder); -} -inline bool Node::Reader::isAnnotation() const { - return which() == Node::ANNOTATION; -} -inline bool Node::Builder::isAnnotation() { - return which() == Node::ANNOTATION; -} -inline typename Node::Annotation::Reader Node::Reader::getAnnotation() const { - KJ_IREQUIRE((which() == Node::ANNOTATION), - "Must check which() before get()ing a union member."); - return typename Node::Annotation::Reader(_reader); -} -inline typename Node::Annotation::Builder Node::Builder::getAnnotation() { - KJ_IREQUIRE((which() == Node::ANNOTATION), - "Must check which() before get()ing a union member."); - return typename Node::Annotation::Builder(_builder); -} -inline typename Node::Annotation::Builder Node::Builder::initAnnotation() { - _builder.setDataField( - ::capnp::bounded<6>() * ::capnp::ELEMENTS, Node::ANNOTATION); - _builder.setDataField(::capnp::bounded<112>() * ::capnp::ELEMENTS, 0); - _builder.setDataField(::capnp::bounded<113>() * ::capnp::ELEMENTS, 0); - _builder.setDataField(::capnp::bounded<114>() * ::capnp::ELEMENTS, 0); - _builder.setDataField(::capnp::bounded<115>() * ::capnp::ELEMENTS, 0); - _builder.setDataField(::capnp::bounded<116>() * ::capnp::ELEMENTS, 0); - _builder.setDataField(::capnp::bounded<117>() * ::capnp::ELEMENTS, 0); - _builder.setDataField(::capnp::bounded<118>() * ::capnp::ELEMENTS, 0); - _builder.setDataField(::capnp::bounded<119>() * ::capnp::ELEMENTS, 0); - _builder.setDataField(::capnp::bounded<120>() * ::capnp::ELEMENTS, 0); - _builder.setDataField(::capnp::bounded<121>() * ::capnp::ELEMENTS, 0); - _builder.setDataField(::capnp::bounded<122>() * ::capnp::ELEMENTS, 0); - _builder.setDataField(::capnp::bounded<123>() * ::capnp::ELEMENTS, 0); - _builder.getPointerField(::capnp::bounded<3>() * ::capnp::POINTERS).clear(); - return typename Node::Annotation::Builder(_builder); -} -inline bool Node::Reader::hasParameters() const { - return !_reader.getPointerField( - ::capnp::bounded<5>() * ::capnp::POINTERS).isNull(); -} -inline bool Node::Builder::hasParameters() { - return !_builder.getPointerField( - ::capnp::bounded<5>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::schema::Node::Parameter>::Reader Node::Reader::getParameters() const { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node::Parameter>>::get(_reader.getPointerField( - ::capnp::bounded<5>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::schema::Node::Parameter>::Builder Node::Builder::getParameters() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node::Parameter>>::get(_builder.getPointerField( - ::capnp::bounded<5>() * ::capnp::POINTERS)); -} -inline void Node::Builder::setParameters( ::capnp::List< ::capnp::schema::Node::Parameter>::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node::Parameter>>::set(_builder.getPointerField( - ::capnp::bounded<5>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::schema::Node::Parameter>::Builder Node::Builder::initParameters(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node::Parameter>>::init(_builder.getPointerField( - ::capnp::bounded<5>() * ::capnp::POINTERS), size); -} -inline void Node::Builder::adoptParameters( - ::capnp::Orphan< ::capnp::List< ::capnp::schema::Node::Parameter>>&& value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node::Parameter>>::adopt(_builder.getPointerField( - ::capnp::bounded<5>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Node::Parameter>> Node::Builder::disownParameters() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node::Parameter>>::disown(_builder.getPointerField( - ::capnp::bounded<5>() * ::capnp::POINTERS)); -} - -inline bool Node::Reader::getIsGeneric() const { - return _reader.getDataField( - ::capnp::bounded<288>() * ::capnp::ELEMENTS); -} - -inline bool Node::Builder::getIsGeneric() { - return _builder.getDataField( - ::capnp::bounded<288>() * ::capnp::ELEMENTS); -} -inline void Node::Builder::setIsGeneric(bool value) { - _builder.setDataField( - ::capnp::bounded<288>() * ::capnp::ELEMENTS, value); -} - -inline bool Node::Parameter::Reader::hasName() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Node::Parameter::Builder::hasName() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::Text::Reader Node::Parameter::Reader::getName() const { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::Text::Builder Node::Parameter::Builder::getName() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Node::Parameter::Builder::setName( ::capnp::Text::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::Text::Builder Node::Parameter::Builder::initName(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void Node::Parameter::Builder::adoptName( - ::capnp::Orphan< ::capnp::Text>&& value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::Text> Node::Parameter::Builder::disownName() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Node::NestedNode::Reader::hasName() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Node::NestedNode::Builder::hasName() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::Text::Reader Node::NestedNode::Reader::getName() const { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::Text::Builder Node::NestedNode::Builder::getName() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Node::NestedNode::Builder::setName( ::capnp::Text::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::Text::Builder Node::NestedNode::Builder::initName(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void Node::NestedNode::Builder::adoptName( - ::capnp::Orphan< ::capnp::Text>&& value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::Text> Node::NestedNode::Builder::disownName() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline ::uint64_t Node::NestedNode::Reader::getId() const { - return _reader.getDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint64_t Node::NestedNode::Builder::getId() { - return _builder.getDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Node::NestedNode::Builder::setId( ::uint64_t value) { - _builder.setDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline ::uint16_t Node::Struct::Reader::getDataWordCount() const { - return _reader.getDataField< ::uint16_t>( - ::capnp::bounded<7>() * ::capnp::ELEMENTS); -} - -inline ::uint16_t Node::Struct::Builder::getDataWordCount() { - return _builder.getDataField< ::uint16_t>( - ::capnp::bounded<7>() * ::capnp::ELEMENTS); -} -inline void Node::Struct::Builder::setDataWordCount( ::uint16_t value) { - _builder.setDataField< ::uint16_t>( - ::capnp::bounded<7>() * ::capnp::ELEMENTS, value); -} - -inline ::uint16_t Node::Struct::Reader::getPointerCount() const { - return _reader.getDataField< ::uint16_t>( - ::capnp::bounded<12>() * ::capnp::ELEMENTS); -} - -inline ::uint16_t Node::Struct::Builder::getPointerCount() { - return _builder.getDataField< ::uint16_t>( - ::capnp::bounded<12>() * ::capnp::ELEMENTS); -} -inline void Node::Struct::Builder::setPointerCount( ::uint16_t value) { - _builder.setDataField< ::uint16_t>( - ::capnp::bounded<12>() * ::capnp::ELEMENTS, value); -} - -inline ::capnp::schema::ElementSize Node::Struct::Reader::getPreferredListEncoding() const { - return _reader.getDataField< ::capnp::schema::ElementSize>( - ::capnp::bounded<13>() * ::capnp::ELEMENTS); -} - -inline ::capnp::schema::ElementSize Node::Struct::Builder::getPreferredListEncoding() { - return _builder.getDataField< ::capnp::schema::ElementSize>( - ::capnp::bounded<13>() * ::capnp::ELEMENTS); -} -inline void Node::Struct::Builder::setPreferredListEncoding( ::capnp::schema::ElementSize value) { - _builder.setDataField< ::capnp::schema::ElementSize>( - ::capnp::bounded<13>() * ::capnp::ELEMENTS, value); -} - -inline bool Node::Struct::Reader::getIsGroup() const { - return _reader.getDataField( - ::capnp::bounded<224>() * ::capnp::ELEMENTS); -} - -inline bool Node::Struct::Builder::getIsGroup() { - return _builder.getDataField( - ::capnp::bounded<224>() * ::capnp::ELEMENTS); -} -inline void Node::Struct::Builder::setIsGroup(bool value) { - _builder.setDataField( - ::capnp::bounded<224>() * ::capnp::ELEMENTS, value); -} - -inline ::uint16_t Node::Struct::Reader::getDiscriminantCount() const { - return _reader.getDataField< ::uint16_t>( - ::capnp::bounded<15>() * ::capnp::ELEMENTS); -} - -inline ::uint16_t Node::Struct::Builder::getDiscriminantCount() { - return _builder.getDataField< ::uint16_t>( - ::capnp::bounded<15>() * ::capnp::ELEMENTS); -} -inline void Node::Struct::Builder::setDiscriminantCount( ::uint16_t value) { - _builder.setDataField< ::uint16_t>( - ::capnp::bounded<15>() * ::capnp::ELEMENTS, value); -} - -inline ::uint32_t Node::Struct::Reader::getDiscriminantOffset() const { - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<8>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Node::Struct::Builder::getDiscriminantOffset() { - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<8>() * ::capnp::ELEMENTS); -} -inline void Node::Struct::Builder::setDiscriminantOffset( ::uint32_t value) { - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<8>() * ::capnp::ELEMENTS, value); -} - -inline bool Node::Struct::Reader::hasFields() const { - return !_reader.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS).isNull(); -} -inline bool Node::Struct::Builder::hasFields() { - return !_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::schema::Field>::Reader Node::Struct::Reader::getFields() const { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Field>>::get(_reader.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::schema::Field>::Builder Node::Struct::Builder::getFields() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Field>>::get(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} -inline void Node::Struct::Builder::setFields( ::capnp::List< ::capnp::schema::Field>::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Field>>::set(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::schema::Field>::Builder Node::Struct::Builder::initFields(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Field>>::init(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS), size); -} -inline void Node::Struct::Builder::adoptFields( - ::capnp::Orphan< ::capnp::List< ::capnp::schema::Field>>&& value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Field>>::adopt(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Field>> Node::Struct::Builder::disownFields() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Field>>::disown(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} - -inline bool Node::Enum::Reader::hasEnumerants() const { - return !_reader.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS).isNull(); -} -inline bool Node::Enum::Builder::hasEnumerants() { - return !_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::schema::Enumerant>::Reader Node::Enum::Reader::getEnumerants() const { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Enumerant>>::get(_reader.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::schema::Enumerant>::Builder Node::Enum::Builder::getEnumerants() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Enumerant>>::get(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} -inline void Node::Enum::Builder::setEnumerants( ::capnp::List< ::capnp::schema::Enumerant>::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Enumerant>>::set(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::schema::Enumerant>::Builder Node::Enum::Builder::initEnumerants(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Enumerant>>::init(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS), size); -} -inline void Node::Enum::Builder::adoptEnumerants( - ::capnp::Orphan< ::capnp::List< ::capnp::schema::Enumerant>>&& value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Enumerant>>::adopt(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Enumerant>> Node::Enum::Builder::disownEnumerants() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Enumerant>>::disown(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} - -inline bool Node::Interface::Reader::hasMethods() const { - return !_reader.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS).isNull(); -} -inline bool Node::Interface::Builder::hasMethods() { - return !_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::schema::Method>::Reader Node::Interface::Reader::getMethods() const { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Method>>::get(_reader.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::schema::Method>::Builder Node::Interface::Builder::getMethods() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Method>>::get(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} -inline void Node::Interface::Builder::setMethods( ::capnp::List< ::capnp::schema::Method>::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Method>>::set(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::schema::Method>::Builder Node::Interface::Builder::initMethods(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Method>>::init(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS), size); -} -inline void Node::Interface::Builder::adoptMethods( - ::capnp::Orphan< ::capnp::List< ::capnp::schema::Method>>&& value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Method>>::adopt(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Method>> Node::Interface::Builder::disownMethods() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Method>>::disown(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} - -inline bool Node::Interface::Reader::hasSuperclasses() const { - return !_reader.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS).isNull(); -} -inline bool Node::Interface::Builder::hasSuperclasses() { - return !_builder.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::schema::Superclass>::Reader Node::Interface::Reader::getSuperclasses() const { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Superclass>>::get(_reader.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::schema::Superclass>::Builder Node::Interface::Builder::getSuperclasses() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Superclass>>::get(_builder.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS)); -} -inline void Node::Interface::Builder::setSuperclasses( ::capnp::List< ::capnp::schema::Superclass>::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Superclass>>::set(_builder.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::schema::Superclass>::Builder Node::Interface::Builder::initSuperclasses(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Superclass>>::init(_builder.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS), size); -} -inline void Node::Interface::Builder::adoptSuperclasses( - ::capnp::Orphan< ::capnp::List< ::capnp::schema::Superclass>>&& value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Superclass>>::adopt(_builder.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Superclass>> Node::Interface::Builder::disownSuperclasses() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Superclass>>::disown(_builder.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS)); -} - -inline bool Node::Const::Reader::hasType() const { - return !_reader.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS).isNull(); -} -inline bool Node::Const::Builder::hasType() { - return !_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::schema::Type::Reader Node::Const::Reader::getType() const { - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::get(_reader.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} -inline ::capnp::schema::Type::Builder Node::Const::Builder::getType() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::get(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::schema::Type::Pipeline Node::Const::Pipeline::getType() { - return ::capnp::schema::Type::Pipeline(_typeless.getPointerField(3)); -} -#endif // !CAPNP_LITE -inline void Node::Const::Builder::setType( ::capnp::schema::Type::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Type>::set(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS), value); -} -inline ::capnp::schema::Type::Builder Node::Const::Builder::initType() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::init(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} -inline void Node::Const::Builder::adoptType( - ::capnp::Orphan< ::capnp::schema::Type>&& value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Type>::adopt(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::schema::Type> Node::Const::Builder::disownType() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::disown(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} - -inline bool Node::Const::Reader::hasValue() const { - return !_reader.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS).isNull(); -} -inline bool Node::Const::Builder::hasValue() { - return !_builder.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::schema::Value::Reader Node::Const::Reader::getValue() const { - return ::capnp::_::PointerHelpers< ::capnp::schema::Value>::get(_reader.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS)); -} -inline ::capnp::schema::Value::Builder Node::Const::Builder::getValue() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Value>::get(_builder.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::schema::Value::Pipeline Node::Const::Pipeline::getValue() { - return ::capnp::schema::Value::Pipeline(_typeless.getPointerField(4)); -} -#endif // !CAPNP_LITE -inline void Node::Const::Builder::setValue( ::capnp::schema::Value::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Value>::set(_builder.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS), value); -} -inline ::capnp::schema::Value::Builder Node::Const::Builder::initValue() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Value>::init(_builder.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS)); -} -inline void Node::Const::Builder::adoptValue( - ::capnp::Orphan< ::capnp::schema::Value>&& value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Value>::adopt(_builder.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::schema::Value> Node::Const::Builder::disownValue() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Value>::disown(_builder.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS)); -} - -inline bool Node::Annotation::Reader::hasType() const { - return !_reader.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS).isNull(); -} -inline bool Node::Annotation::Builder::hasType() { - return !_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::schema::Type::Reader Node::Annotation::Reader::getType() const { - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::get(_reader.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} -inline ::capnp::schema::Type::Builder Node::Annotation::Builder::getType() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::get(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::schema::Type::Pipeline Node::Annotation::Pipeline::getType() { - return ::capnp::schema::Type::Pipeline(_typeless.getPointerField(3)); -} -#endif // !CAPNP_LITE -inline void Node::Annotation::Builder::setType( ::capnp::schema::Type::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Type>::set(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS), value); -} -inline ::capnp::schema::Type::Builder Node::Annotation::Builder::initType() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::init(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} -inline void Node::Annotation::Builder::adoptType( - ::capnp::Orphan< ::capnp::schema::Type>&& value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Type>::adopt(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::schema::Type> Node::Annotation::Builder::disownType() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::disown(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} - -inline bool Node::Annotation::Reader::getTargetsFile() const { - return _reader.getDataField( - ::capnp::bounded<112>() * ::capnp::ELEMENTS); -} - -inline bool Node::Annotation::Builder::getTargetsFile() { - return _builder.getDataField( - ::capnp::bounded<112>() * ::capnp::ELEMENTS); -} -inline void Node::Annotation::Builder::setTargetsFile(bool value) { - _builder.setDataField( - ::capnp::bounded<112>() * ::capnp::ELEMENTS, value); -} - -inline bool Node::Annotation::Reader::getTargetsConst() const { - return _reader.getDataField( - ::capnp::bounded<113>() * ::capnp::ELEMENTS); -} - -inline bool Node::Annotation::Builder::getTargetsConst() { - return _builder.getDataField( - ::capnp::bounded<113>() * ::capnp::ELEMENTS); -} -inline void Node::Annotation::Builder::setTargetsConst(bool value) { - _builder.setDataField( - ::capnp::bounded<113>() * ::capnp::ELEMENTS, value); -} - -inline bool Node::Annotation::Reader::getTargetsEnum() const { - return _reader.getDataField( - ::capnp::bounded<114>() * ::capnp::ELEMENTS); -} - -inline bool Node::Annotation::Builder::getTargetsEnum() { - return _builder.getDataField( - ::capnp::bounded<114>() * ::capnp::ELEMENTS); -} -inline void Node::Annotation::Builder::setTargetsEnum(bool value) { - _builder.setDataField( - ::capnp::bounded<114>() * ::capnp::ELEMENTS, value); -} - -inline bool Node::Annotation::Reader::getTargetsEnumerant() const { - return _reader.getDataField( - ::capnp::bounded<115>() * ::capnp::ELEMENTS); -} - -inline bool Node::Annotation::Builder::getTargetsEnumerant() { - return _builder.getDataField( - ::capnp::bounded<115>() * ::capnp::ELEMENTS); -} -inline void Node::Annotation::Builder::setTargetsEnumerant(bool value) { - _builder.setDataField( - ::capnp::bounded<115>() * ::capnp::ELEMENTS, value); -} - -inline bool Node::Annotation::Reader::getTargetsStruct() const { - return _reader.getDataField( - ::capnp::bounded<116>() * ::capnp::ELEMENTS); -} - -inline bool Node::Annotation::Builder::getTargetsStruct() { - return _builder.getDataField( - ::capnp::bounded<116>() * ::capnp::ELEMENTS); -} -inline void Node::Annotation::Builder::setTargetsStruct(bool value) { - _builder.setDataField( - ::capnp::bounded<116>() * ::capnp::ELEMENTS, value); -} - -inline bool Node::Annotation::Reader::getTargetsField() const { - return _reader.getDataField( - ::capnp::bounded<117>() * ::capnp::ELEMENTS); -} - -inline bool Node::Annotation::Builder::getTargetsField() { - return _builder.getDataField( - ::capnp::bounded<117>() * ::capnp::ELEMENTS); -} -inline void Node::Annotation::Builder::setTargetsField(bool value) { - _builder.setDataField( - ::capnp::bounded<117>() * ::capnp::ELEMENTS, value); -} - -inline bool Node::Annotation::Reader::getTargetsUnion() const { - return _reader.getDataField( - ::capnp::bounded<118>() * ::capnp::ELEMENTS); -} - -inline bool Node::Annotation::Builder::getTargetsUnion() { - return _builder.getDataField( - ::capnp::bounded<118>() * ::capnp::ELEMENTS); -} -inline void Node::Annotation::Builder::setTargetsUnion(bool value) { - _builder.setDataField( - ::capnp::bounded<118>() * ::capnp::ELEMENTS, value); -} - -inline bool Node::Annotation::Reader::getTargetsGroup() const { - return _reader.getDataField( - ::capnp::bounded<119>() * ::capnp::ELEMENTS); -} - -inline bool Node::Annotation::Builder::getTargetsGroup() { - return _builder.getDataField( - ::capnp::bounded<119>() * ::capnp::ELEMENTS); -} -inline void Node::Annotation::Builder::setTargetsGroup(bool value) { - _builder.setDataField( - ::capnp::bounded<119>() * ::capnp::ELEMENTS, value); -} - -inline bool Node::Annotation::Reader::getTargetsInterface() const { - return _reader.getDataField( - ::capnp::bounded<120>() * ::capnp::ELEMENTS); -} - -inline bool Node::Annotation::Builder::getTargetsInterface() { - return _builder.getDataField( - ::capnp::bounded<120>() * ::capnp::ELEMENTS); -} -inline void Node::Annotation::Builder::setTargetsInterface(bool value) { - _builder.setDataField( - ::capnp::bounded<120>() * ::capnp::ELEMENTS, value); -} - -inline bool Node::Annotation::Reader::getTargetsMethod() const { - return _reader.getDataField( - ::capnp::bounded<121>() * ::capnp::ELEMENTS); -} - -inline bool Node::Annotation::Builder::getTargetsMethod() { - return _builder.getDataField( - ::capnp::bounded<121>() * ::capnp::ELEMENTS); -} -inline void Node::Annotation::Builder::setTargetsMethod(bool value) { - _builder.setDataField( - ::capnp::bounded<121>() * ::capnp::ELEMENTS, value); -} - -inline bool Node::Annotation::Reader::getTargetsParam() const { - return _reader.getDataField( - ::capnp::bounded<122>() * ::capnp::ELEMENTS); -} - -inline bool Node::Annotation::Builder::getTargetsParam() { - return _builder.getDataField( - ::capnp::bounded<122>() * ::capnp::ELEMENTS); -} -inline void Node::Annotation::Builder::setTargetsParam(bool value) { - _builder.setDataField( - ::capnp::bounded<122>() * ::capnp::ELEMENTS, value); -} - -inline bool Node::Annotation::Reader::getTargetsAnnotation() const { - return _reader.getDataField( - ::capnp::bounded<123>() * ::capnp::ELEMENTS); -} - -inline bool Node::Annotation::Builder::getTargetsAnnotation() { - return _builder.getDataField( - ::capnp::bounded<123>() * ::capnp::ELEMENTS); -} -inline void Node::Annotation::Builder::setTargetsAnnotation(bool value) { - _builder.setDataField( - ::capnp::bounded<123>() * ::capnp::ELEMENTS, value); -} - -inline ::capnp::schema::Field::Which Field::Reader::which() const { - return _reader.getDataField( - ::capnp::bounded<4>() * ::capnp::ELEMENTS); -} -inline ::capnp::schema::Field::Which Field::Builder::which() { - return _builder.getDataField( - ::capnp::bounded<4>() * ::capnp::ELEMENTS); -} - -inline bool Field::Reader::hasName() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Field::Builder::hasName() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::Text::Reader Field::Reader::getName() const { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::Text::Builder Field::Builder::getName() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Field::Builder::setName( ::capnp::Text::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::Text::Builder Field::Builder::initName(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void Field::Builder::adoptName( - ::capnp::Orphan< ::capnp::Text>&& value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::Text> Field::Builder::disownName() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline ::uint16_t Field::Reader::getCodeOrder() const { - return _reader.getDataField< ::uint16_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint16_t Field::Builder::getCodeOrder() { - return _builder.getDataField< ::uint16_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Field::Builder::setCodeOrder( ::uint16_t value) { - _builder.setDataField< ::uint16_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Field::Reader::hasAnnotations() const { - return !_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline bool Field::Builder::hasAnnotations() { - return !_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::schema::Annotation>::Reader Field::Reader::getAnnotations() const { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::get(_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::schema::Annotation>::Builder Field::Builder::getAnnotations() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::get(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline void Field::Builder::setAnnotations( ::capnp::List< ::capnp::schema::Annotation>::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::set(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::schema::Annotation>::Builder Field::Builder::initAnnotations(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::init(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), size); -} -inline void Field::Builder::adoptAnnotations( - ::capnp::Orphan< ::capnp::List< ::capnp::schema::Annotation>>&& value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::adopt(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Annotation>> Field::Builder::disownAnnotations() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::disown(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} - -inline ::uint16_t Field::Reader::getDiscriminantValue() const { - return _reader.getDataField< ::uint16_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, 65535u); -} - -inline ::uint16_t Field::Builder::getDiscriminantValue() { - return _builder.getDataField< ::uint16_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, 65535u); -} -inline void Field::Builder::setDiscriminantValue( ::uint16_t value) { - _builder.setDataField< ::uint16_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value, 65535u); -} - -inline bool Field::Reader::isSlot() const { - return which() == Field::SLOT; -} -inline bool Field::Builder::isSlot() { - return which() == Field::SLOT; -} -inline typename Field::Slot::Reader Field::Reader::getSlot() const { - KJ_IREQUIRE((which() == Field::SLOT), - "Must check which() before get()ing a union member."); - return typename Field::Slot::Reader(_reader); -} -inline typename Field::Slot::Builder Field::Builder::getSlot() { - KJ_IREQUIRE((which() == Field::SLOT), - "Must check which() before get()ing a union member."); - return typename Field::Slot::Builder(_builder); -} -inline typename Field::Slot::Builder Field::Builder::initSlot() { - _builder.setDataField( - ::capnp::bounded<4>() * ::capnp::ELEMENTS, Field::SLOT); - _builder.setDataField< ::uint32_t>(::capnp::bounded<1>() * ::capnp::ELEMENTS, 0); - _builder.setDataField(::capnp::bounded<128>() * ::capnp::ELEMENTS, 0); - _builder.getPointerField(::capnp::bounded<2>() * ::capnp::POINTERS).clear(); - _builder.getPointerField(::capnp::bounded<3>() * ::capnp::POINTERS).clear(); - return typename Field::Slot::Builder(_builder); -} -inline bool Field::Reader::isGroup() const { - return which() == Field::GROUP; -} -inline bool Field::Builder::isGroup() { - return which() == Field::GROUP; -} -inline typename Field::Group::Reader Field::Reader::getGroup() const { - KJ_IREQUIRE((which() == Field::GROUP), - "Must check which() before get()ing a union member."); - return typename Field::Group::Reader(_reader); -} -inline typename Field::Group::Builder Field::Builder::getGroup() { - KJ_IREQUIRE((which() == Field::GROUP), - "Must check which() before get()ing a union member."); - return typename Field::Group::Builder(_builder); -} -inline typename Field::Group::Builder Field::Builder::initGroup() { - _builder.setDataField( - ::capnp::bounded<4>() * ::capnp::ELEMENTS, Field::GROUP); - _builder.setDataField< ::uint64_t>(::capnp::bounded<2>() * ::capnp::ELEMENTS, 0); - return typename Field::Group::Builder(_builder); -} -inline typename Field::Ordinal::Reader Field::Reader::getOrdinal() const { - return typename Field::Ordinal::Reader(_reader); -} -inline typename Field::Ordinal::Builder Field::Builder::getOrdinal() { - return typename Field::Ordinal::Builder(_builder); -} -#if !CAPNP_LITE -inline typename Field::Ordinal::Pipeline Field::Pipeline::getOrdinal() { - return typename Field::Ordinal::Pipeline(_typeless.noop()); -} -#endif // !CAPNP_LITE -inline typename Field::Ordinal::Builder Field::Builder::initOrdinal() { - _builder.setDataField< ::uint16_t>(::capnp::bounded<5>() * ::capnp::ELEMENTS, 0); - _builder.setDataField< ::uint16_t>(::capnp::bounded<6>() * ::capnp::ELEMENTS, 0); - return typename Field::Ordinal::Builder(_builder); -} -inline ::uint32_t Field::Slot::Reader::getOffset() const { - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Field::Slot::Builder::getOffset() { - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void Field::Slot::Builder::setOffset( ::uint32_t value) { - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline bool Field::Slot::Reader::hasType() const { - return !_reader.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS).isNull(); -} -inline bool Field::Slot::Builder::hasType() { - return !_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::schema::Type::Reader Field::Slot::Reader::getType() const { - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::get(_reader.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS)); -} -inline ::capnp::schema::Type::Builder Field::Slot::Builder::getType() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::get(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::schema::Type::Pipeline Field::Slot::Pipeline::getType() { - return ::capnp::schema::Type::Pipeline(_typeless.getPointerField(2)); -} -#endif // !CAPNP_LITE -inline void Field::Slot::Builder::setType( ::capnp::schema::Type::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Type>::set(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS), value); -} -inline ::capnp::schema::Type::Builder Field::Slot::Builder::initType() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::init(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS)); -} -inline void Field::Slot::Builder::adoptType( - ::capnp::Orphan< ::capnp::schema::Type>&& value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Type>::adopt(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::schema::Type> Field::Slot::Builder::disownType() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::disown(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS)); -} - -inline bool Field::Slot::Reader::hasDefaultValue() const { - return !_reader.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS).isNull(); -} -inline bool Field::Slot::Builder::hasDefaultValue() { - return !_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::schema::Value::Reader Field::Slot::Reader::getDefaultValue() const { - return ::capnp::_::PointerHelpers< ::capnp::schema::Value>::get(_reader.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} -inline ::capnp::schema::Value::Builder Field::Slot::Builder::getDefaultValue() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Value>::get(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::schema::Value::Pipeline Field::Slot::Pipeline::getDefaultValue() { - return ::capnp::schema::Value::Pipeline(_typeless.getPointerField(3)); -} -#endif // !CAPNP_LITE -inline void Field::Slot::Builder::setDefaultValue( ::capnp::schema::Value::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Value>::set(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS), value); -} -inline ::capnp::schema::Value::Builder Field::Slot::Builder::initDefaultValue() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Value>::init(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} -inline void Field::Slot::Builder::adoptDefaultValue( - ::capnp::Orphan< ::capnp::schema::Value>&& value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Value>::adopt(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::schema::Value> Field::Slot::Builder::disownDefaultValue() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Value>::disown(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} - -inline bool Field::Slot::Reader::getHadExplicitDefault() const { - return _reader.getDataField( - ::capnp::bounded<128>() * ::capnp::ELEMENTS); -} - -inline bool Field::Slot::Builder::getHadExplicitDefault() { - return _builder.getDataField( - ::capnp::bounded<128>() * ::capnp::ELEMENTS); -} -inline void Field::Slot::Builder::setHadExplicitDefault(bool value) { - _builder.setDataField( - ::capnp::bounded<128>() * ::capnp::ELEMENTS, value); -} - -inline ::uint64_t Field::Group::Reader::getTypeId() const { - return _reader.getDataField< ::uint64_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} - -inline ::uint64_t Field::Group::Builder::getTypeId() { - return _builder.getDataField< ::uint64_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} -inline void Field::Group::Builder::setTypeId( ::uint64_t value) { - _builder.setDataField< ::uint64_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, value); -} - -inline ::capnp::schema::Field::Ordinal::Which Field::Ordinal::Reader::which() const { - return _reader.getDataField( - ::capnp::bounded<5>() * ::capnp::ELEMENTS); -} -inline ::capnp::schema::Field::Ordinal::Which Field::Ordinal::Builder::which() { - return _builder.getDataField( - ::capnp::bounded<5>() * ::capnp::ELEMENTS); -} - -inline bool Field::Ordinal::Reader::isImplicit() const { - return which() == Field::Ordinal::IMPLICIT; -} -inline bool Field::Ordinal::Builder::isImplicit() { - return which() == Field::Ordinal::IMPLICIT; -} -inline ::capnp::Void Field::Ordinal::Reader::getImplicit() const { - KJ_IREQUIRE((which() == Field::Ordinal::IMPLICIT), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Field::Ordinal::Builder::getImplicit() { - KJ_IREQUIRE((which() == Field::Ordinal::IMPLICIT), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Field::Ordinal::Builder::setImplicit( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<5>() * ::capnp::ELEMENTS, Field::Ordinal::IMPLICIT); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Field::Ordinal::Reader::isExplicit() const { - return which() == Field::Ordinal::EXPLICIT; -} -inline bool Field::Ordinal::Builder::isExplicit() { - return which() == Field::Ordinal::EXPLICIT; -} -inline ::uint16_t Field::Ordinal::Reader::getExplicit() const { - KJ_IREQUIRE((which() == Field::Ordinal::EXPLICIT), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::uint16_t>( - ::capnp::bounded<6>() * ::capnp::ELEMENTS); -} - -inline ::uint16_t Field::Ordinal::Builder::getExplicit() { - KJ_IREQUIRE((which() == Field::Ordinal::EXPLICIT), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::uint16_t>( - ::capnp::bounded<6>() * ::capnp::ELEMENTS); -} -inline void Field::Ordinal::Builder::setExplicit( ::uint16_t value) { - _builder.setDataField( - ::capnp::bounded<5>() * ::capnp::ELEMENTS, Field::Ordinal::EXPLICIT); - _builder.setDataField< ::uint16_t>( - ::capnp::bounded<6>() * ::capnp::ELEMENTS, value); -} - -inline bool Enumerant::Reader::hasName() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Enumerant::Builder::hasName() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::Text::Reader Enumerant::Reader::getName() const { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::Text::Builder Enumerant::Builder::getName() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Enumerant::Builder::setName( ::capnp::Text::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::Text::Builder Enumerant::Builder::initName(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void Enumerant::Builder::adoptName( - ::capnp::Orphan< ::capnp::Text>&& value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::Text> Enumerant::Builder::disownName() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline ::uint16_t Enumerant::Reader::getCodeOrder() const { - return _reader.getDataField< ::uint16_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint16_t Enumerant::Builder::getCodeOrder() { - return _builder.getDataField< ::uint16_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Enumerant::Builder::setCodeOrder( ::uint16_t value) { - _builder.setDataField< ::uint16_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Enumerant::Reader::hasAnnotations() const { - return !_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline bool Enumerant::Builder::hasAnnotations() { - return !_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::schema::Annotation>::Reader Enumerant::Reader::getAnnotations() const { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::get(_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::schema::Annotation>::Builder Enumerant::Builder::getAnnotations() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::get(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline void Enumerant::Builder::setAnnotations( ::capnp::List< ::capnp::schema::Annotation>::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::set(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::schema::Annotation>::Builder Enumerant::Builder::initAnnotations(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::init(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), size); -} -inline void Enumerant::Builder::adoptAnnotations( - ::capnp::Orphan< ::capnp::List< ::capnp::schema::Annotation>>&& value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::adopt(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Annotation>> Enumerant::Builder::disownAnnotations() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::disown(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} - -inline ::uint64_t Superclass::Reader::getId() const { - return _reader.getDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint64_t Superclass::Builder::getId() { - return _builder.getDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Superclass::Builder::setId( ::uint64_t value) { - _builder.setDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Superclass::Reader::hasBrand() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Superclass::Builder::hasBrand() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::schema::Brand::Reader Superclass::Reader::getBrand() const { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::schema::Brand::Builder Superclass::Builder::getBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::schema::Brand::Pipeline Superclass::Pipeline::getBrand() { - return ::capnp::schema::Brand::Pipeline(_typeless.getPointerField(0)); -} -#endif // !CAPNP_LITE -inline void Superclass::Builder::setBrand( ::capnp::schema::Brand::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::schema::Brand::Builder Superclass::Builder::initBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Superclass::Builder::adoptBrand( - ::capnp::Orphan< ::capnp::schema::Brand>&& value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::schema::Brand> Superclass::Builder::disownBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Method::Reader::hasName() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Method::Builder::hasName() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::Text::Reader Method::Reader::getName() const { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::Text::Builder Method::Builder::getName() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Method::Builder::setName( ::capnp::Text::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::Text::Builder Method::Builder::initName(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void Method::Builder::adoptName( - ::capnp::Orphan< ::capnp::Text>&& value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::Text> Method::Builder::disownName() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline ::uint16_t Method::Reader::getCodeOrder() const { - return _reader.getDataField< ::uint16_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint16_t Method::Builder::getCodeOrder() { - return _builder.getDataField< ::uint16_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Method::Builder::setCodeOrder( ::uint16_t value) { - _builder.setDataField< ::uint16_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline ::uint64_t Method::Reader::getParamStructType() const { - return _reader.getDataField< ::uint64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline ::uint64_t Method::Builder::getParamStructType() { - return _builder.getDataField< ::uint64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void Method::Builder::setParamStructType( ::uint64_t value) { - _builder.setDataField< ::uint64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline ::uint64_t Method::Reader::getResultStructType() const { - return _reader.getDataField< ::uint64_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} - -inline ::uint64_t Method::Builder::getResultStructType() { - return _builder.getDataField< ::uint64_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} -inline void Method::Builder::setResultStructType( ::uint64_t value) { - _builder.setDataField< ::uint64_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, value); -} - -inline bool Method::Reader::hasAnnotations() const { - return !_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline bool Method::Builder::hasAnnotations() { - return !_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::schema::Annotation>::Reader Method::Reader::getAnnotations() const { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::get(_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::schema::Annotation>::Builder Method::Builder::getAnnotations() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::get(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline void Method::Builder::setAnnotations( ::capnp::List< ::capnp::schema::Annotation>::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::set(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::schema::Annotation>::Builder Method::Builder::initAnnotations(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::init(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), size); -} -inline void Method::Builder::adoptAnnotations( - ::capnp::Orphan< ::capnp::List< ::capnp::schema::Annotation>>&& value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::adopt(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Annotation>> Method::Builder::disownAnnotations() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Annotation>>::disown(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} - -inline bool Method::Reader::hasParamBrand() const { - return !_reader.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS).isNull(); -} -inline bool Method::Builder::hasParamBrand() { - return !_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::schema::Brand::Reader Method::Reader::getParamBrand() const { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::get(_reader.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS)); -} -inline ::capnp::schema::Brand::Builder Method::Builder::getParamBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::get(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::schema::Brand::Pipeline Method::Pipeline::getParamBrand() { - return ::capnp::schema::Brand::Pipeline(_typeless.getPointerField(2)); -} -#endif // !CAPNP_LITE -inline void Method::Builder::setParamBrand( ::capnp::schema::Brand::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::set(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS), value); -} -inline ::capnp::schema::Brand::Builder Method::Builder::initParamBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::init(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS)); -} -inline void Method::Builder::adoptParamBrand( - ::capnp::Orphan< ::capnp::schema::Brand>&& value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::adopt(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::schema::Brand> Method::Builder::disownParamBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::disown(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS)); -} - -inline bool Method::Reader::hasResultBrand() const { - return !_reader.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS).isNull(); -} -inline bool Method::Builder::hasResultBrand() { - return !_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::schema::Brand::Reader Method::Reader::getResultBrand() const { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::get(_reader.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} -inline ::capnp::schema::Brand::Builder Method::Builder::getResultBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::get(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::schema::Brand::Pipeline Method::Pipeline::getResultBrand() { - return ::capnp::schema::Brand::Pipeline(_typeless.getPointerField(3)); -} -#endif // !CAPNP_LITE -inline void Method::Builder::setResultBrand( ::capnp::schema::Brand::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::set(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS), value); -} -inline ::capnp::schema::Brand::Builder Method::Builder::initResultBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::init(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} -inline void Method::Builder::adoptResultBrand( - ::capnp::Orphan< ::capnp::schema::Brand>&& value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::adopt(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::schema::Brand> Method::Builder::disownResultBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::disown(_builder.getPointerField( - ::capnp::bounded<3>() * ::capnp::POINTERS)); -} - -inline bool Method::Reader::hasImplicitParameters() const { - return !_reader.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS).isNull(); -} -inline bool Method::Builder::hasImplicitParameters() { - return !_builder.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::schema::Node::Parameter>::Reader Method::Reader::getImplicitParameters() const { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node::Parameter>>::get(_reader.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::schema::Node::Parameter>::Builder Method::Builder::getImplicitParameters() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node::Parameter>>::get(_builder.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS)); -} -inline void Method::Builder::setImplicitParameters( ::capnp::List< ::capnp::schema::Node::Parameter>::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node::Parameter>>::set(_builder.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::schema::Node::Parameter>::Builder Method::Builder::initImplicitParameters(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node::Parameter>>::init(_builder.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS), size); -} -inline void Method::Builder::adoptImplicitParameters( - ::capnp::Orphan< ::capnp::List< ::capnp::schema::Node::Parameter>>&& value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node::Parameter>>::adopt(_builder.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Node::Parameter>> Method::Builder::disownImplicitParameters() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node::Parameter>>::disown(_builder.getPointerField( - ::capnp::bounded<4>() * ::capnp::POINTERS)); -} - -inline ::capnp::schema::Type::Which Type::Reader::which() const { - return _reader.getDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline ::capnp::schema::Type::Which Type::Builder::which() { - return _builder.getDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline bool Type::Reader::isVoid() const { - return which() == Type::VOID; -} -inline bool Type::Builder::isVoid() { - return which() == Type::VOID; -} -inline ::capnp::Void Type::Reader::getVoid() const { - KJ_IREQUIRE((which() == Type::VOID), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Type::Builder::getVoid() { - KJ_IREQUIRE((which() == Type::VOID), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Type::Builder::setVoid( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Type::VOID); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::Reader::isBool() const { - return which() == Type::BOOL; -} -inline bool Type::Builder::isBool() { - return which() == Type::BOOL; -} -inline ::capnp::Void Type::Reader::getBool() const { - KJ_IREQUIRE((which() == Type::BOOL), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Type::Builder::getBool() { - KJ_IREQUIRE((which() == Type::BOOL), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Type::Builder::setBool( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Type::BOOL); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::Reader::isInt8() const { - return which() == Type::INT8; -} -inline bool Type::Builder::isInt8() { - return which() == Type::INT8; -} -inline ::capnp::Void Type::Reader::getInt8() const { - KJ_IREQUIRE((which() == Type::INT8), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Type::Builder::getInt8() { - KJ_IREQUIRE((which() == Type::INT8), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Type::Builder::setInt8( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Type::INT8); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::Reader::isInt16() const { - return which() == Type::INT16; -} -inline bool Type::Builder::isInt16() { - return which() == Type::INT16; -} -inline ::capnp::Void Type::Reader::getInt16() const { - KJ_IREQUIRE((which() == Type::INT16), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Type::Builder::getInt16() { - KJ_IREQUIRE((which() == Type::INT16), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Type::Builder::setInt16( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Type::INT16); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::Reader::isInt32() const { - return which() == Type::INT32; -} -inline bool Type::Builder::isInt32() { - return which() == Type::INT32; -} -inline ::capnp::Void Type::Reader::getInt32() const { - KJ_IREQUIRE((which() == Type::INT32), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Type::Builder::getInt32() { - KJ_IREQUIRE((which() == Type::INT32), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Type::Builder::setInt32( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Type::INT32); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::Reader::isInt64() const { - return which() == Type::INT64; -} -inline bool Type::Builder::isInt64() { - return which() == Type::INT64; -} -inline ::capnp::Void Type::Reader::getInt64() const { - KJ_IREQUIRE((which() == Type::INT64), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Type::Builder::getInt64() { - KJ_IREQUIRE((which() == Type::INT64), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Type::Builder::setInt64( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Type::INT64); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::Reader::isUint8() const { - return which() == Type::UINT8; -} -inline bool Type::Builder::isUint8() { - return which() == Type::UINT8; -} -inline ::capnp::Void Type::Reader::getUint8() const { - KJ_IREQUIRE((which() == Type::UINT8), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Type::Builder::getUint8() { - KJ_IREQUIRE((which() == Type::UINT8), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Type::Builder::setUint8( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Type::UINT8); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::Reader::isUint16() const { - return which() == Type::UINT16; -} -inline bool Type::Builder::isUint16() { - return which() == Type::UINT16; -} -inline ::capnp::Void Type::Reader::getUint16() const { - KJ_IREQUIRE((which() == Type::UINT16), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Type::Builder::getUint16() { - KJ_IREQUIRE((which() == Type::UINT16), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Type::Builder::setUint16( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Type::UINT16); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::Reader::isUint32() const { - return which() == Type::UINT32; -} -inline bool Type::Builder::isUint32() { - return which() == Type::UINT32; -} -inline ::capnp::Void Type::Reader::getUint32() const { - KJ_IREQUIRE((which() == Type::UINT32), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Type::Builder::getUint32() { - KJ_IREQUIRE((which() == Type::UINT32), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Type::Builder::setUint32( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Type::UINT32); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::Reader::isUint64() const { - return which() == Type::UINT64; -} -inline bool Type::Builder::isUint64() { - return which() == Type::UINT64; -} -inline ::capnp::Void Type::Reader::getUint64() const { - KJ_IREQUIRE((which() == Type::UINT64), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Type::Builder::getUint64() { - KJ_IREQUIRE((which() == Type::UINT64), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Type::Builder::setUint64( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Type::UINT64); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::Reader::isFloat32() const { - return which() == Type::FLOAT32; -} -inline bool Type::Builder::isFloat32() { - return which() == Type::FLOAT32; -} -inline ::capnp::Void Type::Reader::getFloat32() const { - KJ_IREQUIRE((which() == Type::FLOAT32), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Type::Builder::getFloat32() { - KJ_IREQUIRE((which() == Type::FLOAT32), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Type::Builder::setFloat32( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Type::FLOAT32); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::Reader::isFloat64() const { - return which() == Type::FLOAT64; -} -inline bool Type::Builder::isFloat64() { - return which() == Type::FLOAT64; -} -inline ::capnp::Void Type::Reader::getFloat64() const { - KJ_IREQUIRE((which() == Type::FLOAT64), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Type::Builder::getFloat64() { - KJ_IREQUIRE((which() == Type::FLOAT64), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Type::Builder::setFloat64( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Type::FLOAT64); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::Reader::isText() const { - return which() == Type::TEXT; -} -inline bool Type::Builder::isText() { - return which() == Type::TEXT; -} -inline ::capnp::Void Type::Reader::getText() const { - KJ_IREQUIRE((which() == Type::TEXT), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Type::Builder::getText() { - KJ_IREQUIRE((which() == Type::TEXT), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Type::Builder::setText( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Type::TEXT); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::Reader::isData() const { - return which() == Type::DATA; -} -inline bool Type::Builder::isData() { - return which() == Type::DATA; -} -inline ::capnp::Void Type::Reader::getData() const { - KJ_IREQUIRE((which() == Type::DATA), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Type::Builder::getData() { - KJ_IREQUIRE((which() == Type::DATA), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Type::Builder::setData( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Type::DATA); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::Reader::isList() const { - return which() == Type::LIST; -} -inline bool Type::Builder::isList() { - return which() == Type::LIST; -} -inline typename Type::List::Reader Type::Reader::getList() const { - KJ_IREQUIRE((which() == Type::LIST), - "Must check which() before get()ing a union member."); - return typename Type::List::Reader(_reader); -} -inline typename Type::List::Builder Type::Builder::getList() { - KJ_IREQUIRE((which() == Type::LIST), - "Must check which() before get()ing a union member."); - return typename Type::List::Builder(_builder); -} -inline typename Type::List::Builder Type::Builder::initList() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Type::LIST); - _builder.getPointerField(::capnp::bounded<0>() * ::capnp::POINTERS).clear(); - return typename Type::List::Builder(_builder); -} -inline bool Type::Reader::isEnum() const { - return which() == Type::ENUM; -} -inline bool Type::Builder::isEnum() { - return which() == Type::ENUM; -} -inline typename Type::Enum::Reader Type::Reader::getEnum() const { - KJ_IREQUIRE((which() == Type::ENUM), - "Must check which() before get()ing a union member."); - return typename Type::Enum::Reader(_reader); -} -inline typename Type::Enum::Builder Type::Builder::getEnum() { - KJ_IREQUIRE((which() == Type::ENUM), - "Must check which() before get()ing a union member."); - return typename Type::Enum::Builder(_builder); -} -inline typename Type::Enum::Builder Type::Builder::initEnum() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Type::ENUM); - _builder.setDataField< ::uint64_t>(::capnp::bounded<1>() * ::capnp::ELEMENTS, 0); - _builder.getPointerField(::capnp::bounded<0>() * ::capnp::POINTERS).clear(); - return typename Type::Enum::Builder(_builder); -} -inline bool Type::Reader::isStruct() const { - return which() == Type::STRUCT; -} -inline bool Type::Builder::isStruct() { - return which() == Type::STRUCT; -} -inline typename Type::Struct::Reader Type::Reader::getStruct() const { - KJ_IREQUIRE((which() == Type::STRUCT), - "Must check which() before get()ing a union member."); - return typename Type::Struct::Reader(_reader); -} -inline typename Type::Struct::Builder Type::Builder::getStruct() { - KJ_IREQUIRE((which() == Type::STRUCT), - "Must check which() before get()ing a union member."); - return typename Type::Struct::Builder(_builder); -} -inline typename Type::Struct::Builder Type::Builder::initStruct() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Type::STRUCT); - _builder.setDataField< ::uint64_t>(::capnp::bounded<1>() * ::capnp::ELEMENTS, 0); - _builder.getPointerField(::capnp::bounded<0>() * ::capnp::POINTERS).clear(); - return typename Type::Struct::Builder(_builder); -} -inline bool Type::Reader::isInterface() const { - return which() == Type::INTERFACE; -} -inline bool Type::Builder::isInterface() { - return which() == Type::INTERFACE; -} -inline typename Type::Interface::Reader Type::Reader::getInterface() const { - KJ_IREQUIRE((which() == Type::INTERFACE), - "Must check which() before get()ing a union member."); - return typename Type::Interface::Reader(_reader); -} -inline typename Type::Interface::Builder Type::Builder::getInterface() { - KJ_IREQUIRE((which() == Type::INTERFACE), - "Must check which() before get()ing a union member."); - return typename Type::Interface::Builder(_builder); -} -inline typename Type::Interface::Builder Type::Builder::initInterface() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Type::INTERFACE); - _builder.setDataField< ::uint64_t>(::capnp::bounded<1>() * ::capnp::ELEMENTS, 0); - _builder.getPointerField(::capnp::bounded<0>() * ::capnp::POINTERS).clear(); - return typename Type::Interface::Builder(_builder); -} -inline bool Type::Reader::isAnyPointer() const { - return which() == Type::ANY_POINTER; -} -inline bool Type::Builder::isAnyPointer() { - return which() == Type::ANY_POINTER; -} -inline typename Type::AnyPointer::Reader Type::Reader::getAnyPointer() const { - KJ_IREQUIRE((which() == Type::ANY_POINTER), - "Must check which() before get()ing a union member."); - return typename Type::AnyPointer::Reader(_reader); -} -inline typename Type::AnyPointer::Builder Type::Builder::getAnyPointer() { - KJ_IREQUIRE((which() == Type::ANY_POINTER), - "Must check which() before get()ing a union member."); - return typename Type::AnyPointer::Builder(_builder); -} -inline typename Type::AnyPointer::Builder Type::Builder::initAnyPointer() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Type::ANY_POINTER); - _builder.setDataField< ::uint16_t>(::capnp::bounded<4>() * ::capnp::ELEMENTS, 0); - _builder.setDataField< ::uint16_t>(::capnp::bounded<5>() * ::capnp::ELEMENTS, 0); - _builder.setDataField< ::uint64_t>(::capnp::bounded<2>() * ::capnp::ELEMENTS, 0); - return typename Type::AnyPointer::Builder(_builder); -} -inline bool Type::List::Reader::hasElementType() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Type::List::Builder::hasElementType() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::schema::Type::Reader Type::List::Reader::getElementType() const { - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::schema::Type::Builder Type::List::Builder::getElementType() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::schema::Type::Pipeline Type::List::Pipeline::getElementType() { - return ::capnp::schema::Type::Pipeline(_typeless.getPointerField(0)); -} -#endif // !CAPNP_LITE -inline void Type::List::Builder::setElementType( ::capnp::schema::Type::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Type>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::schema::Type::Builder Type::List::Builder::initElementType() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Type::List::Builder::adoptElementType( - ::capnp::Orphan< ::capnp::schema::Type>&& value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Type>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::schema::Type> Type::List::Builder::disownElementType() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline ::uint64_t Type::Enum::Reader::getTypeId() const { - return _reader.getDataField< ::uint64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline ::uint64_t Type::Enum::Builder::getTypeId() { - return _builder.getDataField< ::uint64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void Type::Enum::Builder::setTypeId( ::uint64_t value) { - _builder.setDataField< ::uint64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::Enum::Reader::hasBrand() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Type::Enum::Builder::hasBrand() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::schema::Brand::Reader Type::Enum::Reader::getBrand() const { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::schema::Brand::Builder Type::Enum::Builder::getBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::schema::Brand::Pipeline Type::Enum::Pipeline::getBrand() { - return ::capnp::schema::Brand::Pipeline(_typeless.getPointerField(0)); -} -#endif // !CAPNP_LITE -inline void Type::Enum::Builder::setBrand( ::capnp::schema::Brand::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::schema::Brand::Builder Type::Enum::Builder::initBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Type::Enum::Builder::adoptBrand( - ::capnp::Orphan< ::capnp::schema::Brand>&& value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::schema::Brand> Type::Enum::Builder::disownBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline ::uint64_t Type::Struct::Reader::getTypeId() const { - return _reader.getDataField< ::uint64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline ::uint64_t Type::Struct::Builder::getTypeId() { - return _builder.getDataField< ::uint64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void Type::Struct::Builder::setTypeId( ::uint64_t value) { - _builder.setDataField< ::uint64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::Struct::Reader::hasBrand() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Type::Struct::Builder::hasBrand() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::schema::Brand::Reader Type::Struct::Reader::getBrand() const { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::schema::Brand::Builder Type::Struct::Builder::getBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::schema::Brand::Pipeline Type::Struct::Pipeline::getBrand() { - return ::capnp::schema::Brand::Pipeline(_typeless.getPointerField(0)); -} -#endif // !CAPNP_LITE -inline void Type::Struct::Builder::setBrand( ::capnp::schema::Brand::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::schema::Brand::Builder Type::Struct::Builder::initBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Type::Struct::Builder::adoptBrand( - ::capnp::Orphan< ::capnp::schema::Brand>&& value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::schema::Brand> Type::Struct::Builder::disownBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline ::uint64_t Type::Interface::Reader::getTypeId() const { - return _reader.getDataField< ::uint64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline ::uint64_t Type::Interface::Builder::getTypeId() { - return _builder.getDataField< ::uint64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void Type::Interface::Builder::setTypeId( ::uint64_t value) { - _builder.setDataField< ::uint64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::Interface::Reader::hasBrand() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Type::Interface::Builder::hasBrand() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::schema::Brand::Reader Type::Interface::Reader::getBrand() const { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::schema::Brand::Builder Type::Interface::Builder::getBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::schema::Brand::Pipeline Type::Interface::Pipeline::getBrand() { - return ::capnp::schema::Brand::Pipeline(_typeless.getPointerField(0)); -} -#endif // !CAPNP_LITE -inline void Type::Interface::Builder::setBrand( ::capnp::schema::Brand::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::schema::Brand::Builder Type::Interface::Builder::initBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Type::Interface::Builder::adoptBrand( - ::capnp::Orphan< ::capnp::schema::Brand>&& value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::schema::Brand> Type::Interface::Builder::disownBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline ::capnp::schema::Type::AnyPointer::Which Type::AnyPointer::Reader::which() const { - return _reader.getDataField( - ::capnp::bounded<4>() * ::capnp::ELEMENTS); -} -inline ::capnp::schema::Type::AnyPointer::Which Type::AnyPointer::Builder::which() { - return _builder.getDataField( - ::capnp::bounded<4>() * ::capnp::ELEMENTS); -} - -inline bool Type::AnyPointer::Reader::isUnconstrained() const { - return which() == Type::AnyPointer::UNCONSTRAINED; -} -inline bool Type::AnyPointer::Builder::isUnconstrained() { - return which() == Type::AnyPointer::UNCONSTRAINED; -} -inline typename Type::AnyPointer::Unconstrained::Reader Type::AnyPointer::Reader::getUnconstrained() const { - KJ_IREQUIRE((which() == Type::AnyPointer::UNCONSTRAINED), - "Must check which() before get()ing a union member."); - return typename Type::AnyPointer::Unconstrained::Reader(_reader); -} -inline typename Type::AnyPointer::Unconstrained::Builder Type::AnyPointer::Builder::getUnconstrained() { - KJ_IREQUIRE((which() == Type::AnyPointer::UNCONSTRAINED), - "Must check which() before get()ing a union member."); - return typename Type::AnyPointer::Unconstrained::Builder(_builder); -} -inline typename Type::AnyPointer::Unconstrained::Builder Type::AnyPointer::Builder::initUnconstrained() { - _builder.setDataField( - ::capnp::bounded<4>() * ::capnp::ELEMENTS, Type::AnyPointer::UNCONSTRAINED); - _builder.setDataField< ::uint16_t>(::capnp::bounded<5>() * ::capnp::ELEMENTS, 0); - return typename Type::AnyPointer::Unconstrained::Builder(_builder); -} -inline bool Type::AnyPointer::Reader::isParameter() const { - return which() == Type::AnyPointer::PARAMETER; -} -inline bool Type::AnyPointer::Builder::isParameter() { - return which() == Type::AnyPointer::PARAMETER; -} -inline typename Type::AnyPointer::Parameter::Reader Type::AnyPointer::Reader::getParameter() const { - KJ_IREQUIRE((which() == Type::AnyPointer::PARAMETER), - "Must check which() before get()ing a union member."); - return typename Type::AnyPointer::Parameter::Reader(_reader); -} -inline typename Type::AnyPointer::Parameter::Builder Type::AnyPointer::Builder::getParameter() { - KJ_IREQUIRE((which() == Type::AnyPointer::PARAMETER), - "Must check which() before get()ing a union member."); - return typename Type::AnyPointer::Parameter::Builder(_builder); -} -inline typename Type::AnyPointer::Parameter::Builder Type::AnyPointer::Builder::initParameter() { - _builder.setDataField( - ::capnp::bounded<4>() * ::capnp::ELEMENTS, Type::AnyPointer::PARAMETER); - _builder.setDataField< ::uint16_t>(::capnp::bounded<5>() * ::capnp::ELEMENTS, 0); - _builder.setDataField< ::uint64_t>(::capnp::bounded<2>() * ::capnp::ELEMENTS, 0); - return typename Type::AnyPointer::Parameter::Builder(_builder); -} -inline bool Type::AnyPointer::Reader::isImplicitMethodParameter() const { - return which() == Type::AnyPointer::IMPLICIT_METHOD_PARAMETER; -} -inline bool Type::AnyPointer::Builder::isImplicitMethodParameter() { - return which() == Type::AnyPointer::IMPLICIT_METHOD_PARAMETER; -} -inline typename Type::AnyPointer::ImplicitMethodParameter::Reader Type::AnyPointer::Reader::getImplicitMethodParameter() const { - KJ_IREQUIRE((which() == Type::AnyPointer::IMPLICIT_METHOD_PARAMETER), - "Must check which() before get()ing a union member."); - return typename Type::AnyPointer::ImplicitMethodParameter::Reader(_reader); -} -inline typename Type::AnyPointer::ImplicitMethodParameter::Builder Type::AnyPointer::Builder::getImplicitMethodParameter() { - KJ_IREQUIRE((which() == Type::AnyPointer::IMPLICIT_METHOD_PARAMETER), - "Must check which() before get()ing a union member."); - return typename Type::AnyPointer::ImplicitMethodParameter::Builder(_builder); -} -inline typename Type::AnyPointer::ImplicitMethodParameter::Builder Type::AnyPointer::Builder::initImplicitMethodParameter() { - _builder.setDataField( - ::capnp::bounded<4>() * ::capnp::ELEMENTS, Type::AnyPointer::IMPLICIT_METHOD_PARAMETER); - _builder.setDataField< ::uint16_t>(::capnp::bounded<5>() * ::capnp::ELEMENTS, 0); - return typename Type::AnyPointer::ImplicitMethodParameter::Builder(_builder); -} -inline ::capnp::schema::Type::AnyPointer::Unconstrained::Which Type::AnyPointer::Unconstrained::Reader::which() const { - return _reader.getDataField( - ::capnp::bounded<5>() * ::capnp::ELEMENTS); -} -inline ::capnp::schema::Type::AnyPointer::Unconstrained::Which Type::AnyPointer::Unconstrained::Builder::which() { - return _builder.getDataField( - ::capnp::bounded<5>() * ::capnp::ELEMENTS); -} - -inline bool Type::AnyPointer::Unconstrained::Reader::isAnyKind() const { - return which() == Type::AnyPointer::Unconstrained::ANY_KIND; -} -inline bool Type::AnyPointer::Unconstrained::Builder::isAnyKind() { - return which() == Type::AnyPointer::Unconstrained::ANY_KIND; -} -inline ::capnp::Void Type::AnyPointer::Unconstrained::Reader::getAnyKind() const { - KJ_IREQUIRE((which() == Type::AnyPointer::Unconstrained::ANY_KIND), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Type::AnyPointer::Unconstrained::Builder::getAnyKind() { - KJ_IREQUIRE((which() == Type::AnyPointer::Unconstrained::ANY_KIND), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Type::AnyPointer::Unconstrained::Builder::setAnyKind( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<5>() * ::capnp::ELEMENTS, Type::AnyPointer::Unconstrained::ANY_KIND); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::AnyPointer::Unconstrained::Reader::isStruct() const { - return which() == Type::AnyPointer::Unconstrained::STRUCT; -} -inline bool Type::AnyPointer::Unconstrained::Builder::isStruct() { - return which() == Type::AnyPointer::Unconstrained::STRUCT; -} -inline ::capnp::Void Type::AnyPointer::Unconstrained::Reader::getStruct() const { - KJ_IREQUIRE((which() == Type::AnyPointer::Unconstrained::STRUCT), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Type::AnyPointer::Unconstrained::Builder::getStruct() { - KJ_IREQUIRE((which() == Type::AnyPointer::Unconstrained::STRUCT), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Type::AnyPointer::Unconstrained::Builder::setStruct( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<5>() * ::capnp::ELEMENTS, Type::AnyPointer::Unconstrained::STRUCT); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::AnyPointer::Unconstrained::Reader::isList() const { - return which() == Type::AnyPointer::Unconstrained::LIST; -} -inline bool Type::AnyPointer::Unconstrained::Builder::isList() { - return which() == Type::AnyPointer::Unconstrained::LIST; -} -inline ::capnp::Void Type::AnyPointer::Unconstrained::Reader::getList() const { - KJ_IREQUIRE((which() == Type::AnyPointer::Unconstrained::LIST), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Type::AnyPointer::Unconstrained::Builder::getList() { - KJ_IREQUIRE((which() == Type::AnyPointer::Unconstrained::LIST), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Type::AnyPointer::Unconstrained::Builder::setList( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<5>() * ::capnp::ELEMENTS, Type::AnyPointer::Unconstrained::LIST); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Type::AnyPointer::Unconstrained::Reader::isCapability() const { - return which() == Type::AnyPointer::Unconstrained::CAPABILITY; -} -inline bool Type::AnyPointer::Unconstrained::Builder::isCapability() { - return which() == Type::AnyPointer::Unconstrained::CAPABILITY; -} -inline ::capnp::Void Type::AnyPointer::Unconstrained::Reader::getCapability() const { - KJ_IREQUIRE((which() == Type::AnyPointer::Unconstrained::CAPABILITY), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Type::AnyPointer::Unconstrained::Builder::getCapability() { - KJ_IREQUIRE((which() == Type::AnyPointer::Unconstrained::CAPABILITY), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Type::AnyPointer::Unconstrained::Builder::setCapability( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<5>() * ::capnp::ELEMENTS, Type::AnyPointer::Unconstrained::CAPABILITY); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline ::uint64_t Type::AnyPointer::Parameter::Reader::getScopeId() const { - return _reader.getDataField< ::uint64_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} - -inline ::uint64_t Type::AnyPointer::Parameter::Builder::getScopeId() { - return _builder.getDataField< ::uint64_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} -inline void Type::AnyPointer::Parameter::Builder::setScopeId( ::uint64_t value) { - _builder.setDataField< ::uint64_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, value); -} - -inline ::uint16_t Type::AnyPointer::Parameter::Reader::getParameterIndex() const { - return _reader.getDataField< ::uint16_t>( - ::capnp::bounded<5>() * ::capnp::ELEMENTS); -} - -inline ::uint16_t Type::AnyPointer::Parameter::Builder::getParameterIndex() { - return _builder.getDataField< ::uint16_t>( - ::capnp::bounded<5>() * ::capnp::ELEMENTS); -} -inline void Type::AnyPointer::Parameter::Builder::setParameterIndex( ::uint16_t value) { - _builder.setDataField< ::uint16_t>( - ::capnp::bounded<5>() * ::capnp::ELEMENTS, value); -} - -inline ::uint16_t Type::AnyPointer::ImplicitMethodParameter::Reader::getParameterIndex() const { - return _reader.getDataField< ::uint16_t>( - ::capnp::bounded<5>() * ::capnp::ELEMENTS); -} - -inline ::uint16_t Type::AnyPointer::ImplicitMethodParameter::Builder::getParameterIndex() { - return _builder.getDataField< ::uint16_t>( - ::capnp::bounded<5>() * ::capnp::ELEMENTS); -} -inline void Type::AnyPointer::ImplicitMethodParameter::Builder::setParameterIndex( ::uint16_t value) { - _builder.setDataField< ::uint16_t>( - ::capnp::bounded<5>() * ::capnp::ELEMENTS, value); -} - -inline bool Brand::Reader::hasScopes() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Brand::Builder::hasScopes() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::schema::Brand::Scope>::Reader Brand::Reader::getScopes() const { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Brand::Scope>>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::schema::Brand::Scope>::Builder Brand::Builder::getScopes() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Brand::Scope>>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Brand::Builder::setScopes( ::capnp::List< ::capnp::schema::Brand::Scope>::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Brand::Scope>>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::schema::Brand::Scope>::Builder Brand::Builder::initScopes(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Brand::Scope>>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void Brand::Builder::adoptScopes( - ::capnp::Orphan< ::capnp::List< ::capnp::schema::Brand::Scope>>&& value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Brand::Scope>>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Brand::Scope>> Brand::Builder::disownScopes() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Brand::Scope>>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline ::capnp::schema::Brand::Scope::Which Brand::Scope::Reader::which() const { - return _reader.getDataField( - ::capnp::bounded<4>() * ::capnp::ELEMENTS); -} -inline ::capnp::schema::Brand::Scope::Which Brand::Scope::Builder::which() { - return _builder.getDataField( - ::capnp::bounded<4>() * ::capnp::ELEMENTS); -} - -inline ::uint64_t Brand::Scope::Reader::getScopeId() const { - return _reader.getDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint64_t Brand::Scope::Builder::getScopeId() { - return _builder.getDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Brand::Scope::Builder::setScopeId( ::uint64_t value) { - _builder.setDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Brand::Scope::Reader::isBind() const { - return which() == Brand::Scope::BIND; -} -inline bool Brand::Scope::Builder::isBind() { - return which() == Brand::Scope::BIND; -} -inline bool Brand::Scope::Reader::hasBind() const { - if (which() != Brand::Scope::BIND) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Brand::Scope::Builder::hasBind() { - if (which() != Brand::Scope::BIND) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::schema::Brand::Binding>::Reader Brand::Scope::Reader::getBind() const { - KJ_IREQUIRE((which() == Brand::Scope::BIND), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Brand::Binding>>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::schema::Brand::Binding>::Builder Brand::Scope::Builder::getBind() { - KJ_IREQUIRE((which() == Brand::Scope::BIND), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Brand::Binding>>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Brand::Scope::Builder::setBind( ::capnp::List< ::capnp::schema::Brand::Binding>::Reader value) { - _builder.setDataField( - ::capnp::bounded<4>() * ::capnp::ELEMENTS, Brand::Scope::BIND); - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Brand::Binding>>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::schema::Brand::Binding>::Builder Brand::Scope::Builder::initBind(unsigned int size) { - _builder.setDataField( - ::capnp::bounded<4>() * ::capnp::ELEMENTS, Brand::Scope::BIND); - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Brand::Binding>>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void Brand::Scope::Builder::adoptBind( - ::capnp::Orphan< ::capnp::List< ::capnp::schema::Brand::Binding>>&& value) { - _builder.setDataField( - ::capnp::bounded<4>() * ::capnp::ELEMENTS, Brand::Scope::BIND); - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Brand::Binding>>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Brand::Binding>> Brand::Scope::Builder::disownBind() { - KJ_IREQUIRE((which() == Brand::Scope::BIND), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Brand::Binding>>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Brand::Scope::Reader::isInherit() const { - return which() == Brand::Scope::INHERIT; -} -inline bool Brand::Scope::Builder::isInherit() { - return which() == Brand::Scope::INHERIT; -} -inline ::capnp::Void Brand::Scope::Reader::getInherit() const { - KJ_IREQUIRE((which() == Brand::Scope::INHERIT), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Brand::Scope::Builder::getInherit() { - KJ_IREQUIRE((which() == Brand::Scope::INHERIT), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Brand::Scope::Builder::setInherit( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<4>() * ::capnp::ELEMENTS, Brand::Scope::INHERIT); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline ::capnp::schema::Brand::Binding::Which Brand::Binding::Reader::which() const { - return _reader.getDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline ::capnp::schema::Brand::Binding::Which Brand::Binding::Builder::which() { - return _builder.getDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline bool Brand::Binding::Reader::isUnbound() const { - return which() == Brand::Binding::UNBOUND; -} -inline bool Brand::Binding::Builder::isUnbound() { - return which() == Brand::Binding::UNBOUND; -} -inline ::capnp::Void Brand::Binding::Reader::getUnbound() const { - KJ_IREQUIRE((which() == Brand::Binding::UNBOUND), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Brand::Binding::Builder::getUnbound() { - KJ_IREQUIRE((which() == Brand::Binding::UNBOUND), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Brand::Binding::Builder::setUnbound( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Brand::Binding::UNBOUND); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Brand::Binding::Reader::isType() const { - return which() == Brand::Binding::TYPE; -} -inline bool Brand::Binding::Builder::isType() { - return which() == Brand::Binding::TYPE; -} -inline bool Brand::Binding::Reader::hasType() const { - if (which() != Brand::Binding::TYPE) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Brand::Binding::Builder::hasType() { - if (which() != Brand::Binding::TYPE) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::schema::Type::Reader Brand::Binding::Reader::getType() const { - KJ_IREQUIRE((which() == Brand::Binding::TYPE), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::schema::Type::Builder Brand::Binding::Builder::getType() { - KJ_IREQUIRE((which() == Brand::Binding::TYPE), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Brand::Binding::Builder::setType( ::capnp::schema::Type::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Brand::Binding::TYPE); - ::capnp::_::PointerHelpers< ::capnp::schema::Type>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::schema::Type::Builder Brand::Binding::Builder::initType() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Brand::Binding::TYPE); - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Brand::Binding::Builder::adoptType( - ::capnp::Orphan< ::capnp::schema::Type>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Brand::Binding::TYPE); - ::capnp::_::PointerHelpers< ::capnp::schema::Type>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::schema::Type> Brand::Binding::Builder::disownType() { - KJ_IREQUIRE((which() == Brand::Binding::TYPE), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::schema::Type>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline ::capnp::schema::Value::Which Value::Reader::which() const { - return _reader.getDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline ::capnp::schema::Value::Which Value::Builder::which() { - return _builder.getDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline bool Value::Reader::isVoid() const { - return which() == Value::VOID; -} -inline bool Value::Builder::isVoid() { - return which() == Value::VOID; -} -inline ::capnp::Void Value::Reader::getVoid() const { - KJ_IREQUIRE((which() == Value::VOID), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Value::Builder::getVoid() { - KJ_IREQUIRE((which() == Value::VOID), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Value::Builder::setVoid( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::VOID); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Value::Reader::isBool() const { - return which() == Value::BOOL; -} -inline bool Value::Builder::isBool() { - return which() == Value::BOOL; -} -inline bool Value::Reader::getBool() const { - KJ_IREQUIRE((which() == Value::BOOL), - "Must check which() before get()ing a union member."); - return _reader.getDataField( - ::capnp::bounded<16>() * ::capnp::ELEMENTS); -} - -inline bool Value::Builder::getBool() { - KJ_IREQUIRE((which() == Value::BOOL), - "Must check which() before get()ing a union member."); - return _builder.getDataField( - ::capnp::bounded<16>() * ::capnp::ELEMENTS); -} -inline void Value::Builder::setBool(bool value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::BOOL); - _builder.setDataField( - ::capnp::bounded<16>() * ::capnp::ELEMENTS, value); -} - -inline bool Value::Reader::isInt8() const { - return which() == Value::INT8; -} -inline bool Value::Builder::isInt8() { - return which() == Value::INT8; -} -inline ::int8_t Value::Reader::getInt8() const { - KJ_IREQUIRE((which() == Value::INT8), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::int8_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} - -inline ::int8_t Value::Builder::getInt8() { - KJ_IREQUIRE((which() == Value::INT8), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::int8_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} -inline void Value::Builder::setInt8( ::int8_t value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::INT8); - _builder.setDataField< ::int8_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, value); -} - -inline bool Value::Reader::isInt16() const { - return which() == Value::INT16; -} -inline bool Value::Builder::isInt16() { - return which() == Value::INT16; -} -inline ::int16_t Value::Reader::getInt16() const { - KJ_IREQUIRE((which() == Value::INT16), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::int16_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline ::int16_t Value::Builder::getInt16() { - KJ_IREQUIRE((which() == Value::INT16), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::int16_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void Value::Builder::setInt16( ::int16_t value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::INT16); - _builder.setDataField< ::int16_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline bool Value::Reader::isInt32() const { - return which() == Value::INT32; -} -inline bool Value::Builder::isInt32() { - return which() == Value::INT32; -} -inline ::int32_t Value::Reader::getInt32() const { - KJ_IREQUIRE((which() == Value::INT32), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::int32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline ::int32_t Value::Builder::getInt32() { - KJ_IREQUIRE((which() == Value::INT32), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::int32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void Value::Builder::setInt32( ::int32_t value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::INT32); - _builder.setDataField< ::int32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline bool Value::Reader::isInt64() const { - return which() == Value::INT64; -} -inline bool Value::Builder::isInt64() { - return which() == Value::INT64; -} -inline ::int64_t Value::Reader::getInt64() const { - KJ_IREQUIRE((which() == Value::INT64), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::int64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline ::int64_t Value::Builder::getInt64() { - KJ_IREQUIRE((which() == Value::INT64), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::int64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void Value::Builder::setInt64( ::int64_t value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::INT64); - _builder.setDataField< ::int64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline bool Value::Reader::isUint8() const { - return which() == Value::UINT8; -} -inline bool Value::Builder::isUint8() { - return which() == Value::UINT8; -} -inline ::uint8_t Value::Reader::getUint8() const { - KJ_IREQUIRE((which() == Value::UINT8), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::uint8_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} - -inline ::uint8_t Value::Builder::getUint8() { - KJ_IREQUIRE((which() == Value::UINT8), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::uint8_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} -inline void Value::Builder::setUint8( ::uint8_t value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::UINT8); - _builder.setDataField< ::uint8_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, value); -} - -inline bool Value::Reader::isUint16() const { - return which() == Value::UINT16; -} -inline bool Value::Builder::isUint16() { - return which() == Value::UINT16; -} -inline ::uint16_t Value::Reader::getUint16() const { - KJ_IREQUIRE((which() == Value::UINT16), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::uint16_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline ::uint16_t Value::Builder::getUint16() { - KJ_IREQUIRE((which() == Value::UINT16), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::uint16_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void Value::Builder::setUint16( ::uint16_t value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::UINT16); - _builder.setDataField< ::uint16_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline bool Value::Reader::isUint32() const { - return which() == Value::UINT32; -} -inline bool Value::Builder::isUint32() { - return which() == Value::UINT32; -} -inline ::uint32_t Value::Reader::getUint32() const { - KJ_IREQUIRE((which() == Value::UINT32), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::uint32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline ::uint32_t Value::Builder::getUint32() { - KJ_IREQUIRE((which() == Value::UINT32), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::uint32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void Value::Builder::setUint32( ::uint32_t value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::UINT32); - _builder.setDataField< ::uint32_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline bool Value::Reader::isUint64() const { - return which() == Value::UINT64; -} -inline bool Value::Builder::isUint64() { - return which() == Value::UINT64; -} -inline ::uint64_t Value::Reader::getUint64() const { - KJ_IREQUIRE((which() == Value::UINT64), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::uint64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline ::uint64_t Value::Builder::getUint64() { - KJ_IREQUIRE((which() == Value::UINT64), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::uint64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void Value::Builder::setUint64( ::uint64_t value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::UINT64); - _builder.setDataField< ::uint64_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline bool Value::Reader::isFloat32() const { - return which() == Value::FLOAT32; -} -inline bool Value::Builder::isFloat32() { - return which() == Value::FLOAT32; -} -inline float Value::Reader::getFloat32() const { - KJ_IREQUIRE((which() == Value::FLOAT32), - "Must check which() before get()ing a union member."); - return _reader.getDataField( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline float Value::Builder::getFloat32() { - KJ_IREQUIRE((which() == Value::FLOAT32), - "Must check which() before get()ing a union member."); - return _builder.getDataField( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void Value::Builder::setFloat32(float value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::FLOAT32); - _builder.setDataField( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline bool Value::Reader::isFloat64() const { - return which() == Value::FLOAT64; -} -inline bool Value::Builder::isFloat64() { - return which() == Value::FLOAT64; -} -inline double Value::Reader::getFloat64() const { - KJ_IREQUIRE((which() == Value::FLOAT64), - "Must check which() before get()ing a union member."); - return _reader.getDataField( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline double Value::Builder::getFloat64() { - KJ_IREQUIRE((which() == Value::FLOAT64), - "Must check which() before get()ing a union member."); - return _builder.getDataField( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void Value::Builder::setFloat64(double value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::FLOAT64); - _builder.setDataField( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline bool Value::Reader::isText() const { - return which() == Value::TEXT; -} -inline bool Value::Builder::isText() { - return which() == Value::TEXT; -} -inline bool Value::Reader::hasText() const { - if (which() != Value::TEXT) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Value::Builder::hasText() { - if (which() != Value::TEXT) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::Text::Reader Value::Reader::getText() const { - KJ_IREQUIRE((which() == Value::TEXT), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::Text::Builder Value::Builder::getText() { - KJ_IREQUIRE((which() == Value::TEXT), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Value::Builder::setText( ::capnp::Text::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::TEXT); - ::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::Text::Builder Value::Builder::initText(unsigned int size) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::TEXT); - return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void Value::Builder::adoptText( - ::capnp::Orphan< ::capnp::Text>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::TEXT); - ::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::Text> Value::Builder::disownText() { - KJ_IREQUIRE((which() == Value::TEXT), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Value::Reader::isData() const { - return which() == Value::DATA; -} -inline bool Value::Builder::isData() { - return which() == Value::DATA; -} -inline bool Value::Reader::hasData() const { - if (which() != Value::DATA) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Value::Builder::hasData() { - if (which() != Value::DATA) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::Data::Reader Value::Reader::getData() const { - KJ_IREQUIRE((which() == Value::DATA), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::Data>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::Data::Builder Value::Builder::getData() { - KJ_IREQUIRE((which() == Value::DATA), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::Data>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Value::Builder::setData( ::capnp::Data::Reader value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::DATA); - ::capnp::_::PointerHelpers< ::capnp::Data>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::Data::Builder Value::Builder::initData(unsigned int size) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::DATA); - return ::capnp::_::PointerHelpers< ::capnp::Data>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void Value::Builder::adoptData( - ::capnp::Orphan< ::capnp::Data>&& value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::DATA); - ::capnp::_::PointerHelpers< ::capnp::Data>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::Data> Value::Builder::disownData() { - KJ_IREQUIRE((which() == Value::DATA), - "Must check which() before get()ing a union member."); - return ::capnp::_::PointerHelpers< ::capnp::Data>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Value::Reader::isList() const { - return which() == Value::LIST; -} -inline bool Value::Builder::isList() { - return which() == Value::LIST; -} -inline bool Value::Reader::hasList() const { - if (which() != Value::LIST) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Value::Builder::hasList() { - if (which() != Value::LIST) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::AnyPointer::Reader Value::Reader::getList() const { - KJ_IREQUIRE((which() == Value::LIST), - "Must check which() before get()ing a union member."); - return ::capnp::AnyPointer::Reader(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Value::Builder::getList() { - KJ_IREQUIRE((which() == Value::LIST), - "Must check which() before get()ing a union member."); - return ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Value::Builder::initList() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::LIST); - auto result = ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); - result.clear(); - return result; -} - -inline bool Value::Reader::isEnum() const { - return which() == Value::ENUM; -} -inline bool Value::Builder::isEnum() { - return which() == Value::ENUM; -} -inline ::uint16_t Value::Reader::getEnum() const { - KJ_IREQUIRE((which() == Value::ENUM), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::uint16_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} - -inline ::uint16_t Value::Builder::getEnum() { - KJ_IREQUIRE((which() == Value::ENUM), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::uint16_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS); -} -inline void Value::Builder::setEnum( ::uint16_t value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::ENUM); - _builder.setDataField< ::uint16_t>( - ::capnp::bounded<1>() * ::capnp::ELEMENTS, value); -} - -inline bool Value::Reader::isStruct() const { - return which() == Value::STRUCT; -} -inline bool Value::Builder::isStruct() { - return which() == Value::STRUCT; -} -inline bool Value::Reader::hasStruct() const { - if (which() != Value::STRUCT) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Value::Builder::hasStruct() { - if (which() != Value::STRUCT) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::AnyPointer::Reader Value::Reader::getStruct() const { - KJ_IREQUIRE((which() == Value::STRUCT), - "Must check which() before get()ing a union member."); - return ::capnp::AnyPointer::Reader(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Value::Builder::getStruct() { - KJ_IREQUIRE((which() == Value::STRUCT), - "Must check which() before get()ing a union member."); - return ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Value::Builder::initStruct() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::STRUCT); - auto result = ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); - result.clear(); - return result; -} - -inline bool Value::Reader::isInterface() const { - return which() == Value::INTERFACE; -} -inline bool Value::Builder::isInterface() { - return which() == Value::INTERFACE; -} -inline ::capnp::Void Value::Reader::getInterface() const { - KJ_IREQUIRE((which() == Value::INTERFACE), - "Must check which() before get()ing a union member."); - return _reader.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::capnp::Void Value::Builder::getInterface() { - KJ_IREQUIRE((which() == Value::INTERFACE), - "Must check which() before get()ing a union member."); - return _builder.getDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Value::Builder::setInterface( ::capnp::Void value) { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::INTERFACE); - _builder.setDataField< ::capnp::Void>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Value::Reader::isAnyPointer() const { - return which() == Value::ANY_POINTER; -} -inline bool Value::Builder::isAnyPointer() { - return which() == Value::ANY_POINTER; -} -inline bool Value::Reader::hasAnyPointer() const { - if (which() != Value::ANY_POINTER) return false; - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Value::Builder::hasAnyPointer() { - if (which() != Value::ANY_POINTER) return false; - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::AnyPointer::Reader Value::Reader::getAnyPointer() const { - KJ_IREQUIRE((which() == Value::ANY_POINTER), - "Must check which() before get()ing a union member."); - return ::capnp::AnyPointer::Reader(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Value::Builder::getAnyPointer() { - KJ_IREQUIRE((which() == Value::ANY_POINTER), - "Must check which() before get()ing a union member."); - return ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::AnyPointer::Builder Value::Builder::initAnyPointer() { - _builder.setDataField( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, Value::ANY_POINTER); - auto result = ::capnp::AnyPointer::Builder(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); - result.clear(); - return result; -} - -inline ::uint64_t Annotation::Reader::getId() const { - return _reader.getDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint64_t Annotation::Builder::getId() { - return _builder.getDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void Annotation::Builder::setId( ::uint64_t value) { - _builder.setDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool Annotation::Reader::hasValue() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool Annotation::Builder::hasValue() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::schema::Value::Reader Annotation::Reader::getValue() const { - return ::capnp::_::PointerHelpers< ::capnp::schema::Value>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::schema::Value::Builder Annotation::Builder::getValue() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Value>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::schema::Value::Pipeline Annotation::Pipeline::getValue() { - return ::capnp::schema::Value::Pipeline(_typeless.getPointerField(0)); -} -#endif // !CAPNP_LITE -inline void Annotation::Builder::setValue( ::capnp::schema::Value::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Value>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::schema::Value::Builder Annotation::Builder::initValue() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Value>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void Annotation::Builder::adoptValue( - ::capnp::Orphan< ::capnp::schema::Value>&& value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Value>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::schema::Value> Annotation::Builder::disownValue() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Value>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool Annotation::Reader::hasBrand() const { - return !_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline bool Annotation::Builder::hasBrand() { - return !_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::schema::Brand::Reader Annotation::Reader::getBrand() const { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::get(_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline ::capnp::schema::Brand::Builder Annotation::Builder::getBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::get(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::schema::Brand::Pipeline Annotation::Pipeline::getBrand() { - return ::capnp::schema::Brand::Pipeline(_typeless.getPointerField(1)); -} -#endif // !CAPNP_LITE -inline void Annotation::Builder::setBrand( ::capnp::schema::Brand::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::set(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), value); -} -inline ::capnp::schema::Brand::Builder Annotation::Builder::initBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::init(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline void Annotation::Builder::adoptBrand( - ::capnp::Orphan< ::capnp::schema::Brand>&& value) { - ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::adopt(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::schema::Brand> Annotation::Builder::disownBrand() { - return ::capnp::_::PointerHelpers< ::capnp::schema::Brand>::disown(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} - -inline ::uint16_t CapnpVersion::Reader::getMajor() const { - return _reader.getDataField< ::uint16_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint16_t CapnpVersion::Builder::getMajor() { - return _builder.getDataField< ::uint16_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void CapnpVersion::Builder::setMajor( ::uint16_t value) { - _builder.setDataField< ::uint16_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline ::uint8_t CapnpVersion::Reader::getMinor() const { - return _reader.getDataField< ::uint8_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} - -inline ::uint8_t CapnpVersion::Builder::getMinor() { - return _builder.getDataField< ::uint8_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS); -} -inline void CapnpVersion::Builder::setMinor( ::uint8_t value) { - _builder.setDataField< ::uint8_t>( - ::capnp::bounded<2>() * ::capnp::ELEMENTS, value); -} - -inline ::uint8_t CapnpVersion::Reader::getMicro() const { - return _reader.getDataField< ::uint8_t>( - ::capnp::bounded<3>() * ::capnp::ELEMENTS); -} - -inline ::uint8_t CapnpVersion::Builder::getMicro() { - return _builder.getDataField< ::uint8_t>( - ::capnp::bounded<3>() * ::capnp::ELEMENTS); -} -inline void CapnpVersion::Builder::setMicro( ::uint8_t value) { - _builder.setDataField< ::uint8_t>( - ::capnp::bounded<3>() * ::capnp::ELEMENTS, value); -} - -inline bool CodeGeneratorRequest::Reader::hasNodes() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool CodeGeneratorRequest::Builder::hasNodes() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::schema::Node>::Reader CodeGeneratorRequest::Reader::getNodes() const { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node>>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::schema::Node>::Builder CodeGeneratorRequest::Builder::getNodes() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node>>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void CodeGeneratorRequest::Builder::setNodes( ::capnp::List< ::capnp::schema::Node>::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node>>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::schema::Node>::Builder CodeGeneratorRequest::Builder::initNodes(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node>>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void CodeGeneratorRequest::Builder::adoptNodes( - ::capnp::Orphan< ::capnp::List< ::capnp::schema::Node>>&& value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node>>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::Node>> CodeGeneratorRequest::Builder::disownNodes() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::Node>>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool CodeGeneratorRequest::Reader::hasRequestedFiles() const { - return !_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline bool CodeGeneratorRequest::Builder::hasRequestedFiles() { - return !_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile>::Reader CodeGeneratorRequest::Reader::getRequestedFiles() const { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile>>::get(_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile>::Builder CodeGeneratorRequest::Builder::getRequestedFiles() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile>>::get(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline void CodeGeneratorRequest::Builder::setRequestedFiles( ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile>::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile>>::set(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile>::Builder CodeGeneratorRequest::Builder::initRequestedFiles(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile>>::init(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), size); -} -inline void CodeGeneratorRequest::Builder::adoptRequestedFiles( - ::capnp::Orphan< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile>>&& value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile>>::adopt(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile>> CodeGeneratorRequest::Builder::disownRequestedFiles() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile>>::disown(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} - -inline bool CodeGeneratorRequest::Reader::hasCapnpVersion() const { - return !_reader.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS).isNull(); -} -inline bool CodeGeneratorRequest::Builder::hasCapnpVersion() { - return !_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::schema::CapnpVersion::Reader CodeGeneratorRequest::Reader::getCapnpVersion() const { - return ::capnp::_::PointerHelpers< ::capnp::schema::CapnpVersion>::get(_reader.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS)); -} -inline ::capnp::schema::CapnpVersion::Builder CodeGeneratorRequest::Builder::getCapnpVersion() { - return ::capnp::_::PointerHelpers< ::capnp::schema::CapnpVersion>::get(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS)); -} -#if !CAPNP_LITE -inline ::capnp::schema::CapnpVersion::Pipeline CodeGeneratorRequest::Pipeline::getCapnpVersion() { - return ::capnp::schema::CapnpVersion::Pipeline(_typeless.getPointerField(2)); -} -#endif // !CAPNP_LITE -inline void CodeGeneratorRequest::Builder::setCapnpVersion( ::capnp::schema::CapnpVersion::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::schema::CapnpVersion>::set(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS), value); -} -inline ::capnp::schema::CapnpVersion::Builder CodeGeneratorRequest::Builder::initCapnpVersion() { - return ::capnp::_::PointerHelpers< ::capnp::schema::CapnpVersion>::init(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS)); -} -inline void CodeGeneratorRequest::Builder::adoptCapnpVersion( - ::capnp::Orphan< ::capnp::schema::CapnpVersion>&& value) { - ::capnp::_::PointerHelpers< ::capnp::schema::CapnpVersion>::adopt(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::schema::CapnpVersion> CodeGeneratorRequest::Builder::disownCapnpVersion() { - return ::capnp::_::PointerHelpers< ::capnp::schema::CapnpVersion>::disown(_builder.getPointerField( - ::capnp::bounded<2>() * ::capnp::POINTERS)); -} - -inline ::uint64_t CodeGeneratorRequest::RequestedFile::Reader::getId() const { - return _reader.getDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint64_t CodeGeneratorRequest::RequestedFile::Builder::getId() { - return _builder.getDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void CodeGeneratorRequest::RequestedFile::Builder::setId( ::uint64_t value) { - _builder.setDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool CodeGeneratorRequest::RequestedFile::Reader::hasFilename() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool CodeGeneratorRequest::RequestedFile::Builder::hasFilename() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::Text::Reader CodeGeneratorRequest::RequestedFile::Reader::getFilename() const { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::Text::Builder CodeGeneratorRequest::RequestedFile::Builder::getFilename() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void CodeGeneratorRequest::RequestedFile::Builder::setFilename( ::capnp::Text::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::Text::Builder CodeGeneratorRequest::RequestedFile::Builder::initFilename(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void CodeGeneratorRequest::RequestedFile::Builder::adoptFilename( - ::capnp::Orphan< ::capnp::Text>&& value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::Text> CodeGeneratorRequest::RequestedFile::Builder::disownFilename() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -inline bool CodeGeneratorRequest::RequestedFile::Reader::hasImports() const { - return !_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline bool CodeGeneratorRequest::RequestedFile::Builder::hasImports() { - return !_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile::Import>::Reader CodeGeneratorRequest::RequestedFile::Reader::getImports() const { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile::Import>>::get(_reader.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile::Import>::Builder CodeGeneratorRequest::RequestedFile::Builder::getImports() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile::Import>>::get(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} -inline void CodeGeneratorRequest::RequestedFile::Builder::setImports( ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile::Import>::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile::Import>>::set(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), value); -} -inline ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile::Import>::Builder CodeGeneratorRequest::RequestedFile::Builder::initImports(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile::Import>>::init(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), size); -} -inline void CodeGeneratorRequest::RequestedFile::Builder::adoptImports( - ::capnp::Orphan< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile::Import>>&& value) { - ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile::Import>>::adopt(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile::Import>> CodeGeneratorRequest::RequestedFile::Builder::disownImports() { - return ::capnp::_::PointerHelpers< ::capnp::List< ::capnp::schema::CodeGeneratorRequest::RequestedFile::Import>>::disown(_builder.getPointerField( - ::capnp::bounded<1>() * ::capnp::POINTERS)); -} - -inline ::uint64_t CodeGeneratorRequest::RequestedFile::Import::Reader::getId() const { - return _reader.getDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} - -inline ::uint64_t CodeGeneratorRequest::RequestedFile::Import::Builder::getId() { - return _builder.getDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS); -} -inline void CodeGeneratorRequest::RequestedFile::Import::Builder::setId( ::uint64_t value) { - _builder.setDataField< ::uint64_t>( - ::capnp::bounded<0>() * ::capnp::ELEMENTS, value); -} - -inline bool CodeGeneratorRequest::RequestedFile::Import::Reader::hasName() const { - return !_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline bool CodeGeneratorRequest::RequestedFile::Import::Builder::hasName() { - return !_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); -} -inline ::capnp::Text::Reader CodeGeneratorRequest::RequestedFile::Import::Reader::getName() const { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline ::capnp::Text::Builder CodeGeneratorRequest::RequestedFile::Import::Builder::getName() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} -inline void CodeGeneratorRequest::RequestedFile::Import::Builder::setName( ::capnp::Text::Reader value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), value); -} -inline ::capnp::Text::Builder CodeGeneratorRequest::RequestedFile::Import::Builder::initName(unsigned int size) { - return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), size); -} -inline void CodeGeneratorRequest::RequestedFile::Import::Builder::adoptName( - ::capnp::Orphan< ::capnp::Text>&& value) { - ::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value)); -} -inline ::capnp::Orphan< ::capnp::Text> CodeGeneratorRequest::RequestedFile::Import::Builder::disownName() { - return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField( - ::capnp::bounded<0>() * ::capnp::POINTERS)); -} - -} // namespace -} // namespace - -#endif // CAPNP_INCLUDED_a93fc509624c72d9_ diff --git a/phonelibs/capnp-cpp/include/capnp/schema.h b/phonelibs/capnp-cpp/include/capnp/schema.h deleted file mode 100644 index d59fa75236..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/schema.h +++ /dev/null @@ -1,934 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_SCHEMA_H_ -#define CAPNP_SCHEMA_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#if CAPNP_LITE -#error "Reflection APIs, including this header, are not available in lite mode." -#endif - -#include - -namespace capnp { - -class Schema; -class StructSchema; -class EnumSchema; -class InterfaceSchema; -class ConstSchema; -class ListSchema; -class Type; - -template ()> struct SchemaType_ { typedef Schema Type; }; -template struct SchemaType_ { typedef schema::Type::Which Type; }; -template struct SchemaType_ { typedef schema::Type::Which Type; }; -template struct SchemaType_ { typedef EnumSchema Type; }; -template struct SchemaType_ { typedef StructSchema Type; }; -template struct SchemaType_ { typedef InterfaceSchema Type; }; -template struct SchemaType_ { typedef ListSchema Type; }; - -template -using SchemaType = typename SchemaType_::Type; -// SchemaType is the type of T's schema, e.g. StructSchema if T is a struct. - -namespace _ { // private -extern const RawSchema NULL_SCHEMA; -extern const RawSchema NULL_STRUCT_SCHEMA; -extern const RawSchema NULL_ENUM_SCHEMA; -extern const RawSchema NULL_INTERFACE_SCHEMA; -extern const RawSchema NULL_CONST_SCHEMA; -// The schema types default to these null (empty) schemas in case of error, especially when -// exceptions are disabled. -} // namespace _ (private) - -class Schema { - // Convenience wrapper around capnp::schema::Node. - -public: - inline Schema(): raw(&_::NULL_SCHEMA.defaultBrand) {} - - template - static inline SchemaType from() { return SchemaType::template fromImpl(); } - // Get the Schema for a particular compiled-in type. - - schema::Node::Reader getProto() const; - // Get the underlying Cap'n Proto representation of the schema node. (Note that this accessor - // has performance comparable to accessors of struct-typed fields on Reader classes.) - - kj::ArrayPtr asUncheckedMessage() const; - // Get the encoded schema node content as a single message segment. It is safe to read as an - // unchecked message. - - Schema getDependency(uint64_t id) const KJ_DEPRECATED("Does not handle generics correctly."); - // DEPRECATED: This method cannot correctly account for generic type parameter bindings that - // may apply to the dependency. Instead of using this method, use a method of the Schema API - // that corresponds to the exact kind of dependency. For example, to get a field type, use - // StructSchema::Field::getType(). - // - // Gets the Schema for one of this Schema's dependencies. For example, if this Schema is for a - // struct, you could look up the schema for one of its fields' types. Throws an exception if this - // schema doesn't actually depend on the given id. - // - // Note that not all type IDs found in the schema node are considered "dependencies" -- only the - // ones that are needed to implement the dynamic API are. That includes: - // - Field types. - // - Group types. - // - scopeId for group nodes, but NOT otherwise. - // - Method parameter and return types. - // - // The following are NOT considered dependencies: - // - Nested nodes. - // - scopeId for a non-group node. - // - Annotations. - // - // To obtain schemas for those, you would need a SchemaLoader. - - bool isBranded() const; - // Returns true if this schema represents a non-default parameterization of this type. - - Schema getGeneric() const; - // Get the version of this schema with any brands removed. - - class BrandArgumentList; - BrandArgumentList getBrandArgumentsAtScope(uint64_t scopeId) const; - // Gets the values bound to the brand parameters at the given scope. - - StructSchema asStruct() const; - EnumSchema asEnum() const; - InterfaceSchema asInterface() const; - ConstSchema asConst() const; - // Cast the Schema to a specific type. Throws an exception if the type doesn't match. Use - // getProto() to determine type, e.g. getProto().isStruct(). - - inline bool operator==(const Schema& other) const { return raw == other.raw; } - inline bool operator!=(const Schema& other) const { return raw != other.raw; } - // Determine whether two Schemas are wrapping the exact same underlying data, by identity. If - // you want to check if two Schemas represent the same type (but possibly different versions of - // it), compare their IDs instead. - - template - void requireUsableAs() const; - // Throws an exception if a value with this Schema cannot safely be cast to a native value of - // the given type. This passes if either: - // - *this == from() - // - This schema was loaded with SchemaLoader, the type ID matches typeId(), and - // loadCompiledTypeAndDependencies() was called on the SchemaLoader. - - kj::StringPtr getShortDisplayName() const; - // Get the short version of the node's display name. - -private: - const _::RawBrandedSchema* raw; - - inline explicit Schema(const _::RawBrandedSchema* raw): raw(raw) { - KJ_IREQUIRE(raw->lazyInitializer == nullptr, - "Must call ensureInitialized() on RawSchema before constructing Schema."); - } - - template static inline Schema fromImpl() { - return Schema(&_::rawSchema()); - } - - void requireUsableAs(const _::RawSchema* expected) const; - - uint32_t getSchemaOffset(const schema::Value::Reader& value) const; - - Type getBrandBinding(uint64_t scopeId, uint index) const; - // Look up the binding for a brand parameter used by this Schema. Returns `AnyPointer` if the - // parameter is not bound. - // - // TODO(someday): Public interface for iterating over all bindings? - - Schema getDependency(uint64_t id, uint location) const; - // Look up schema for a particular dependency of this schema. `location` is the dependency - // location number as defined in _::RawBrandedSchema. - - Type interpretType(schema::Type::Reader proto, uint location) const; - // Interpret a schema::Type in the given location within the schema, compiling it into a - // Type object. - - friend class StructSchema; - friend class EnumSchema; - friend class InterfaceSchema; - friend class ConstSchema; - friend class ListSchema; - friend class SchemaLoader; - friend class Type; - friend kj::StringTree _::structString( - _::StructReader reader, const _::RawBrandedSchema& schema); - friend kj::String _::enumString(uint16_t value, const _::RawBrandedSchema& schema); -}; - -kj::StringPtr KJ_STRINGIFY(const Schema& schema); - -class Schema::BrandArgumentList { - // A list of generic parameter bindings for parameters of some particular type. Note that since - // parameters on an outer type apply to all inner types as well, a deeply-nested type can have - // multiple BrandArgumentLists that apply to it. - // - // A BrandArgumentList only represents the arguments that the client of the type specified. Since - // new parameters can be added over time, this list may not cover all defined parameters for the - // type. Missing parameters should be treated as AnyPointer. This class's implementation of - // operator[] already does this for you; out-of-bounds access will safely return AnyPointer. - -public: - inline BrandArgumentList(): scopeId(0), size_(0), bindings(nullptr) {} - - inline uint size() const { return size_; } - Type operator[](uint index) const; - - typedef _::IndexingIterator Iterator; - inline Iterator begin() const { return Iterator(this, 0); } - inline Iterator end() const { return Iterator(this, size()); } - -private: - uint64_t scopeId; - uint size_; - bool isUnbound; - const _::RawBrandedSchema::Binding* bindings; - - inline BrandArgumentList(uint64_t scopeId, bool isUnbound) - : scopeId(scopeId), size_(0), isUnbound(isUnbound), bindings(nullptr) {} - inline BrandArgumentList(uint64_t scopeId, uint size, - const _::RawBrandedSchema::Binding* bindings) - : scopeId(scopeId), size_(size), isUnbound(false), bindings(bindings) {} - - friend class Schema; -}; - -// ------------------------------------------------------------------- - -class StructSchema: public Schema { -public: - inline StructSchema(): Schema(&_::NULL_STRUCT_SCHEMA.defaultBrand) {} - - class Field; - class FieldList; - class FieldSubset; - - FieldList getFields() const; - // List top-level fields of this struct. This list will contain top-level groups (including - // named unions) but not the members of those groups. The list does, however, contain the - // members of the unnamed union, if there is one. - - FieldSubset getUnionFields() const; - // If the field contains an unnamed union, get a list of fields in the union, ordered by - // ordinal. Since discriminant values are assigned sequentially by ordinal, you may index this - // list by discriminant value. - - FieldSubset getNonUnionFields() const; - // Get the fields of this struct which are not in an unnamed union, ordered by ordinal. - - kj::Maybe findFieldByName(kj::StringPtr name) const; - // Find the field with the given name, or return null if there is no such field. If the struct - // contains an unnamed union, then this will find fields of that union in addition to fields - // of the outer struct, since they exist in the same namespace. It will not, however, find - // members of groups (including named unions) -- you must first look up the group itself, - // then dig into its type. - - Field getFieldByName(kj::StringPtr name) const; - // Like findFieldByName() but throws an exception on failure. - - kj::Maybe getFieldByDiscriminant(uint16_t discriminant) const; - // Finds the field whose `discriminantValue` is equal to the given value, or returns null if - // there is no such field. (If the schema does not represent a union or a struct containing - // an unnamed union, then this always returns null.) - -private: - StructSchema(Schema base): Schema(base) {} - template static inline StructSchema fromImpl() { - return StructSchema(Schema(&_::rawBrandedSchema())); - } - friend class Schema; - friend class Type; -}; - -class StructSchema::Field { -public: - Field() = default; - - inline schema::Field::Reader getProto() const { return proto; } - inline StructSchema getContainingStruct() const { return parent; } - - inline uint getIndex() const { return index; } - // Get the index of this field within the containing struct or union. - - Type getType() const; - // Get the type of this field. Note that this is preferred over getProto().getType() as this - // method will apply generics. - - uint32_t getDefaultValueSchemaOffset() const; - // For struct, list, and object fields, returns the offset, in words, within the first segment of - // the struct's schema, where this field's default value pointer is located. The schema is - // always stored as a single-segment unchecked message, which in turn means that the default - // value pointer itself can be treated as the root of an unchecked message -- if you know where - // to find it, which is what this method helps you with. - // - // For blobs, returns the offset of the beginning of the blob's content within the first segment - // of the struct's schema. - // - // This is primarily useful for code generators. The C++ code generator, for example, embeds - // the entire schema as a raw word array within the generated code. Of course, to implement - // field accessors, it needs access to those fields' default values. Embedding separate copies - // of those default values would be redundant since they are already included in the schema, but - // seeking through the schema at runtime to find the default values would be ugly. Instead, - // the code generator can use getDefaultValueSchemaOffset() to find the offset of the default - // value within the schema, and can simply apply that offset at runtime. - // - // If the above does not make sense, you probably don't need this method. - - inline bool operator==(const Field& other) const; - inline bool operator!=(const Field& other) const { return !(*this == other); } - -private: - StructSchema parent; - uint index; - schema::Field::Reader proto; - - inline Field(StructSchema parent, uint index, schema::Field::Reader proto) - : parent(parent), index(index), proto(proto) {} - - friend class StructSchema; -}; - -kj::StringPtr KJ_STRINGIFY(const StructSchema::Field& field); - -class StructSchema::FieldList { -public: - FieldList() = default; // empty list - - inline uint size() const { return list.size(); } - inline Field operator[](uint index) const { return Field(parent, index, list[index]); } - - typedef _::IndexingIterator Iterator; - inline Iterator begin() const { return Iterator(this, 0); } - inline Iterator end() const { return Iterator(this, size()); } - -private: - StructSchema parent; - List::Reader list; - - inline FieldList(StructSchema parent, List::Reader list) - : parent(parent), list(list) {} - - friend class StructSchema; -}; - -class StructSchema::FieldSubset { -public: - FieldSubset() = default; // empty list - - inline uint size() const { return size_; } - inline Field operator[](uint index) const { - return Field(parent, indices[index], list[indices[index]]); - } - - typedef _::IndexingIterator Iterator; - inline Iterator begin() const { return Iterator(this, 0); } - inline Iterator end() const { return Iterator(this, size()); } - -private: - StructSchema parent; - List::Reader list; - const uint16_t* indices; - uint size_; - - inline FieldSubset(StructSchema parent, List::Reader list, - const uint16_t* indices, uint size) - : parent(parent), list(list), indices(indices), size_(size) {} - - friend class StructSchema; -}; - -// ------------------------------------------------------------------- - -class EnumSchema: public Schema { -public: - inline EnumSchema(): Schema(&_::NULL_ENUM_SCHEMA.defaultBrand) {} - - class Enumerant; - class EnumerantList; - - EnumerantList getEnumerants() const; - - kj::Maybe findEnumerantByName(kj::StringPtr name) const; - - Enumerant getEnumerantByName(kj::StringPtr name) const; - // Like findEnumerantByName() but throws an exception on failure. - -private: - EnumSchema(Schema base): Schema(base) {} - template static inline EnumSchema fromImpl() { - return EnumSchema(Schema(&_::rawBrandedSchema())); - } - friend class Schema; - friend class Type; -}; - -class EnumSchema::Enumerant { -public: - Enumerant() = default; - - inline schema::Enumerant::Reader getProto() const { return proto; } - inline EnumSchema getContainingEnum() const { return parent; } - - inline uint16_t getOrdinal() const { return ordinal; } - inline uint getIndex() const { return ordinal; } - - inline bool operator==(const Enumerant& other) const; - inline bool operator!=(const Enumerant& other) const { return !(*this == other); } - -private: - EnumSchema parent; - uint16_t ordinal; - schema::Enumerant::Reader proto; - - inline Enumerant(EnumSchema parent, uint16_t ordinal, schema::Enumerant::Reader proto) - : parent(parent), ordinal(ordinal), proto(proto) {} - - friend class EnumSchema; -}; - -class EnumSchema::EnumerantList { -public: - EnumerantList() = default; // empty list - - inline uint size() const { return list.size(); } - inline Enumerant operator[](uint index) const { return Enumerant(parent, index, list[index]); } - - typedef _::IndexingIterator Iterator; - inline Iterator begin() const { return Iterator(this, 0); } - inline Iterator end() const { return Iterator(this, size()); } - -private: - EnumSchema parent; - List::Reader list; - - inline EnumerantList(EnumSchema parent, List::Reader list) - : parent(parent), list(list) {} - - friend class EnumSchema; -}; - -// ------------------------------------------------------------------- - -class InterfaceSchema: public Schema { -public: - inline InterfaceSchema(): Schema(&_::NULL_INTERFACE_SCHEMA.defaultBrand) {} - - class Method; - class MethodList; - - MethodList getMethods() const; - - kj::Maybe findMethodByName(kj::StringPtr name) const; - - Method getMethodByName(kj::StringPtr name) const; - // Like findMethodByName() but throws an exception on failure. - - class SuperclassList; - - SuperclassList getSuperclasses() const; - // Get the immediate superclasses of this type, after applying generics. - - bool extends(InterfaceSchema other) const; - // Returns true if `other` is a superclass of this interface (including if `other == *this`). - - kj::Maybe findSuperclass(uint64_t typeId) const; - // Find the superclass of this interface with the given type ID. Returns null if the interface - // extends no such type. - -private: - InterfaceSchema(Schema base): Schema(base) {} - template static inline InterfaceSchema fromImpl() { - return InterfaceSchema(Schema(&_::rawBrandedSchema())); - } - friend class Schema; - friend class Type; - - kj::Maybe findMethodByName(kj::StringPtr name, uint& counter) const; - bool extends(InterfaceSchema other, uint& counter) const; - kj::Maybe findSuperclass(uint64_t typeId, uint& counter) const; - // We protect against malicious schemas with large or cyclic hierarchies by cutting off the - // search when the counter reaches a threshold. -}; - -class InterfaceSchema::Method { -public: - Method() = default; - - inline schema::Method::Reader getProto() const { return proto; } - inline InterfaceSchema getContainingInterface() const { return parent; } - - inline uint16_t getOrdinal() const { return ordinal; } - inline uint getIndex() const { return ordinal; } - - StructSchema getParamType() const; - StructSchema getResultType() const; - // Get the parameter and result types, including substituting generic parameters. - - inline bool operator==(const Method& other) const; - inline bool operator!=(const Method& other) const { return !(*this == other); } - -private: - InterfaceSchema parent; - uint16_t ordinal; - schema::Method::Reader proto; - - inline Method(InterfaceSchema parent, uint16_t ordinal, - schema::Method::Reader proto) - : parent(parent), ordinal(ordinal), proto(proto) {} - - friend class InterfaceSchema; -}; - -class InterfaceSchema::MethodList { -public: - MethodList() = default; // empty list - - inline uint size() const { return list.size(); } - inline Method operator[](uint index) const { return Method(parent, index, list[index]); } - - typedef _::IndexingIterator Iterator; - inline Iterator begin() const { return Iterator(this, 0); } - inline Iterator end() const { return Iterator(this, size()); } - -private: - InterfaceSchema parent; - List::Reader list; - - inline MethodList(InterfaceSchema parent, List::Reader list) - : parent(parent), list(list) {} - - friend class InterfaceSchema; -}; - -class InterfaceSchema::SuperclassList { -public: - SuperclassList() = default; // empty list - - inline uint size() const { return list.size(); } - InterfaceSchema operator[](uint index) const; - - typedef _::IndexingIterator Iterator; - inline Iterator begin() const { return Iterator(this, 0); } - inline Iterator end() const { return Iterator(this, size()); } - -private: - InterfaceSchema parent; - List::Reader list; - - inline SuperclassList(InterfaceSchema parent, List::Reader list) - : parent(parent), list(list) {} - - friend class InterfaceSchema; -}; - -// ------------------------------------------------------------------- - -class ConstSchema: public Schema { - // Represents a constant declaration. - // - // `ConstSchema` can be implicitly cast to DynamicValue to read its value. - -public: - inline ConstSchema(): Schema(&_::NULL_CONST_SCHEMA.defaultBrand) {} - - template - ReaderFor as() const; - // Read the constant's value. This is a convenience method equivalent to casting the ConstSchema - // to a DynamicValue and then calling its `as()` method. For dependency reasons, this method - // is defined in , which you must #include explicitly. - - uint32_t getValueSchemaOffset() const; - // Much like StructSchema::Field::getDefaultValueSchemaOffset(), if the constant has pointer - // type, this gets the offset from the beginning of the constant's schema node to a pointer - // representing the constant value. - - Type getType() const; - -private: - ConstSchema(Schema base): Schema(base) {} - friend class Schema; -}; - -// ------------------------------------------------------------------- - -class Type { -public: - struct BrandParameter { - uint64_t scopeId; - uint index; - }; - struct ImplicitParameter { - uint index; - }; - - inline Type(); - inline Type(schema::Type::Which primitive); - inline Type(StructSchema schema); - inline Type(EnumSchema schema); - inline Type(InterfaceSchema schema); - inline Type(ListSchema schema); - inline Type(schema::Type::AnyPointer::Unconstrained::Which anyPointerKind); - inline Type(BrandParameter param); - inline Type(ImplicitParameter param); - - template - inline static Type from(); - - inline schema::Type::Which which() const; - - StructSchema asStruct() const; - EnumSchema asEnum() const; - InterfaceSchema asInterface() const; - ListSchema asList() const; - // Each of these methods may only be called if which() returns the corresponding type. - - kj::Maybe getBrandParameter() const; - // Only callable if which() returns ANY_POINTER. Returns null if the type is just a regular - // AnyPointer and not a parameter. - - kj::Maybe getImplicitParameter() const; - // Only callable if which() returns ANY_POINTER. Returns null if the type is just a regular - // AnyPointer and not a parameter. "Implicit parameters" refer to type parameters on methods. - - inline schema::Type::AnyPointer::Unconstrained::Which whichAnyPointerKind() const; - // Only callable if which() returns ANY_POINTER. - - inline bool isVoid() const; - inline bool isBool() const; - inline bool isInt8() const; - inline bool isInt16() const; - inline bool isInt32() const; - inline bool isInt64() const; - inline bool isUInt8() const; - inline bool isUInt16() const; - inline bool isUInt32() const; - inline bool isUInt64() const; - inline bool isFloat32() const; - inline bool isFloat64() const; - inline bool isText() const; - inline bool isData() const; - inline bool isList() const; - inline bool isEnum() const; - inline bool isStruct() const; - inline bool isInterface() const; - inline bool isAnyPointer() const; - - bool operator==(const Type& other) const; - inline bool operator!=(const Type& other) const { return !(*this == other); } - - size_t hashCode() const; - - inline Type wrapInList(uint depth = 1) const; - // Return the Type formed by wrapping this type in List() `depth` times. - - inline Type(schema::Type::Which derived, const _::RawBrandedSchema* schema); - // For internal use. - -private: - schema::Type::Which baseType; // type not including applications of List() - uint8_t listDepth; // 0 for T, 1 for List(T), 2 for List(List(T)), ... - - bool isImplicitParam; - // If true, this refers to an implicit method parameter. baseType must be ANY_POINTER, scopeId - // must be zero, and paramIndex indicates the parameter index. - - union { - uint16_t paramIndex; - // If baseType is ANY_POINTER but this Type actually refers to a type parameter, this is the - // index of the parameter among the parameters at its scope, and `scopeId` below is the type ID - // of the scope where the parameter was defined. - - schema::Type::AnyPointer::Unconstrained::Which anyPointerKind; - // If scopeId is zero and isImplicitParam is false. - }; - - union { - const _::RawBrandedSchema* schema; // if type is struct, enum, interface... - uint64_t scopeId; // if type is AnyPointer but it's actually a type parameter... - }; - - Type(schema::Type::Which baseType, uint8_t listDepth, const _::RawBrandedSchema* schema) - : baseType(baseType), listDepth(listDepth), schema(schema) { - KJ_IREQUIRE(baseType != schema::Type::ANY_POINTER); - } - - void requireUsableAs(Type expected) const; - - friend class ListSchema; // only for requireUsableAs() -}; - -// ------------------------------------------------------------------- - -class ListSchema { - // ListSchema is a little different because list types are not described by schema nodes. So, - // ListSchema doesn't subclass Schema. - -public: - ListSchema() = default; - - static ListSchema of(schema::Type::Which primitiveType); - static ListSchema of(StructSchema elementType); - static ListSchema of(EnumSchema elementType); - static ListSchema of(InterfaceSchema elementType); - static ListSchema of(ListSchema elementType); - static ListSchema of(Type elementType); - // Construct the schema for a list of the given type. - - static ListSchema of(schema::Type::Reader elementType, Schema context) - KJ_DEPRECATED("Does not handle generics correctly."); - // DEPRECATED: This method cannot correctly account for generic type parameter bindings that - // may apply to the input type. Instead of using this method, use a method of the Schema API - // that corresponds to the exact kind of dependency. For example, to get a field type, use - // StructSchema::Field::getType(). - // - // Construct from an element type schema. Requires a context which can handle getDependency() - // requests for any type ID found in the schema. - - Type getElementType() const; - - inline schema::Type::Which whichElementType() const; - // Get the element type's "which()". ListSchema does not actually store a schema::Type::Reader - // describing the element type, but if it did, this would be equivalent to calling - // .getBody().which() on that type. - - StructSchema getStructElementType() const; - EnumSchema getEnumElementType() const; - InterfaceSchema getInterfaceElementType() const; - ListSchema getListElementType() const; - // Get the schema for complex element types. Each of these throws an exception if the element - // type is not of the requested kind. - - inline bool operator==(const ListSchema& other) const { return elementType == other.elementType; } - inline bool operator!=(const ListSchema& other) const { return elementType != other.elementType; } - - template - void requireUsableAs() const; - -private: - Type elementType; - - inline explicit ListSchema(Type elementType): elementType(elementType) {} - - template - struct FromImpl; - template static inline ListSchema fromImpl() { - return FromImpl::get(); - } - - void requireUsableAs(ListSchema expected) const; - - friend class Schema; -}; - -// ======================================================================================= -// inline implementation - -template <> inline schema::Type::Which Schema::from() { return schema::Type::VOID; } -template <> inline schema::Type::Which Schema::from() { return schema::Type::BOOL; } -template <> inline schema::Type::Which Schema::from() { return schema::Type::INT8; } -template <> inline schema::Type::Which Schema::from() { return schema::Type::INT16; } -template <> inline schema::Type::Which Schema::from() { return schema::Type::INT32; } -template <> inline schema::Type::Which Schema::from() { return schema::Type::INT64; } -template <> inline schema::Type::Which Schema::from() { return schema::Type::UINT8; } -template <> inline schema::Type::Which Schema::from() { return schema::Type::UINT16; } -template <> inline schema::Type::Which Schema::from() { return schema::Type::UINT32; } -template <> inline schema::Type::Which Schema::from() { return schema::Type::UINT64; } -template <> inline schema::Type::Which Schema::from() { return schema::Type::FLOAT32; } -template <> inline schema::Type::Which Schema::from() { return schema::Type::FLOAT64; } -template <> inline schema::Type::Which Schema::from() { return schema::Type::TEXT; } -template <> inline schema::Type::Which Schema::from() { return schema::Type::DATA; } - -inline Schema Schema::getDependency(uint64_t id) const { - return getDependency(id, 0); -} - -inline bool Schema::isBranded() const { - return raw != &raw->generic->defaultBrand; -} - -inline Schema Schema::getGeneric() const { - return Schema(&raw->generic->defaultBrand); -} - -template -inline void Schema::requireUsableAs() const { - requireUsableAs(&_::rawSchema()); -} - -inline bool StructSchema::Field::operator==(const Field& other) const { - return parent == other.parent && index == other.index; -} -inline bool EnumSchema::Enumerant::operator==(const Enumerant& other) const { - return parent == other.parent && ordinal == other.ordinal; -} -inline bool InterfaceSchema::Method::operator==(const Method& other) const { - return parent == other.parent && ordinal == other.ordinal; -} - -inline ListSchema ListSchema::of(StructSchema elementType) { - return ListSchema(Type(elementType)); -} -inline ListSchema ListSchema::of(EnumSchema elementType) { - return ListSchema(Type(elementType)); -} -inline ListSchema ListSchema::of(InterfaceSchema elementType) { - return ListSchema(Type(elementType)); -} -inline ListSchema ListSchema::of(ListSchema elementType) { - return ListSchema(Type(elementType)); -} -inline ListSchema ListSchema::of(Type elementType) { - return ListSchema(elementType); -} - -inline Type ListSchema::getElementType() const { - return elementType; -} - -inline schema::Type::Which ListSchema::whichElementType() const { - return elementType.which(); -} - -inline StructSchema ListSchema::getStructElementType() const { - return elementType.asStruct(); -} - -inline EnumSchema ListSchema::getEnumElementType() const { - return elementType.asEnum(); -} - -inline InterfaceSchema ListSchema::getInterfaceElementType() const { - return elementType.asInterface(); -} - -inline ListSchema ListSchema::getListElementType() const { - return elementType.asList(); -} - -template -inline void ListSchema::requireUsableAs() const { - static_assert(kind() == Kind::LIST, - "ListSchema::requireUsableAs() requires T is a list type."); - requireUsableAs(Schema::from()); -} - -inline void ListSchema::requireUsableAs(ListSchema expected) const { - elementType.requireUsableAs(expected.elementType); -} - -template -struct ListSchema::FromImpl> { - static inline ListSchema get() { return of(Schema::from()); } -}; - -inline Type::Type(): baseType(schema::Type::VOID), listDepth(0), schema(nullptr) {} -inline Type::Type(schema::Type::Which primitive) - : baseType(primitive), listDepth(0), isImplicitParam(false) { - KJ_IREQUIRE(primitive != schema::Type::STRUCT && - primitive != schema::Type::ENUM && - primitive != schema::Type::INTERFACE && - primitive != schema::Type::LIST); - if (primitive == schema::Type::ANY_POINTER) { - scopeId = 0; - anyPointerKind = schema::Type::AnyPointer::Unconstrained::ANY_KIND; - } else { - schema = nullptr; - } -} -inline Type::Type(schema::Type::Which derived, const _::RawBrandedSchema* schema) - : baseType(derived), listDepth(0), isImplicitParam(false), schema(schema) { - KJ_IREQUIRE(derived == schema::Type::STRUCT || - derived == schema::Type::ENUM || - derived == schema::Type::INTERFACE); -} - -inline Type::Type(StructSchema schema) - : baseType(schema::Type::STRUCT), listDepth(0), schema(schema.raw) {} -inline Type::Type(EnumSchema schema) - : baseType(schema::Type::ENUM), listDepth(0), schema(schema.raw) {} -inline Type::Type(InterfaceSchema schema) - : baseType(schema::Type::INTERFACE), listDepth(0), schema(schema.raw) {} -inline Type::Type(ListSchema schema) - : Type(schema.getElementType()) { ++listDepth; } -inline Type::Type(schema::Type::AnyPointer::Unconstrained::Which anyPointerKind) - : baseType(schema::Type::ANY_POINTER), listDepth(0), isImplicitParam(false), - anyPointerKind(anyPointerKind), scopeId(0) {} -inline Type::Type(BrandParameter param) - : baseType(schema::Type::ANY_POINTER), listDepth(0), isImplicitParam(false), - paramIndex(param.index), scopeId(param.scopeId) {} -inline Type::Type(ImplicitParameter param) - : baseType(schema::Type::ANY_POINTER), listDepth(0), isImplicitParam(true), - paramIndex(param.index), scopeId(0) {} - -inline schema::Type::Which Type::which() const { - return listDepth > 0 ? schema::Type::LIST : baseType; -} - -inline schema::Type::AnyPointer::Unconstrained::Which Type::whichAnyPointerKind() const { - KJ_IREQUIRE(baseType == schema::Type::ANY_POINTER); - return !isImplicitParam && scopeId == 0 ? anyPointerKind - : schema::Type::AnyPointer::Unconstrained::ANY_KIND; -} - -template -inline Type Type::from() { return Type(Schema::from()); } - -inline bool Type::isVoid () const { return baseType == schema::Type::VOID && listDepth == 0; } -inline bool Type::isBool () const { return baseType == schema::Type::BOOL && listDepth == 0; } -inline bool Type::isInt8 () const { return baseType == schema::Type::INT8 && listDepth == 0; } -inline bool Type::isInt16 () const { return baseType == schema::Type::INT16 && listDepth == 0; } -inline bool Type::isInt32 () const { return baseType == schema::Type::INT32 && listDepth == 0; } -inline bool Type::isInt64 () const { return baseType == schema::Type::INT64 && listDepth == 0; } -inline bool Type::isUInt8 () const { return baseType == schema::Type::UINT8 && listDepth == 0; } -inline bool Type::isUInt16 () const { return baseType == schema::Type::UINT16 && listDepth == 0; } -inline bool Type::isUInt32 () const { return baseType == schema::Type::UINT32 && listDepth == 0; } -inline bool Type::isUInt64 () const { return baseType == schema::Type::UINT64 && listDepth == 0; } -inline bool Type::isFloat32() const { return baseType == schema::Type::FLOAT32 && listDepth == 0; } -inline bool Type::isFloat64() const { return baseType == schema::Type::FLOAT64 && listDepth == 0; } -inline bool Type::isText () const { return baseType == schema::Type::TEXT && listDepth == 0; } -inline bool Type::isData () const { return baseType == schema::Type::DATA && listDepth == 0; } -inline bool Type::isList () const { return listDepth > 0; } -inline bool Type::isEnum () const { return baseType == schema::Type::ENUM && listDepth == 0; } -inline bool Type::isStruct () const { return baseType == schema::Type::STRUCT && listDepth == 0; } -inline bool Type::isInterface() const { - return baseType == schema::Type::INTERFACE && listDepth == 0; -} -inline bool Type::isAnyPointer() const { - return baseType == schema::Type::ANY_POINTER && listDepth == 0; -} - -inline Type Type::wrapInList(uint depth) const { - Type result = *this; - result.listDepth += depth; - return result; -} - -} // namespace capnp - -#endif // CAPNP_SCHEMA_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/serialize-async.h b/phonelibs/capnp-cpp/include/capnp/serialize-async.h deleted file mode 100644 index a16bfd8975..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/serialize-async.h +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_SERIALIZE_ASYNC_H_ -#define CAPNP_SERIALIZE_ASYNC_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include -#include "message.h" - -namespace capnp { - -kj::Promise> readMessage( - kj::AsyncInputStream& input, ReaderOptions options = ReaderOptions(), - kj::ArrayPtr scratchSpace = nullptr); -// Read a message asynchronously. -// -// `input` must remain valid until the returned promise resolves (or is canceled). -// -// `scratchSpace`, if provided, must remain valid until the returned MessageReader is destroyed. - -kj::Promise>> tryReadMessage( - kj::AsyncInputStream& input, ReaderOptions options = ReaderOptions(), - kj::ArrayPtr scratchSpace = nullptr); -// Like `readMessage` but returns null on EOF. - -kj::Promise writeMessage(kj::AsyncOutputStream& output, - kj::ArrayPtr> segments) - KJ_WARN_UNUSED_RESULT; -kj::Promise writeMessage(kj::AsyncOutputStream& output, MessageBuilder& builder) - KJ_WARN_UNUSED_RESULT; -// Write asynchronously. The parameters must remain valid until the returned promise resolves. - -// ======================================================================================= -// inline implementation details - -inline kj::Promise writeMessage(kj::AsyncOutputStream& output, MessageBuilder& builder) { - return writeMessage(output, builder.getSegmentsForOutput()); -} - -} // namespace capnp - -#endif // CAPNP_SERIALIZE_ASYNC_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/serialize-packed.h b/phonelibs/capnp-cpp/include/capnp/serialize-packed.h deleted file mode 100644 index a71260ce1d..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/serialize-packed.h +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_SERIALIZE_PACKED_H_ -#define CAPNP_SERIALIZE_PACKED_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include "serialize.h" - -namespace capnp { - -namespace _ { // private - -class PackedInputStream: public kj::InputStream { - // An input stream that unpacks packed data with a picky constraint: The caller must read data - // in the exact same size and sequence as the data was written to PackedOutputStream. - -public: - explicit PackedInputStream(kj::BufferedInputStream& inner); - KJ_DISALLOW_COPY(PackedInputStream); - ~PackedInputStream() noexcept(false); - - // implements InputStream ------------------------------------------ - size_t tryRead(void* buffer, size_t minBytes, size_t maxBytes) override; - void skip(size_t bytes) override; - -private: - kj::BufferedInputStream& inner; -}; - -class PackedOutputStream: public kj::OutputStream { -public: - explicit PackedOutputStream(kj::BufferedOutputStream& inner); - KJ_DISALLOW_COPY(PackedOutputStream); - ~PackedOutputStream() noexcept(false); - - // implements OutputStream ----------------------------------------- - void write(const void* buffer, size_t bytes) override; - -private: - kj::BufferedOutputStream& inner; -}; - -} // namespace _ (private) - -class PackedMessageReader: private _::PackedInputStream, public InputStreamMessageReader { -public: - PackedMessageReader(kj::BufferedInputStream& inputStream, ReaderOptions options = ReaderOptions(), - kj::ArrayPtr scratchSpace = nullptr); - KJ_DISALLOW_COPY(PackedMessageReader); - ~PackedMessageReader() noexcept(false); -}; - -class PackedFdMessageReader: private kj::FdInputStream, private kj::BufferedInputStreamWrapper, - public PackedMessageReader { -public: - PackedFdMessageReader(int fd, ReaderOptions options = ReaderOptions(), - kj::ArrayPtr scratchSpace = nullptr); - // Read message from a file descriptor, without taking ownership of the descriptor. - // Note that if you want to reuse the descriptor after the reader is destroyed, you'll need to - // seek it, since otherwise the position is unspecified. - - PackedFdMessageReader(kj::AutoCloseFd fd, ReaderOptions options = ReaderOptions(), - kj::ArrayPtr scratchSpace = nullptr); - // Read a message from a file descriptor, taking ownership of the descriptor. - - KJ_DISALLOW_COPY(PackedFdMessageReader); - - ~PackedFdMessageReader() noexcept(false); -}; - -void writePackedMessage(kj::BufferedOutputStream& output, MessageBuilder& builder); -void writePackedMessage(kj::BufferedOutputStream& output, - kj::ArrayPtr> segments); -// Write a packed message to a buffered output stream. - -void writePackedMessage(kj::OutputStream& output, MessageBuilder& builder); -void writePackedMessage(kj::OutputStream& output, - kj::ArrayPtr> segments); -// Write a packed message to an unbuffered output stream. If you intend to write multiple messages -// in succession, consider wrapping your output in a buffered stream in order to reduce system -// call overhead. - -void writePackedMessageToFd(int fd, MessageBuilder& builder); -void writePackedMessageToFd(int fd, kj::ArrayPtr> segments); -// Write a single packed message to the file descriptor. - -size_t computeUnpackedSizeInWords(kj::ArrayPtr packedBytes); -// Computes the number of words to which the given packed bytes will unpack. Not intended for use -// in performance-sensitive situations. - -// ======================================================================================= -// inline stuff - -inline void writePackedMessage(kj::BufferedOutputStream& output, MessageBuilder& builder) { - writePackedMessage(output, builder.getSegmentsForOutput()); -} - -inline void writePackedMessage(kj::OutputStream& output, MessageBuilder& builder) { - writePackedMessage(output, builder.getSegmentsForOutput()); -} - -inline void writePackedMessageToFd(int fd, MessageBuilder& builder) { - writePackedMessageToFd(fd, builder.getSegmentsForOutput()); -} - -} // namespace capnp - -#endif // CAPNP_SERIALIZE_PACKED_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/serialize-text.h b/phonelibs/capnp-cpp/include/capnp/serialize-text.h deleted file mode 100644 index d86fc2c00e..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/serialize-text.h +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) 2015 Philip Quinn. -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef CAPNP_SERIALIZE_TEXT_H_ -#define CAPNP_SERIALIZE_TEXT_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include -#include "dynamic.h" -#include "orphan.h" -#include "schema.h" - -namespace capnp { - -class TextCodec { - // Reads and writes Cap'n Proto objects in a plain text format (as used in the schema - // language for constants, and read/written by the 'decode' and 'encode' commands of - // the capnp tool). - // - // This format is useful for debugging or human input, but it is not a robust alternative - // to the binary format. Changes to a schema's types or names that are permitted in a - // schema's binary evolution will likely break messages stored in this format. - // - // Note that definitions or references (to constants, other fields, or files) are not - // permitted in this format. To evaluate declarations with the full expressiveness of the - // schema language, see `capnp::SchemaParser`. - // - // Requires linking with the capnpc library. - -public: - TextCodec(); - ~TextCodec() noexcept(true); - - void setPrettyPrint(bool enabled); - // If enabled, pads the output of `encode()` with spaces and newlines to make it more - // human-readable. - - template - kj::String encode(T&& value) const; - kj::String encode(DynamicValue::Reader value) const; - // Encode any Cap'n Proto value. - - template - Orphan decode(kj::StringPtr input, Orphanage orphanage) const; - // Decode a text message into a Cap'n Proto object of type T, allocated in the given - // orphanage. Any errors parsing the input or assigning the fields of T are thrown as - // exceptions. - - void decode(kj::StringPtr input, DynamicStruct::Builder output) const; - // Decode a text message for a struct into the given builder. Any errors parsing the - // input or assigning the fields of the output are thrown as exceptions. - - // TODO(someday): expose some control over the error handling? -private: - Orphan decode(kj::StringPtr input, Type type, Orphanage orphanage) const; - - bool prettyPrint; -}; - -// ======================================================================================= -// inline stuff - -template -inline kj::String TextCodec::encode(T&& value) const { - return encode(DynamicValue::Reader(ReaderFor>(kj::fwd(value)))); -} - -template -inline Orphan TextCodec::decode(kj::StringPtr input, Orphanage orphanage) const { - return decode(input, Type::from(), orphanage).template releaseAs(); -} - -} // namespace capnp - -#endif // CAPNP_SERIALIZE_TEXT_H_ diff --git a/phonelibs/capnp-cpp/include/capnp/serialize.h b/phonelibs/capnp-cpp/include/capnp/serialize.h deleted file mode 100644 index 797db51766..0000000000 --- a/phonelibs/capnp-cpp/include/capnp/serialize.h +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// This file implements a simple serialization format for Cap'n Proto messages. The format -// is as follows: -// -// * 32-bit little-endian segment count (4 bytes). -// * 32-bit little-endian size of each segment (4*(segment count) bytes). -// * Padding so that subsequent data is 64-bit-aligned (0 or 4 bytes). (I.e., if there are an even -// number of segments, there are 4 bytes of zeros here, otherwise there is no padding.) -// * Data from each segment, in order (8*sum(segment sizes) bytes) -// -// This format has some important properties: -// - It is self-delimiting, so multiple messages may be written to a stream without any external -// delimiter. -// - The total size and position of each segment can be determined by reading only the first part -// of the message, allowing lazy and random-access reading of the segment data. -// - A message is always at least 8 bytes. -// - A single-segment message can be read entirely in two system calls with no buffering. -// - A multi-segment message can be read entirely in three system calls with no buffering. -// - The format is appropriate for mmap()ing since all data is aligned. - -#ifndef CAPNP_SERIALIZE_H_ -#define CAPNP_SERIALIZE_H_ - -#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) -#pragma GCC system_header -#endif - -#include "message.h" -#include - -namespace capnp { - -class FlatArrayMessageReader: public MessageReader { - // Parses a message from a flat array. Note that it makes sense to use this together with mmap() - // for extremely fast parsing. - -public: - FlatArrayMessageReader(kj::ArrayPtr array, ReaderOptions options = ReaderOptions()); - // The array must remain valid until the MessageReader is destroyed. - - kj::ArrayPtr getSegment(uint id) override; - - const word* getEnd() const { return end; } - // Get a pointer just past the end of the message as determined by reading the message header. - // This could actually be before the end of the input array. This pointer is useful e.g. if - // you know that the input array has extra stuff appended after the message and you want to - // get at it. - -private: - // Optimize for single-segment case. - kj::ArrayPtr segment0; - kj::Array> moreSegments; - const word* end; -}; - -kj::ArrayPtr initMessageBuilderFromFlatArrayCopy( - kj::ArrayPtr array, MessageBuilder& target, - ReaderOptions options = ReaderOptions()); -// Convenience function which reads a message using `FlatArrayMessageReader` then copies the -// content into the target `MessageBuilder`, verifying that the message structure is valid -// (although not necessarily that it matches the desired schema). -// -// Returns an ArrayPtr containing any words left over in the array after consuming the whole -// message. This is useful when reading multiple messages that have been concatenated. See also -// FlatArrayMessageReader::getEnd(). -// -// (Note that it's also possible to initialize a `MessageBuilder` directly without a copy using one -// of `MessageBuilder`'s constructors. However, this approach skips the validation step and is not -// safe to use on untrusted input. Therefore, we do not provide a convenience method for it.) - -kj::Array messageToFlatArray(MessageBuilder& builder); -// Constructs a flat array containing the entire content of the given message. -// -// To output the message as bytes, use `.asBytes()` on the returned word array. Keep in mind that -// `asBytes()` returns an ArrayPtr, so you have to save the Array as well to prevent it from being -// deleted. For example: -// -// kj::Array words = messageToFlatArray(myMessage); -// kj::ArrayPtr bytes = words.asBytes(); -// write(fd, bytes.begin(), bytes.size()); - -kj::Array messageToFlatArray(kj::ArrayPtr> segments); -// Version of messageToFlatArray that takes a raw segment array. - -size_t computeSerializedSizeInWords(MessageBuilder& builder); -// Returns the size, in words, that will be needed to serialize the message, including the header. - -size_t computeSerializedSizeInWords(kj::ArrayPtr> segments); -// Version of computeSerializedSizeInWords that takes a raw segment array. - -size_t expectedSizeInWordsFromPrefix(kj::ArrayPtr messagePrefix); -// Given a prefix of a serialized message, try to determine the expected total size of the message, -// in words. The returned size is based on the information known so far; it may be an underestimate -// if the prefix doesn't contain the full segment table. -// -// If the returned value is greater than `messagePrefix.size()`, then the message is not yet -// complete and the app cannot parse it yet. If the returned value is less than or equal to -// `messagePrefix.size()`, then the returned value is the exact total size of the message; any -// remaining bytes are part of the next message. -// -// This function is useful when reading messages from a stream in an asynchronous way, but when -// using the full KJ async infrastructure would be too difficult. Each time bytes are received, -// use this function to determine if an entire message is ready to be parsed. - -// ======================================================================================= - -class InputStreamMessageReader: public MessageReader { - // A MessageReader that reads from an abstract kj::InputStream. See also StreamFdMessageReader - // for a subclass specific to file descriptors. - -public: - InputStreamMessageReader(kj::InputStream& inputStream, - ReaderOptions options = ReaderOptions(), - kj::ArrayPtr scratchSpace = nullptr); - ~InputStreamMessageReader() noexcept(false); - - // implements MessageReader ---------------------------------------- - kj::ArrayPtr getSegment(uint id) override; - -private: - kj::InputStream& inputStream; - byte* readPos; - - // Optimize for single-segment case. - kj::ArrayPtr segment0; - kj::Array> moreSegments; - - kj::Array ownedSpace; - // Only if scratchSpace wasn't big enough. - - kj::UnwindDetector unwindDetector; -}; - -void readMessageCopy(kj::InputStream& input, MessageBuilder& target, - ReaderOptions options = ReaderOptions(), - kj::ArrayPtr scratchSpace = nullptr); -// Convenience function which reads a message using `InputStreamMessageReader` then copies the -// content into the target `MessageBuilder`, verifying that the message structure is valid -// (although not necessarily that it matches the desired schema). -// -// (Note that it's also possible to initialize a `MessageBuilder` directly without a copy using one -// of `MessageBuilder`'s constructors. However, this approach skips the validation step and is not -// safe to use on untrusted input. Therefore, we do not provide a convenience method for it.) - -void writeMessage(kj::OutputStream& output, MessageBuilder& builder); -// Write the message to the given output stream. - -void writeMessage(kj::OutputStream& output, kj::ArrayPtr> segments); -// Write the segment array to the given output stream. - -// ======================================================================================= -// Specializations for reading from / writing to file descriptors. - -class StreamFdMessageReader: private kj::FdInputStream, public InputStreamMessageReader { - // A MessageReader that reads from a steam-based file descriptor. - -public: - StreamFdMessageReader(int fd, ReaderOptions options = ReaderOptions(), - kj::ArrayPtr scratchSpace = nullptr) - : FdInputStream(fd), InputStreamMessageReader(*this, options, scratchSpace) {} - // Read message from a file descriptor, without taking ownership of the descriptor. - - StreamFdMessageReader(kj::AutoCloseFd fd, ReaderOptions options = ReaderOptions(), - kj::ArrayPtr scratchSpace = nullptr) - : FdInputStream(kj::mv(fd)), InputStreamMessageReader(*this, options, scratchSpace) {} - // Read a message from a file descriptor, taking ownership of the descriptor. - - ~StreamFdMessageReader() noexcept(false); -}; - -void readMessageCopyFromFd(int fd, MessageBuilder& target, - ReaderOptions options = ReaderOptions(), - kj::ArrayPtr scratchSpace = nullptr); -// Convenience function which reads a message using `StreamFdMessageReader` then copies the -// content into the target `MessageBuilder`, verifying that the message structure is valid -// (although not necessarily that it matches the desired schema). -// -// (Note that it's also possible to initialize a `MessageBuilder` directly without a copy using one -// of `MessageBuilder`'s constructors. However, this approach skips the validation step and is not -// safe to use on untrusted input. Therefore, we do not provide a convenience method for it.) - -void writeMessageToFd(int fd, MessageBuilder& builder); -// Write the message to the given file descriptor. -// -// This function throws an exception on any I/O error. If your code is not exception-safe, be sure -// you catch this exception at the call site. If throwing an exception is not acceptable, you -// can implement your own OutputStream with arbitrary error handling and then use writeMessage(). - -void writeMessageToFd(int fd, kj::ArrayPtr> segments); -// Write the segment array to the given file descriptor. -// -// This function throws an exception on any I/O error. If your code is not exception-safe, be sure -// you catch this exception at the call site. If throwing an exception is not acceptable, you -// can implement your own OutputStream with arbitrary error handling and then use writeMessage(). - -// ======================================================================================= -// inline stuff - -inline kj::Array messageToFlatArray(MessageBuilder& builder) { - return messageToFlatArray(builder.getSegmentsForOutput()); -} - -inline size_t computeSerializedSizeInWords(MessageBuilder& builder) { - return computeSerializedSizeInWords(builder.getSegmentsForOutput()); -} - -inline void writeMessage(kj::OutputStream& output, MessageBuilder& builder) { - writeMessage(output, builder.getSegmentsForOutput()); -} - -inline void writeMessageToFd(int fd, MessageBuilder& builder) { - writeMessageToFd(fd, builder.getSegmentsForOutput()); -} - -} // namespace capnp - -#endif // SERIALIZE_H_ diff --git a/phonelibs/capnp-cpp/include/kj/arena.h b/phonelibs/capnp-cpp/include/kj/arena.h deleted file mode 100644 index 32c1f61c51..0000000000 --- a/phonelibs/capnp-cpp/include/kj/arena.h +++ /dev/null @@ -1,213 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_ARENA_H_ -#define KJ_ARENA_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "memory.h" -#include "array.h" -#include "string.h" - -namespace kj { - -class Arena { - // A class which allows several objects to be allocated in contiguous chunks of memory, then - // frees them all at once. - // - // Allocating from the same Arena in multiple threads concurrently is NOT safe, because making - // it safe would require atomic operations that would slow down allocation even when - // single-threaded. If you need to use arena allocation in a multithreaded context, consider - // allocating thread-local arenas. - -public: - explicit Arena(size_t chunkSizeHint = 1024); - // Create an Arena. `chunkSizeHint` hints at where to start when allocating chunks, but is only - // a hint -- the Arena will, for example, allocate progressively larger chunks as time goes on, - // in order to reduce overall allocation overhead. - - explicit Arena(ArrayPtr scratch); - // Allocates from the given scratch space first, only resorting to the heap when it runs out. - - KJ_DISALLOW_COPY(Arena); - ~Arena() noexcept(false); - - template - T& allocate(Params&&... params); - template - ArrayPtr allocateArray(size_t size); - // Allocate an object or array of type T. If T has a non-trivial destructor, that destructor - // will be run during the Arena's destructor. Such destructors are run in opposite order of - // allocation. Note that these methods must maintain a list of destructors to call, which has - // overhead, but this overhead only applies if T has a non-trivial destructor. - - template - Own allocateOwn(Params&&... params); - template - Array allocateOwnArray(size_t size); - template - ArrayBuilder allocateOwnArrayBuilder(size_t capacity); - // Allocate an object or array of type T. Destructors are executed when the returned Own - // or Array goes out-of-scope, which must happen before the Arena is destroyed. This variant - // is useful when you need to control when the destructor is called. This variant also avoids - // the need for the Arena itself to keep track of destructors to call later, which may make it - // slightly more efficient. - - template - inline T& copy(T&& value) { return allocate>(kj::fwd(value)); } - // Allocate a copy of the given value in the arena. This is just a shortcut for calling the - // type's copy (or move) constructor. - - StringPtr copyString(StringPtr content); - // Make a copy of the given string inside the arena, and return a pointer to the copy. - -private: - struct ChunkHeader { - ChunkHeader* next; - byte* pos; // first unallocated byte in this chunk - byte* end; // end of this chunk - }; - struct ObjectHeader { - void (*destructor)(void*); - ObjectHeader* next; - }; - - size_t nextChunkSize; - ChunkHeader* chunkList = nullptr; - ObjectHeader* objectList = nullptr; - - ChunkHeader* currentChunk = nullptr; - - void cleanup(); - // Run all destructors, leaving the above pointers null. If a destructor throws, the State is - // left in a consistent state, such that if cleanup() is called again, it will pick up where - // it left off. - - void* allocateBytes(size_t amount, uint alignment, bool hasDisposer); - // Allocate the given number of bytes. `hasDisposer` must be true if `setDisposer()` may be - // called on this pointer later. - - void* allocateBytesInternal(size_t amount, uint alignment); - // Try to allocate the given number of bytes without taking a lock. Fails if and only if there - // is no space left in the current chunk. - - void setDestructor(void* ptr, void (*destructor)(void*)); - // Schedule the given destructor to be executed when the Arena is destroyed. `ptr` must be a - // pointer previously returned by an `allocateBytes()` call for which `hasDisposer` was true. - - template - static void destroyArray(void* pointer) { - size_t elementCount = *reinterpret_cast(pointer); - constexpr size_t prefixSize = kj::max(alignof(T), sizeof(size_t)); - DestructorOnlyArrayDisposer::instance.disposeImpl( - reinterpret_cast(pointer) + prefixSize, - sizeof(T), elementCount, elementCount, &destroyObject); - } - - template - static void destroyObject(void* pointer) { - dtor(*reinterpret_cast(pointer)); - } -}; - -// ======================================================================================= -// Inline implementation details - -template -T& Arena::allocate(Params&&... params) { - T& result = *reinterpret_cast(allocateBytes( - sizeof(T), alignof(T), !__has_trivial_destructor(T))); - if (!__has_trivial_constructor(T) || sizeof...(Params) > 0) { - ctor(result, kj::fwd(params)...); - } - if (!__has_trivial_destructor(T)) { - setDestructor(&result, &destroyObject); - } - return result; -} - -template -ArrayPtr Arena::allocateArray(size_t size) { - if (__has_trivial_destructor(T)) { - ArrayPtr result = - arrayPtr(reinterpret_cast(allocateBytes( - sizeof(T) * size, alignof(T), false)), size); - if (!__has_trivial_constructor(T)) { - for (size_t i = 0; i < size; i++) { - ctor(result[i]); - } - } - return result; - } else { - // Allocate with a 64-bit prefix in which we store the array size. - constexpr size_t prefixSize = kj::max(alignof(T), sizeof(size_t)); - void* base = allocateBytes(sizeof(T) * size + prefixSize, alignof(T), true); - size_t& tag = *reinterpret_cast(base); - ArrayPtr result = - arrayPtr(reinterpret_cast(reinterpret_cast(base) + prefixSize), size); - setDestructor(base, &destroyArray); - - if (__has_trivial_constructor(T)) { - tag = size; - } else { - // In case of constructor exceptions, we need the tag to end up storing the number of objects - // that were successfully constructed, so that they'll be properly destroyed. - tag = 0; - for (size_t i = 0; i < size; i++) { - ctor(result[i]); - tag = i + 1; - } - } - return result; - } -} - -template -Own Arena::allocateOwn(Params&&... params) { - T& result = *reinterpret_cast(allocateBytes(sizeof(T), alignof(T), false)); - if (!__has_trivial_constructor(T) || sizeof...(Params) > 0) { - ctor(result, kj::fwd(params)...); - } - return Own(&result, DestructorOnlyDisposer::instance); -} - -template -Array Arena::allocateOwnArray(size_t size) { - ArrayBuilder result = allocateOwnArrayBuilder(size); - for (size_t i = 0; i < size; i++) { - result.add(); - } - return result.finish(); -} - -template -ArrayBuilder Arena::allocateOwnArrayBuilder(size_t capacity) { - return ArrayBuilder( - reinterpret_cast(allocateBytes(sizeof(T) * capacity, alignof(T), false)), - capacity, DestructorOnlyArrayDisposer::instance); -} - -} // namespace kj - -#endif // KJ_ARENA_H_ diff --git a/phonelibs/capnp-cpp/include/kj/array.h b/phonelibs/capnp-cpp/include/kj/array.h deleted file mode 100644 index 51b5dcf319..0000000000 --- a/phonelibs/capnp-cpp/include/kj/array.h +++ /dev/null @@ -1,813 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_ARRAY_H_ -#define KJ_ARRAY_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "common.h" -#include -#include - -namespace kj { - -// ======================================================================================= -// ArrayDisposer -- Implementation details. - -class ArrayDisposer { - // Much like Disposer from memory.h. - -protected: - // Do not declare a destructor, as doing so will force a global initializer for - // HeapArrayDisposer::instance. - - virtual void disposeImpl(void* firstElement, size_t elementSize, size_t elementCount, - size_t capacity, void (*destroyElement)(void*)) const = 0; - // Disposes of the array. `destroyElement` invokes the destructor of each element, or is nullptr - // if the elements have trivial destructors. `capacity` is the amount of space that was - // allocated while `elementCount` is the number of elements that were actually constructed; - // these are always the same number for Array but may be different when using ArrayBuilder. - -public: - - template - void dispose(T* firstElement, size_t elementCount, size_t capacity) const; - // Helper wrapper around disposeImpl(). - // - // Callers must not call dispose() on the same array twice, even if the first call throws - // an exception. - -private: - template - struct Dispose_; -}; - -class ExceptionSafeArrayUtil { - // Utility class that assists in constructing or destroying elements of an array, where the - // constructor or destructor could throw exceptions. In case of an exception, - // ExceptionSafeArrayUtil's destructor will call destructors on all elements that have been - // constructed but not destroyed. Remember that destructors that throw exceptions are required - // to use UnwindDetector to detect unwind and avoid exceptions in this case. Therefore, no more - // than one exception will be thrown (and the program will not terminate). - -public: - inline ExceptionSafeArrayUtil(void* ptr, size_t elementSize, size_t constructedElementCount, - void (*destroyElement)(void*)) - : pos(reinterpret_cast(ptr) + elementSize * constructedElementCount), - elementSize(elementSize), constructedElementCount(constructedElementCount), - destroyElement(destroyElement) {} - KJ_DISALLOW_COPY(ExceptionSafeArrayUtil); - - inline ~ExceptionSafeArrayUtil() noexcept(false) { - if (constructedElementCount > 0) destroyAll(); - } - - void construct(size_t count, void (*constructElement)(void*)); - // Construct the given number of elements. - - void destroyAll(); - // Destroy all elements. Call this immediately before ExceptionSafeArrayUtil goes out-of-scope - // to ensure that one element throwing an exception does not prevent the others from being - // destroyed. - - void release() { constructedElementCount = 0; } - // Prevent ExceptionSafeArrayUtil's destructor from destroying the constructed elements. - // Call this after you've successfully finished constructing. - -private: - byte* pos; - size_t elementSize; - size_t constructedElementCount; - void (*destroyElement)(void*); -}; - -class DestructorOnlyArrayDisposer: public ArrayDisposer { -public: - static const DestructorOnlyArrayDisposer instance; - - void disposeImpl(void* firstElement, size_t elementSize, size_t elementCount, - size_t capacity, void (*destroyElement)(void*)) const override; -}; - -class NullArrayDisposer: public ArrayDisposer { - // An ArrayDisposer that does nothing. Can be used to construct a fake Arrays that doesn't - // actually own its content. - -public: - static const NullArrayDisposer instance; - - void disposeImpl(void* firstElement, size_t elementSize, size_t elementCount, - size_t capacity, void (*destroyElement)(void*)) const override; -}; - -// ======================================================================================= -// Array - -template -class Array { - // An owned array which will automatically be disposed of (using an ArrayDisposer) in the - // destructor. Can be moved, but not copied. Much like Own, but for arrays rather than - // single objects. - -public: - inline Array(): ptr(nullptr), size_(0), disposer(nullptr) {} - inline Array(decltype(nullptr)): ptr(nullptr), size_(0), disposer(nullptr) {} - inline Array(Array&& other) noexcept - : ptr(other.ptr), size_(other.size_), disposer(other.disposer) { - other.ptr = nullptr; - other.size_ = 0; - } - inline Array(Array>&& other) noexcept - : ptr(other.ptr), size_(other.size_), disposer(other.disposer) { - other.ptr = nullptr; - other.size_ = 0; - } - inline Array(T* firstElement, size_t size, const ArrayDisposer& disposer) - : ptr(firstElement), size_(size), disposer(&disposer) {} - - KJ_DISALLOW_COPY(Array); - inline ~Array() noexcept { dispose(); } - - inline operator ArrayPtr() { - return ArrayPtr(ptr, size_); - } - inline operator ArrayPtr() const { - return ArrayPtr(ptr, size_); - } - inline ArrayPtr asPtr() { - return ArrayPtr(ptr, size_); - } - inline ArrayPtr asPtr() const { - return ArrayPtr(ptr, size_); - } - - inline size_t size() const { return size_; } - inline T& operator[](size_t index) const { - KJ_IREQUIRE(index < size_, "Out-of-bounds Array access."); - return ptr[index]; - } - - inline const T* begin() const { return ptr; } - inline const T* end() const { return ptr + size_; } - inline const T& front() const { return *ptr; } - inline const T& back() const { return *(ptr + size_ - 1); } - inline T* begin() { return ptr; } - inline T* end() { return ptr + size_; } - inline T& front() { return *ptr; } - inline T& back() { return *(ptr + size_ - 1); } - - inline ArrayPtr slice(size_t start, size_t end) { - KJ_IREQUIRE(start <= end && end <= size_, "Out-of-bounds Array::slice()."); - return ArrayPtr(ptr + start, end - start); - } - inline ArrayPtr slice(size_t start, size_t end) const { - KJ_IREQUIRE(start <= end && end <= size_, "Out-of-bounds Array::slice()."); - return ArrayPtr(ptr + start, end - start); - } - - inline ArrayPtr asBytes() const { return asPtr().asBytes(); } - inline ArrayPtr> asBytes() { return asPtr().asBytes(); } - inline ArrayPtr asChars() const { return asPtr().asChars(); } - inline ArrayPtr> asChars() { return asPtr().asChars(); } - - inline Array> releaseAsBytes() { - // Like asBytes() but transfers ownership. - static_assert(sizeof(T) == sizeof(byte), - "releaseAsBytes() only possible on arrays with byte-size elements (e.g. chars)."); - Array> result( - reinterpret_cast*>(ptr), size_, *disposer); - ptr = nullptr; - size_ = 0; - return result; - } - inline Array> releaseAsChars() { - // Like asChars() but transfers ownership. - static_assert(sizeof(T) == sizeof(PropagateConst), - "releaseAsChars() only possible on arrays with char-size elements (e.g. bytes)."); - Array> result( - reinterpret_cast*>(ptr), size_, *disposer); - ptr = nullptr; - size_ = 0; - return result; - } - - inline bool operator==(decltype(nullptr)) const { return size_ == 0; } - inline bool operator!=(decltype(nullptr)) const { return size_ != 0; } - - inline Array& operator=(decltype(nullptr)) { - dispose(); - return *this; - } - - inline Array& operator=(Array&& other) { - dispose(); - ptr = other.ptr; - size_ = other.size_; - disposer = other.disposer; - other.ptr = nullptr; - other.size_ = 0; - return *this; - } - -private: - T* ptr; - size_t size_; - const ArrayDisposer* disposer; - - inline void dispose() { - // Make sure that if an exception is thrown, we are left with a null ptr, so we won't possibly - // dispose again. - T* ptrCopy = ptr; - size_t sizeCopy = size_; - if (ptrCopy != nullptr) { - ptr = nullptr; - size_ = 0; - disposer->dispose(ptrCopy, sizeCopy, sizeCopy); - } - } - - template - friend class Array; -}; - -static_assert(!canMemcpy>(), "canMemcpy<>() is broken"); - -namespace _ { // private - -class HeapArrayDisposer final: public ArrayDisposer { -public: - template - static T* allocate(size_t count); - template - static T* allocateUninitialized(size_t count); - - static const HeapArrayDisposer instance; - -private: - static void* allocateImpl(size_t elementSize, size_t elementCount, size_t capacity, - void (*constructElement)(void*), void (*destroyElement)(void*)); - // Allocates and constructs the array. Both function pointers are null if the constructor is - // trivial, otherwise destroyElement is null if the constructor doesn't throw. - - virtual void disposeImpl(void* firstElement, size_t elementSize, size_t elementCount, - size_t capacity, void (*destroyElement)(void*)) const override; - - template - struct Allocate_; -}; - -} // namespace _ (private) - -template -inline Array heapArray(size_t size) { - // Much like `heap()` from memory.h, allocates a new array on the heap. - - return Array(_::HeapArrayDisposer::allocate(size), size, - _::HeapArrayDisposer::instance); -} - -template Array heapArray(const T* content, size_t size); -template Array heapArray(ArrayPtr content); -template Array heapArray(ArrayPtr content); -template Array heapArray(Iterator begin, Iterator end); -template Array heapArray(std::initializer_list init); -// Allocate a heap array containing a copy of the given content. - -template -Array heapArrayFromIterable(Container&& a) { return heapArray(a.begin(), a.end()); } -template -Array heapArrayFromIterable(Array&& a) { return mv(a); } - -// ======================================================================================= -// ArrayBuilder - -template -class ArrayBuilder { - // Class which lets you build an Array specifying the exact constructor arguments for each - // element, rather than starting by default-constructing them. - -public: - ArrayBuilder(): ptr(nullptr), pos(nullptr), endPtr(nullptr) {} - ArrayBuilder(decltype(nullptr)): ptr(nullptr), pos(nullptr), endPtr(nullptr) {} - explicit ArrayBuilder(RemoveConst* firstElement, size_t capacity, - const ArrayDisposer& disposer) - : ptr(firstElement), pos(firstElement), endPtr(firstElement + capacity), - disposer(&disposer) {} - ArrayBuilder(ArrayBuilder&& other) - : ptr(other.ptr), pos(other.pos), endPtr(other.endPtr), disposer(other.disposer) { - other.ptr = nullptr; - other.pos = nullptr; - other.endPtr = nullptr; - } - KJ_DISALLOW_COPY(ArrayBuilder); - inline ~ArrayBuilder() noexcept(false) { dispose(); } - - inline operator ArrayPtr() { - return arrayPtr(ptr, pos); - } - inline operator ArrayPtr() const { - return arrayPtr(ptr, pos); - } - inline ArrayPtr asPtr() { - return arrayPtr(ptr, pos); - } - inline ArrayPtr asPtr() const { - return arrayPtr(ptr, pos); - } - - inline size_t size() const { return pos - ptr; } - inline size_t capacity() const { return endPtr - ptr; } - inline T& operator[](size_t index) const { - KJ_IREQUIRE(index < implicitCast(pos - ptr), "Out-of-bounds Array access."); - return ptr[index]; - } - - inline const T* begin() const { return ptr; } - inline const T* end() const { return pos; } - inline const T& front() const { return *ptr; } - inline const T& back() const { return *(pos - 1); } - inline T* begin() { return ptr; } - inline T* end() { return pos; } - inline T& front() { return *ptr; } - inline T& back() { return *(pos - 1); } - - ArrayBuilder& operator=(ArrayBuilder&& other) { - dispose(); - ptr = other.ptr; - pos = other.pos; - endPtr = other.endPtr; - disposer = other.disposer; - other.ptr = nullptr; - other.pos = nullptr; - other.endPtr = nullptr; - return *this; - } - ArrayBuilder& operator=(decltype(nullptr)) { - dispose(); - return *this; - } - - template - T& add(Params&&... params) { - KJ_IREQUIRE(pos < endPtr, "Added too many elements to ArrayBuilder."); - ctor(*pos, kj::fwd(params)...); - return *pos++; - } - - template - void addAll(Container&& container) { - addAll()>( - container.begin(), container.end()); - } - - template - void addAll(Iterator start, Iterator end); - - void removeLast() { - KJ_IREQUIRE(pos > ptr, "No elements present to remove."); - kj::dtor(*--pos); - } - - void truncate(size_t size) { - KJ_IREQUIRE(size <= this->size(), "can't use truncate() to expand"); - - T* target = ptr + size; - if (__has_trivial_destructor(T)) { - pos = target; - } else { - while (pos > target) { - kj::dtor(*--pos); - } - } - } - - void resize(size_t size) { - KJ_IREQUIRE(size <= capacity(), "can't resize past capacity"); - - T* target = ptr + size; - if (target > pos) { - // expand - if (__has_trivial_constructor(T)) { - pos = target; - } else { - while (pos < target) { - kj::ctor(*pos++); - } - } - } else { - // truncate - if (__has_trivial_destructor(T)) { - pos = target; - } else { - while (pos > target) { - kj::dtor(*--pos); - } - } - } - } - - Array finish() { - // We could safely remove this check if we assume that the disposer implementation doesn't - // need to know the original capacity, as is thes case with HeapArrayDisposer since it uses - // operator new() or if we created a custom disposer for ArrayBuilder which stores the capacity - // in a prefix. But that would make it hard to write cleverer heap allocators, and anyway this - // check might catch bugs. Probably people should use Vector if they want to build arrays - // without knowing the final size in advance. - KJ_IREQUIRE(pos == endPtr, "ArrayBuilder::finish() called prematurely."); - Array result(reinterpret_cast(ptr), pos - ptr, *disposer); - ptr = nullptr; - pos = nullptr; - endPtr = nullptr; - return result; - } - - inline bool isFull() const { - return pos == endPtr; - } - -private: - T* ptr; - RemoveConst* pos; - T* endPtr; - const ArrayDisposer* disposer; - - inline void dispose() { - // Make sure that if an exception is thrown, we are left with a null ptr, so we won't possibly - // dispose again. - T* ptrCopy = ptr; - T* posCopy = pos; - T* endCopy = endPtr; - if (ptrCopy != nullptr) { - ptr = nullptr; - pos = nullptr; - endPtr = nullptr; - disposer->dispose(ptrCopy, posCopy - ptrCopy, endCopy - ptrCopy); - } - } -}; - -template -inline ArrayBuilder heapArrayBuilder(size_t size) { - // Like `heapArray()` but does not default-construct the elements. You must construct them - // manually by calling `add()`. - - return ArrayBuilder(_::HeapArrayDisposer::allocateUninitialized>(size), - size, _::HeapArrayDisposer::instance); -} - -// ======================================================================================= -// Inline Arrays - -template -class FixedArray { - // A fixed-width array whose storage is allocated inline rather than on the heap. - -public: - inline size_t size() const { return fixedSize; } - inline T* begin() { return content; } - inline T* end() { return content + fixedSize; } - inline const T* begin() const { return content; } - inline const T* end() const { return content + fixedSize; } - - inline operator ArrayPtr() { - return arrayPtr(content, fixedSize); - } - inline operator ArrayPtr() const { - return arrayPtr(content, fixedSize); - } - - inline T& operator[](size_t index) { return content[index]; } - inline const T& operator[](size_t index) const { return content[index]; } - -private: - T content[fixedSize]; -}; - -template -class CappedArray { - // Like `FixedArray` but can be dynamically resized as long as the size does not exceed the limit - // specified by the template parameter. - // - // TODO(someday): Don't construct elements past currentSize? - -public: - inline KJ_CONSTEXPR() CappedArray(): currentSize(fixedSize) {} - inline explicit constexpr CappedArray(size_t s): currentSize(s) {} - - inline size_t size() const { return currentSize; } - inline void setSize(size_t s) { KJ_IREQUIRE(s <= fixedSize); currentSize = s; } - inline T* begin() { return content; } - inline T* end() { return content + currentSize; } - inline const T* begin() const { return content; } - inline const T* end() const { return content + currentSize; } - - inline operator ArrayPtr() { - return arrayPtr(content, currentSize); - } - inline operator ArrayPtr() const { - return arrayPtr(content, currentSize); - } - - inline T& operator[](size_t index) { return content[index]; } - inline const T& operator[](size_t index) const { return content[index]; } - -private: - size_t currentSize; - T content[fixedSize]; -}; - -// ======================================================================================= -// KJ_MAP - -#define KJ_MAP(elementName, array) \ - ::kj::_::Mapper(array) * \ - [&](typename ::kj::_::Mapper::Element elementName) -// Applies some function to every element of an array, returning an Array of the results, with -// nice syntax. Example: -// -// StringPtr foo = "abcd"; -// Array bar = KJ_MAP(c, foo) -> char { return c + 1; }; -// KJ_ASSERT(str(bar) == "bcde"); - -namespace _ { // private - -template -struct Mapper { - T array; - Mapper(T&& array): array(kj::fwd(array)) {} - template - auto operator*(Func&& func) -> Array { - auto builder = heapArrayBuilder(array.size()); - for (auto iter = array.begin(); iter != array.end(); ++iter) { - builder.add(func(*iter)); - } - return builder.finish(); - } - typedef decltype(*kj::instance().begin()) Element; -}; - -template -struct Mapper { - T* array; - Mapper(T* array): array(array) {} - template - auto operator*(Func&& func) -> Array { - auto builder = heapArrayBuilder(s); - for (size_t i = 0; i < s; i++) { - builder.add(func(array[i])); - } - return builder.finish(); - } - typedef decltype(*array)& Element; -}; - -} // namespace _ (private) - -// ======================================================================================= -// Inline implementation details - -template -struct ArrayDisposer::Dispose_ { - static void dispose(T* firstElement, size_t elementCount, size_t capacity, - const ArrayDisposer& disposer) { - disposer.disposeImpl(const_cast*>(firstElement), - sizeof(T), elementCount, capacity, nullptr); - } -}; -template -struct ArrayDisposer::Dispose_ { - static void destruct(void* ptr) { - kj::dtor(*reinterpret_cast(ptr)); - } - - static void dispose(T* firstElement, size_t elementCount, size_t capacity, - const ArrayDisposer& disposer) { - disposer.disposeImpl(firstElement, sizeof(T), elementCount, capacity, &destruct); - } -}; - -template -void ArrayDisposer::dispose(T* firstElement, size_t elementCount, size_t capacity) const { - Dispose_::dispose(firstElement, elementCount, capacity, *this); -} - -namespace _ { // private - -template -struct HeapArrayDisposer::Allocate_ { - static T* allocate(size_t elementCount, size_t capacity) { - return reinterpret_cast(allocateImpl( - sizeof(T), elementCount, capacity, nullptr, nullptr)); - } -}; -template -struct HeapArrayDisposer::Allocate_ { - static void construct(void* ptr) { - kj::ctor(*reinterpret_cast(ptr)); - } - static T* allocate(size_t elementCount, size_t capacity) { - return reinterpret_cast(allocateImpl( - sizeof(T), elementCount, capacity, &construct, nullptr)); - } -}; -template -struct HeapArrayDisposer::Allocate_ { - static void construct(void* ptr) { - kj::ctor(*reinterpret_cast(ptr)); - } - static void destruct(void* ptr) { - kj::dtor(*reinterpret_cast(ptr)); - } - static T* allocate(size_t elementCount, size_t capacity) { - return reinterpret_cast(allocateImpl( - sizeof(T), elementCount, capacity, &construct, &destruct)); - } -}; - -template -T* HeapArrayDisposer::allocate(size_t count) { - return Allocate_::allocate(count, count); -} - -template -T* HeapArrayDisposer::allocateUninitialized(size_t count) { - return Allocate_::allocate(0, count); -} - -template ()> -struct CopyConstructArray_; - -template -struct CopyConstructArray_ { - static inline T* apply(T* __restrict__ pos, T* start, T* end) { - memcpy(pos, start, reinterpret_cast(end) - reinterpret_cast(start)); - return pos + (end - start); - } -}; - -template -struct CopyConstructArray_ { - static inline T* apply(T* __restrict__ pos, const T* start, const T* end) { - memcpy(pos, start, reinterpret_cast(end) - reinterpret_cast(start)); - return pos + (end - start); - } -}; - -template -struct CopyConstructArray_ { - static inline T* apply(T* __restrict__ pos, Iterator start, Iterator end) { - // Since both the copy constructor and assignment operator are trivial, we know that assignment - // is equivalent to copy-constructing. So we can make this case somewhat easier for the - // compiler to optimize. - while (start != end) { - *pos++ = *start++; - } - return pos; - } -}; - -template -struct CopyConstructArray_ { - struct ExceptionGuard { - T* start; - T* pos; - inline explicit ExceptionGuard(T* pos): start(pos), pos(pos) {} - ~ExceptionGuard() noexcept(false) { - while (pos > start) { - dtor(*--pos); - } - } - }; - - static T* apply(T* __restrict__ pos, Iterator start, Iterator end) { - // Verify that T can be *implicitly* constructed from the source values. - if (false) implicitCast(*start); - - if (noexcept(T(*start))) { - while (start != end) { - ctor(*pos++, *start++); - } - return pos; - } else { - // Crap. This is complicated. - ExceptionGuard guard(pos); - while (start != end) { - ctor(*guard.pos, *start++); - ++guard.pos; - } - guard.start = guard.pos; - return guard.pos; - } - } -}; - -template -struct CopyConstructArray_ { - // Actually move-construct. - - struct ExceptionGuard { - T* start; - T* pos; - inline explicit ExceptionGuard(T* pos): start(pos), pos(pos) {} - ~ExceptionGuard() noexcept(false) { - while (pos > start) { - dtor(*--pos); - } - } - }; - - static T* apply(T* __restrict__ pos, Iterator start, Iterator end) { - // Verify that T can be *implicitly* constructed from the source values. - if (false) implicitCast(kj::mv(*start)); - - if (noexcept(T(kj::mv(*start)))) { - while (start != end) { - ctor(*pos++, kj::mv(*start++)); - } - return pos; - } else { - // Crap. This is complicated. - ExceptionGuard guard(pos); - while (start != end) { - ctor(*guard.pos, kj::mv(*start++)); - ++guard.pos; - } - guard.start = guard.pos; - return guard.pos; - } - } -}; - -} // namespace _ (private) - -template -template -void ArrayBuilder::addAll(Iterator start, Iterator end) { - pos = _::CopyConstructArray_, Decay, move>::apply(pos, start, end); -} - -template -Array heapArray(const T* content, size_t size) { - ArrayBuilder builder = heapArrayBuilder(size); - builder.addAll(content, content + size); - return builder.finish(); -} - -template -Array heapArray(T* content, size_t size) { - ArrayBuilder builder = heapArrayBuilder(size); - builder.addAll(content, content + size); - return builder.finish(); -} - -template -Array heapArray(ArrayPtr content) { - ArrayBuilder builder = heapArrayBuilder(content.size()); - builder.addAll(content); - return builder.finish(); -} - -template -Array heapArray(ArrayPtr content) { - ArrayBuilder builder = heapArrayBuilder(content.size()); - builder.addAll(content); - return builder.finish(); -} - -template Array -heapArray(Iterator begin, Iterator end) { - ArrayBuilder builder = heapArrayBuilder(end - begin); - builder.addAll(begin, end); - return builder.finish(); -} - -template -inline Array heapArray(std::initializer_list init) { - return heapArray(init.begin(), init.end()); -} - -} // namespace kj - -#endif // KJ_ARRAY_H_ diff --git a/phonelibs/capnp-cpp/include/kj/async-inl.h b/phonelibs/capnp-cpp/include/kj/async-inl.h deleted file mode 100644 index f11e4fcd5b..0000000000 --- a/phonelibs/capnp-cpp/include/kj/async-inl.h +++ /dev/null @@ -1,1112 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// This file contains extended inline implementation details that are required along with async.h. -// We move this all into a separate file to make async.h more readable. -// -// Non-inline declarations here are defined in async.c++. - -#ifndef KJ_ASYNC_H_ -#error "Do not include this directly; include kj/async.h." -#include "async.h" // help IDE parse this file -#endif - -#ifndef KJ_ASYNC_INL_H_ -#define KJ_ASYNC_INL_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -namespace kj { -namespace _ { // private - -template -class ExceptionOr; - -class ExceptionOrValue { -public: - ExceptionOrValue(bool, Exception&& exception): exception(kj::mv(exception)) {} - KJ_DISALLOW_COPY(ExceptionOrValue); - - void addException(Exception&& exception) { - if (this->exception == nullptr) { - this->exception = kj::mv(exception); - } - } - - template - ExceptionOr& as() { return *static_cast*>(this); } - template - const ExceptionOr& as() const { return *static_cast*>(this); } - - Maybe exception; - -protected: - // Allow subclasses to have move constructor / assignment. - ExceptionOrValue() = default; - ExceptionOrValue(ExceptionOrValue&& other) = default; - ExceptionOrValue& operator=(ExceptionOrValue&& other) = default; -}; - -template -class ExceptionOr: public ExceptionOrValue { -public: - ExceptionOr() = default; - ExceptionOr(T&& value): value(kj::mv(value)) {} - ExceptionOr(bool, Exception&& exception): ExceptionOrValue(false, kj::mv(exception)) {} - ExceptionOr(ExceptionOr&&) = default; - ExceptionOr& operator=(ExceptionOr&&) = default; - - Maybe value; -}; - -class Event { - // An event waiting to be executed. Not for direct use by applications -- promises use this - // internally. - -public: - Event(); - ~Event() noexcept(false); - KJ_DISALLOW_COPY(Event); - - void armDepthFirst(); - // Enqueue this event so that `fire()` will be called from the event loop soon. - // - // Events scheduled in this way are executed in depth-first order: if an event callback arms - // more events, those events are placed at the front of the queue (in the order in which they - // were armed), so that they run immediately after the first event's callback returns. - // - // Depth-first event scheduling is appropriate for events that represent simple continuations - // of a previous event that should be globbed together for performance. Depth-first scheduling - // can lead to starvation, so any long-running task must occasionally yield with - // `armBreadthFirst()`. (Promise::then() uses depth-first whereas evalLater() uses - // breadth-first.) - // - // To use breadth-first scheduling instead, use `armBreadthFirst()`. - - void armBreadthFirst(); - // Like `armDepthFirst()` except that the event is placed at the end of the queue. - - kj::String trace(); - // Dump debug info about this event. - - virtual _::PromiseNode* getInnerForTrace(); - // If this event wraps a PromiseNode, get that node. Used for debug tracing. - // Default implementation returns nullptr. - -protected: - virtual Maybe> fire() = 0; - // Fire the event. Possibly returns a pointer to itself, which will be discarded by the - // caller. This is the only way that an event can delete itself as a result of firing, as - // doing so from within fire() will throw an exception. - -private: - friend class kj::EventLoop; - EventLoop& loop; - Event* next; - Event** prev; - bool firing = false; -}; - -class PromiseNode { - // A Promise contains a chain of PromiseNodes tracking the pending transformations. - // - // To reduce generated code bloat, PromiseNode is not a template. Instead, it makes very hacky - // use of pointers to ExceptionOrValue which actually point to ExceptionOr, but are only - // so down-cast in the few places that really need to be templated. Luckily this is all - // internal implementation details. - -public: - virtual void onReady(Event& event) noexcept = 0; - // Arms the given event when ready. - - virtual void setSelfPointer(Own* selfPtr) noexcept; - // Tells the node that `selfPtr` is the pointer that owns this node, and will continue to own - // this node until it is destroyed or setSelfPointer() is called again. ChainPromiseNode uses - // this to shorten redundant chains. The default implementation does nothing; only - // ChainPromiseNode should implement this. - - virtual void get(ExceptionOrValue& output) noexcept = 0; - // Get the result. `output` points to an ExceptionOr into which the result will be written. - // Can only be called once, and only after the node is ready. Must be called directly from the - // event loop, with no application code on the stack. - - virtual PromiseNode* getInnerForTrace(); - // If this node wraps some other PromiseNode, get the wrapped node. Used for debug tracing. - // Default implementation returns nullptr. - -protected: - class OnReadyEvent { - // Helper class for implementing onReady(). - - public: - void init(Event& newEvent); - // Returns true if arm() was already called. - - void arm(); - // Arms the event if init() has already been called and makes future calls to init() return - // true. - - private: - Event* event = nullptr; - }; -}; - -// ------------------------------------------------------------------- - -class ImmediatePromiseNodeBase: public PromiseNode { -public: - ImmediatePromiseNodeBase(); - ~ImmediatePromiseNodeBase() noexcept(false); - - void onReady(Event& event) noexcept override; -}; - -template -class ImmediatePromiseNode final: public ImmediatePromiseNodeBase { - // A promise that has already been resolved to an immediate value or exception. - -public: - ImmediatePromiseNode(ExceptionOr&& result): result(kj::mv(result)) {} - - void get(ExceptionOrValue& output) noexcept override { - output.as() = kj::mv(result); - } - -private: - ExceptionOr result; -}; - -class ImmediateBrokenPromiseNode final: public ImmediatePromiseNodeBase { -public: - ImmediateBrokenPromiseNode(Exception&& exception); - - void get(ExceptionOrValue& output) noexcept override; - -private: - Exception exception; -}; - -// ------------------------------------------------------------------- - -class AttachmentPromiseNodeBase: public PromiseNode { -public: - AttachmentPromiseNodeBase(Own&& dependency); - - void onReady(Event& event) noexcept override; - void get(ExceptionOrValue& output) noexcept override; - PromiseNode* getInnerForTrace() override; - -private: - Own dependency; - - void dropDependency(); - - template - friend class AttachmentPromiseNode; -}; - -template -class AttachmentPromiseNode final: public AttachmentPromiseNodeBase { - // A PromiseNode that holds on to some object (usually, an Own, but could be any movable - // object) until the promise resolves. - -public: - AttachmentPromiseNode(Own&& dependency, Attachment&& attachment) - : AttachmentPromiseNodeBase(kj::mv(dependency)), - attachment(kj::mv(attachment)) {} - - ~AttachmentPromiseNode() noexcept(false) { - // We need to make sure the dependency is deleted before we delete the attachment because the - // dependency may be using the attachment. - dropDependency(); - } - -private: - Attachment attachment; -}; - -// ------------------------------------------------------------------- - -class PtmfHelper { - // This class is a private helper for GetFunctorStartAddress. The class represents the internal - // representation of a pointer-to-member-function. - - template - friend struct GetFunctorStartAddress; - -#if __GNUG__ - - void* ptr; - ptrdiff_t adj; - // Layout of a pointer-to-member-function used by GCC and compatible compilers. - - void* apply(void* obj) { -#if defined(__arm__) || defined(__mips__) || defined(__aarch64__) - if (adj & 1) { - ptrdiff_t voff = (ptrdiff_t)ptr; -#else - ptrdiff_t voff = (ptrdiff_t)ptr; - if (voff & 1) { - voff &= ~1; -#endif - return *(void**)(*(char**)obj + voff); - } else { - return ptr; - } - } - -#define BODY \ - PtmfHelper result; \ - static_assert(sizeof(p) == sizeof(result), "unknown ptmf layout"); \ - memcpy(&result, &p, sizeof(result)); \ - return result - -#else // __GNUG__ - - void* apply(void* obj) { return nullptr; } - // TODO(port): PTMF instruction address extraction - -#define BODY return PtmfHelper{} - -#endif // __GNUG__, else - - template - static PtmfHelper from(F p) { BODY; } - // Create a PtmfHelper from some arbitrary pointer-to-member-function which is not - // overloaded nor a template. In this case the compiler is able to deduce the full function - // signature directly given the name since there is only one function with that name. - - template - static PtmfHelper from(R (C::*p)(NoInfer

...)) { BODY; } - template - static PtmfHelper from(R (C::*p)(NoInfer

...) const) { BODY; } - // Create a PtmfHelper from some poniter-to-member-function which is a template. In this case - // the function must match exactly the containing type C, return type R, and parameter types P... - // GetFunctorStartAddress normally specifies exactly the correct C and R, but can only make a - // guess at P. Luckily, if the function parameters are template parameters then it's not - // necessary to be precise about P. -#undef BODY -}; - -template -struct GetFunctorStartAddress { - // Given a functor (any object defining operator()), return the start address of the function, - // suitable for passing to addr2line to obtain a source file/line for debugging purposes. - // - // This turns out to be incredibly hard to implement in the presence of overloaded or templated - // functors. Therefore, we impose these specific restrictions, specific to our use case: - // - Overloading is not allowed, but templating is. (Generally we only intend to support lambdas - // anyway.) - // - The template parameters to GetFunctorStartAddress specify a hint as to the expected - // parameter types. If the functor is templated, its parameters must match exactly these types. - // (If it's not templated, ParamTypes are ignored.) - - template - static void* apply(Func&& func) { - typedef decltype(func(instance()...)) ReturnType; - return PtmfHelper::from, ParamTypes...>( - &Decay::operator()).apply(&func); - } -}; - -template <> -struct GetFunctorStartAddress: public GetFunctorStartAddress<> {}; -// Hack for TransformPromiseNode use case: an input type of `Void` indicates that the function -// actually has no parameters. - -class TransformPromiseNodeBase: public PromiseNode { -public: - TransformPromiseNodeBase(Own&& dependency, void* continuationTracePtr); - - void onReady(Event& event) noexcept override; - void get(ExceptionOrValue& output) noexcept override; - PromiseNode* getInnerForTrace() override; - -private: - Own dependency; - void* continuationTracePtr; - - void dropDependency(); - void getDepResult(ExceptionOrValue& output); - - virtual void getImpl(ExceptionOrValue& output) = 0; - - template - friend class TransformPromiseNode; -}; - -template -class TransformPromiseNode final: public TransformPromiseNodeBase { - // A PromiseNode that transforms the result of another PromiseNode through an application-provided - // function (implements `then()`). - -public: - TransformPromiseNode(Own&& dependency, Func&& func, ErrorFunc&& errorHandler) - : TransformPromiseNodeBase(kj::mv(dependency), - GetFunctorStartAddress::apply(func)), - func(kj::fwd(func)), errorHandler(kj::fwd(errorHandler)) {} - - ~TransformPromiseNode() noexcept(false) { - // We need to make sure the dependency is deleted before we delete the continuations because it - // is a common pattern for the continuations to hold ownership of objects that might be in-use - // by the dependency. - dropDependency(); - } - -private: - Func func; - ErrorFunc errorHandler; - - void getImpl(ExceptionOrValue& output) override { - ExceptionOr depResult; - getDepResult(depResult); - KJ_IF_MAYBE(depException, depResult.exception) { - output.as() = handle( - MaybeVoidCaller>>::apply( - errorHandler, kj::mv(*depException))); - } else KJ_IF_MAYBE(depValue, depResult.value) { - output.as() = handle(MaybeVoidCaller::apply(func, kj::mv(*depValue))); - } - } - - ExceptionOr handle(T&& value) { - return kj::mv(value); - } - ExceptionOr handle(PropagateException::Bottom&& value) { - return ExceptionOr(false, value.asException()); - } -}; - -// ------------------------------------------------------------------- - -class ForkHubBase; - -class ForkBranchBase: public PromiseNode { -public: - ForkBranchBase(Own&& hub); - ~ForkBranchBase() noexcept(false); - - void hubReady() noexcept; - // Called by the hub to indicate that it is ready. - - // implements PromiseNode ------------------------------------------ - void onReady(Event& event) noexcept override; - PromiseNode* getInnerForTrace() override; - -protected: - inline ExceptionOrValue& getHubResultRef(); - - void releaseHub(ExceptionOrValue& output); - // Release the hub. If an exception is thrown, add it to `output`. - -private: - OnReadyEvent onReadyEvent; - - Own hub; - ForkBranchBase* next = nullptr; - ForkBranchBase** prevPtr = nullptr; - - friend class ForkHubBase; -}; - -template T copyOrAddRef(T& t) { return t; } -template Own copyOrAddRef(Own& t) { return t->addRef(); } - -template -class ForkBranch final: public ForkBranchBase { - // A PromiseNode that implements one branch of a fork -- i.e. one of the branches that receives - // a const reference. - -public: - ForkBranch(Own&& hub): ForkBranchBase(kj::mv(hub)) {} - - void get(ExceptionOrValue& output) noexcept override { - ExceptionOr& hubResult = getHubResultRef().template as(); - KJ_IF_MAYBE(value, hubResult.value) { - output.as().value = copyOrAddRef(*value); - } else { - output.as().value = nullptr; - } - output.exception = hubResult.exception; - releaseHub(output); - } -}; - -template -class SplitBranch final: public ForkBranchBase { - // A PromiseNode that implements one branch of a fork -- i.e. one of the branches that receives - // a const reference. - -public: - SplitBranch(Own&& hub): ForkBranchBase(kj::mv(hub)) {} - - typedef kj::Decay(kj::instance()))> Element; - - void get(ExceptionOrValue& output) noexcept override { - ExceptionOr& hubResult = getHubResultRef().template as(); - KJ_IF_MAYBE(value, hubResult.value) { - output.as().value = kj::mv(kj::get(*value)); - } else { - output.as().value = nullptr; - } - output.exception = hubResult.exception; - releaseHub(output); - } -}; - -// ------------------------------------------------------------------- - -class ForkHubBase: public Refcounted, protected Event { -public: - ForkHubBase(Own&& inner, ExceptionOrValue& resultRef); - - inline ExceptionOrValue& getResultRef() { return resultRef; } - -private: - Own inner; - ExceptionOrValue& resultRef; - - ForkBranchBase* headBranch = nullptr; - ForkBranchBase** tailBranch = &headBranch; - // Tail becomes null once the inner promise is ready and all branches have been notified. - - Maybe> fire() override; - _::PromiseNode* getInnerForTrace() override; - - friend class ForkBranchBase; -}; - -template -class ForkHub final: public ForkHubBase { - // A PromiseNode that implements the hub of a fork. The first call to Promise::fork() replaces - // the promise's outer node with a ForkHub, and subsequent calls add branches to that hub (if - // possible). - -public: - ForkHub(Own&& inner): ForkHubBase(kj::mv(inner), result) {} - - Promise<_::UnfixVoid> addBranch() { - return Promise<_::UnfixVoid>(false, kj::heap>(addRef(*this))); - } - - _::SplitTuplePromise split() { - return splitImpl(MakeIndexes()>()); - } - -private: - ExceptionOr result; - - template - _::SplitTuplePromise splitImpl(Indexes) { - return kj::tuple(addSplit()...); - } - - template - Promise::Element>> addSplit() { - return Promise::Element>>( - false, maybeChain(kj::heap>(addRef(*this)), - implicitCast::Element*>(nullptr))); - } -}; - -inline ExceptionOrValue& ForkBranchBase::getHubResultRef() { - return hub->getResultRef(); -} - -// ------------------------------------------------------------------- - -class ChainPromiseNode final: public PromiseNode, public Event { - // Promise node which reduces Promise> to Promise. - // - // `Event` is only a public base class because otherwise we can't cast Own to - // Own. Ugh, templates and private... - -public: - explicit ChainPromiseNode(Own inner); - ~ChainPromiseNode() noexcept(false); - - void onReady(Event& event) noexcept override; - void setSelfPointer(Own* selfPtr) noexcept override; - void get(ExceptionOrValue& output) noexcept override; - PromiseNode* getInnerForTrace() override; - -private: - enum State { - STEP1, - STEP2 - }; - - State state; - - Own inner; - // In STEP1, a PromiseNode for a Promise. - // In STEP2, a PromiseNode for a T. - - Event* onReadyEvent = nullptr; - Own* selfPtr = nullptr; - - Maybe> fire() override; -}; - -template -Own maybeChain(Own&& node, Promise*) { - return heap(kj::mv(node)); -} - -template -Own&& maybeChain(Own&& node, T*) { - return kj::mv(node); -} - -// ------------------------------------------------------------------- - -class ExclusiveJoinPromiseNode final: public PromiseNode { -public: - ExclusiveJoinPromiseNode(Own left, Own right); - ~ExclusiveJoinPromiseNode() noexcept(false); - - void onReady(Event& event) noexcept override; - void get(ExceptionOrValue& output) noexcept override; - PromiseNode* getInnerForTrace() override; - -private: - class Branch: public Event { - public: - Branch(ExclusiveJoinPromiseNode& joinNode, Own dependency); - ~Branch() noexcept(false); - - bool get(ExceptionOrValue& output); - // Returns true if this is the side that finished. - - Maybe> fire() override; - _::PromiseNode* getInnerForTrace() override; - - private: - ExclusiveJoinPromiseNode& joinNode; - Own dependency; - }; - - Branch left; - Branch right; - OnReadyEvent onReadyEvent; -}; - -// ------------------------------------------------------------------- - -class ArrayJoinPromiseNodeBase: public PromiseNode { -public: - ArrayJoinPromiseNodeBase(Array> promises, - ExceptionOrValue* resultParts, size_t partSize); - ~ArrayJoinPromiseNodeBase() noexcept(false); - - void onReady(Event& event) noexcept override final; - void get(ExceptionOrValue& output) noexcept override final; - PromiseNode* getInnerForTrace() override final; - -protected: - virtual void getNoError(ExceptionOrValue& output) noexcept = 0; - // Called to compile the result only in the case where there were no errors. - -private: - uint countLeft; - OnReadyEvent onReadyEvent; - - class Branch final: public Event { - public: - Branch(ArrayJoinPromiseNodeBase& joinNode, Own dependency, - ExceptionOrValue& output); - ~Branch() noexcept(false); - - Maybe> fire() override; - _::PromiseNode* getInnerForTrace() override; - - Maybe getPart(); - // Calls dependency->get(output). If there was an exception, return it. - - private: - ArrayJoinPromiseNodeBase& joinNode; - Own dependency; - ExceptionOrValue& output; - }; - - Array branches; -}; - -template -class ArrayJoinPromiseNode final: public ArrayJoinPromiseNodeBase { -public: - ArrayJoinPromiseNode(Array> promises, - Array> resultParts) - : ArrayJoinPromiseNodeBase(kj::mv(promises), resultParts.begin(), sizeof(ExceptionOr)), - resultParts(kj::mv(resultParts)) {} - -protected: - void getNoError(ExceptionOrValue& output) noexcept override { - auto builder = heapArrayBuilder(resultParts.size()); - for (auto& part: resultParts) { - KJ_IASSERT(part.value != nullptr, - "Bug in KJ promise framework: Promise result had neither value no exception."); - builder.add(kj::mv(*_::readMaybe(part.value))); - } - output.as>() = builder.finish(); - } - -private: - Array> resultParts; -}; - -template <> -class ArrayJoinPromiseNode final: public ArrayJoinPromiseNodeBase { -public: - ArrayJoinPromiseNode(Array> promises, - Array> resultParts); - ~ArrayJoinPromiseNode(); - -protected: - void getNoError(ExceptionOrValue& output) noexcept override; - -private: - Array> resultParts; -}; - -// ------------------------------------------------------------------- - -class EagerPromiseNodeBase: public PromiseNode, protected Event { - // A PromiseNode that eagerly evaluates its dependency even if its dependent does not eagerly - // evaluate it. - -public: - EagerPromiseNodeBase(Own&& dependency, ExceptionOrValue& resultRef); - - void onReady(Event& event) noexcept override; - PromiseNode* getInnerForTrace() override; - -private: - Own dependency; - OnReadyEvent onReadyEvent; - - ExceptionOrValue& resultRef; - - Maybe> fire() override; -}; - -template -class EagerPromiseNode final: public EagerPromiseNodeBase { -public: - EagerPromiseNode(Own&& dependency) - : EagerPromiseNodeBase(kj::mv(dependency), result) {} - - void get(ExceptionOrValue& output) noexcept override { - output.as() = kj::mv(result); - } - -private: - ExceptionOr result; -}; - -template -Own spark(Own&& node) { - // Forces evaluation of the given node to begin as soon as possible, even if no one is waiting - // on it. - return heap>(kj::mv(node)); -} - -// ------------------------------------------------------------------- - -class AdapterPromiseNodeBase: public PromiseNode { -public: - void onReady(Event& event) noexcept override; - -protected: - inline void setReady() { - onReadyEvent.arm(); - } - -private: - OnReadyEvent onReadyEvent; -}; - -template -class AdapterPromiseNode final: public AdapterPromiseNodeBase, - private PromiseFulfiller> { - // A PromiseNode that wraps a PromiseAdapter. - -public: - template - AdapterPromiseNode(Params&&... params) - : adapter(static_cast>&>(*this), kj::fwd(params)...) {} - - void get(ExceptionOrValue& output) noexcept override { - KJ_IREQUIRE(!isWaiting()); - output.as() = kj::mv(result); - } - -private: - ExceptionOr result; - bool waiting = true; - Adapter adapter; - - void fulfill(T&& value) override { - if (waiting) { - waiting = false; - result = ExceptionOr(kj::mv(value)); - setReady(); - } - } - - void reject(Exception&& exception) override { - if (waiting) { - waiting = false; - result = ExceptionOr(false, kj::mv(exception)); - setReady(); - } - } - - bool isWaiting() override { - return waiting; - } -}; - -} // namespace _ (private) - -// ======================================================================================= - -template -Promise::Promise(_::FixVoid value) - : PromiseBase(heap<_::ImmediatePromiseNode<_::FixVoid>>(kj::mv(value))) {} - -template -Promise::Promise(kj::Exception&& exception) - : PromiseBase(heap<_::ImmediateBrokenPromiseNode>(kj::mv(exception))) {} - -template -template -PromiseForResult Promise::then(Func&& func, ErrorFunc&& errorHandler) { - typedef _::FixVoid<_::ReturnType> ResultT; - - Own<_::PromiseNode> intermediate = - heap<_::TransformPromiseNode, Func, ErrorFunc>>( - kj::mv(node), kj::fwd(func), kj::fwd(errorHandler)); - return PromiseForResult(false, - _::maybeChain(kj::mv(intermediate), implicitCast(nullptr))); -} - -namespace _ { // private - -template -struct IdentityFunc { - inline T operator()(T&& value) const { - return kj::mv(value); - } -}; -template -struct IdentityFunc> { - inline Promise operator()(T&& value) const { - return kj::mv(value); - } -}; -template <> -struct IdentityFunc { - inline void operator()() const {} -}; -template <> -struct IdentityFunc> { - Promise operator()() const; - // This can't be inline because it will make the translation unit depend on kj-async. Awkwardly, - // Cap'n Proto relies on being able to include this header without creating such a link-time - // dependency. -}; - -} // namespace _ (private) - -template -template -Promise Promise::catch_(ErrorFunc&& errorHandler) { - // then()'s ErrorFunc can only return a Promise if Func also returns a Promise. In this case, - // Func is being filled in automatically. We want to make sure ErrorFunc can return a Promise, - // but we don't want the extra overhead of promise chaining if ErrorFunc doesn't actually - // return a promise. So we make our Func return match ErrorFunc. - return then(_::IdentityFunc()))>(), - kj::fwd(errorHandler)); -} - -template -T Promise::wait(WaitScope& waitScope) { - _::ExceptionOr<_::FixVoid> result; - - waitImpl(kj::mv(node), result, waitScope); - - KJ_IF_MAYBE(value, result.value) { - KJ_IF_MAYBE(exception, result.exception) { - throwRecoverableException(kj::mv(*exception)); - } - return _::returnMaybeVoid(kj::mv(*value)); - } else KJ_IF_MAYBE(exception, result.exception) { - throwFatalException(kj::mv(*exception)); - } else { - // Result contained neither a value nor an exception? - KJ_UNREACHABLE; - } -} - -template <> -inline void Promise::wait(WaitScope& waitScope) { - // Override case to use throwRecoverableException(). - - _::ExceptionOr<_::Void> result; - - waitImpl(kj::mv(node), result, waitScope); - - if (result.value != nullptr) { - KJ_IF_MAYBE(exception, result.exception) { - throwRecoverableException(kj::mv(*exception)); - } - } else KJ_IF_MAYBE(exception, result.exception) { - throwRecoverableException(kj::mv(*exception)); - } else { - // Result contained neither a value nor an exception? - KJ_UNREACHABLE; - } -} - -template -ForkedPromise Promise::fork() { - return ForkedPromise(false, refcounted<_::ForkHub<_::FixVoid>>(kj::mv(node))); -} - -template -Promise ForkedPromise::addBranch() { - return hub->addBranch(); -} - -template -_::SplitTuplePromise Promise::split() { - return refcounted<_::ForkHub<_::FixVoid>>(kj::mv(node))->split(); -} - -template -Promise Promise::exclusiveJoin(Promise&& other) { - return Promise(false, heap<_::ExclusiveJoinPromiseNode>(kj::mv(node), kj::mv(other.node))); -} - -template -template -Promise Promise::attach(Attachments&&... attachments) { - return Promise(false, kj::heap<_::AttachmentPromiseNode>>( - kj::mv(node), kj::tuple(kj::fwd(attachments)...))); -} - -template -template -Promise Promise::eagerlyEvaluate(ErrorFunc&& errorHandler) { - // See catch_() for commentary. - return Promise(false, _::spark<_::FixVoid>(then( - _::IdentityFunc()))>(), - kj::fwd(errorHandler)).node)); -} - -template -Promise Promise::eagerlyEvaluate(decltype(nullptr)) { - return Promise(false, _::spark<_::FixVoid>(kj::mv(node))); -} - -template -kj::String Promise::trace() { - return PromiseBase::trace(); -} - -template -inline PromiseForResult evalLater(Func&& func) { - return _::yield().then(kj::fwd(func), _::PropagateException()); -} - -template -inline PromiseForResult evalNow(Func&& func) { - PromiseForResult result = nullptr; - KJ_IF_MAYBE(e, kj::runCatchingExceptions([&]() { - result = func(); - })) { - result = kj::mv(*e); - } - return result; -} - -template -template -void Promise::detach(ErrorFunc&& errorHandler) { - return _::detach(then([](T&&) {}, kj::fwd(errorHandler))); -} - -template <> -template -void Promise::detach(ErrorFunc&& errorHandler) { - return _::detach(then([]() {}, kj::fwd(errorHandler))); -} - -template -Promise> joinPromises(Array>&& promises) { - return Promise>(false, kj::heap<_::ArrayJoinPromiseNode>( - KJ_MAP(p, promises) { return kj::mv(p.node); }, - heapArray<_::ExceptionOr>(promises.size()))); -} - -// ======================================================================================= - -namespace _ { // private - -template -class WeakFulfiller final: public PromiseFulfiller, private kj::Disposer { - // A wrapper around PromiseFulfiller which can be detached. - // - // There are a couple non-trivialities here: - // - If the WeakFulfiller is discarded, we want the promise it fulfills to be implicitly - // rejected. - // - We cannot destroy the WeakFulfiller until the application has discarded it *and* it has been - // detached from the underlying fulfiller, because otherwise the later detach() call will go - // to a dangling pointer. Essentially, WeakFulfiller is reference counted, although the - // refcount never goes over 2 and we manually implement the refcounting because we need to do - // other special things when each side detaches anyway. To this end, WeakFulfiller is its own - // Disposer -- dispose() is called when the application discards its owned pointer to the - // fulfiller and detach() is called when the promise is destroyed. - -public: - KJ_DISALLOW_COPY(WeakFulfiller); - - static kj::Own make() { - WeakFulfiller* ptr = new WeakFulfiller; - return Own(ptr, *ptr); - } - - void fulfill(FixVoid&& value) override { - if (inner != nullptr) { - inner->fulfill(kj::mv(value)); - } - } - - void reject(Exception&& exception) override { - if (inner != nullptr) { - inner->reject(kj::mv(exception)); - } - } - - bool isWaiting() override { - return inner != nullptr && inner->isWaiting(); - } - - void attach(PromiseFulfiller& newInner) { - inner = &newInner; - } - - void detach(PromiseFulfiller& from) { - if (inner == nullptr) { - // Already disposed. - delete this; - } else { - KJ_IREQUIRE(inner == &from); - inner = nullptr; - } - } - -private: - mutable PromiseFulfiller* inner; - - WeakFulfiller(): inner(nullptr) {} - - void disposeImpl(void* pointer) const override { - // TODO(perf): Factor some of this out so it isn't regenerated for every fulfiller type? - - if (inner == nullptr) { - // Already detached. - delete this; - } else { - if (inner->isWaiting()) { - inner->reject(kj::Exception(kj::Exception::Type::FAILED, __FILE__, __LINE__, - kj::heapString("PromiseFulfiller was destroyed without fulfilling the promise."))); - } - inner = nullptr; - } - } -}; - -template -class PromiseAndFulfillerAdapter { -public: - PromiseAndFulfillerAdapter(PromiseFulfiller& fulfiller, - WeakFulfiller& wrapper) - : fulfiller(fulfiller), wrapper(wrapper) { - wrapper.attach(fulfiller); - } - - ~PromiseAndFulfillerAdapter() noexcept(false) { - wrapper.detach(fulfiller); - } - -private: - PromiseFulfiller& fulfiller; - WeakFulfiller& wrapper; -}; - -} // namespace _ (private) - -template -template -bool PromiseFulfiller::rejectIfThrows(Func&& func) { - KJ_IF_MAYBE(exception, kj::runCatchingExceptions(kj::mv(func))) { - reject(kj::mv(*exception)); - return false; - } else { - return true; - } -} - -template -bool PromiseFulfiller::rejectIfThrows(Func&& func) { - KJ_IF_MAYBE(exception, kj::runCatchingExceptions(kj::mv(func))) { - reject(kj::mv(*exception)); - return false; - } else { - return true; - } -} - -template -Promise newAdaptedPromise(Params&&... adapterConstructorParams) { - return Promise(false, heap<_::AdapterPromiseNode<_::FixVoid, Adapter>>( - kj::fwd(adapterConstructorParams)...)); -} - -template -PromiseFulfillerPair newPromiseAndFulfiller() { - auto wrapper = _::WeakFulfiller::make(); - - Own<_::PromiseNode> intermediate( - heap<_::AdapterPromiseNode<_::FixVoid, _::PromiseAndFulfillerAdapter>>(*wrapper)); - Promise<_::JoinPromises> promise(false, - _::maybeChain(kj::mv(intermediate), implicitCast(nullptr))); - - return PromiseFulfillerPair { kj::mv(promise), kj::mv(wrapper) }; -} - -} // namespace kj - -#endif // KJ_ASYNC_INL_H_ diff --git a/phonelibs/capnp-cpp/include/kj/async-io.h b/phonelibs/capnp-cpp/include/kj/async-io.h deleted file mode 100644 index 2804ed7289..0000000000 --- a/phonelibs/capnp-cpp/include/kj/async-io.h +++ /dev/null @@ -1,561 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_ASYNC_IO_H_ -#define KJ_ASYNC_IO_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "async.h" -#include "function.h" -#include "thread.h" -#include "time.h" - -struct sockaddr; - -namespace kj { - -#if _WIN32 -class Win32EventPort; -#else -class UnixEventPort; -#endif - -class NetworkAddress; -class AsyncOutputStream; - -// ======================================================================================= -// Streaming I/O - -class AsyncInputStream { - // Asynchronous equivalent of InputStream (from io.h). - -public: - virtual Promise read(void* buffer, size_t minBytes, size_t maxBytes); - virtual Promise tryRead(void* buffer, size_t minBytes, size_t maxBytes) = 0; - - Promise read(void* buffer, size_t bytes); - - virtual Maybe tryGetLength(); - // Get the remaining number of bytes that will be produced by this stream, if known. - // - // This is used e.g. to fill in the Content-Length header of an HTTP message. If unknown, the - // HTTP implementation may need to fall back to Transfer-Encoding: chunked. - // - // The default implementation always returns null. - - virtual Promise pumpTo( - AsyncOutputStream& output, uint64_t amount = kj::maxValue); - // Read `amount` bytes from this stream (or to EOF) and write them to `output`, returning the - // total bytes actually pumped (which is only less than `amount` if EOF was reached). - // - // Override this if your stream type knows how to pump itself to certain kinds of output - // streams more efficiently than via the naive approach. You can use - // kj::dynamicDowncastIfAvailable() to test for stream types you recognize, and if none match, - // delegate to the default implementation. - // - // The default implementation first tries calling output.tryPumpFrom(), but if that fails, it - // performs a naive pump by allocating a buffer and reading to it / writing from it in a loop. - - Promise> readAllBytes(); - Promise readAllText(); - // Read until EOF and return as one big byte array or string. -}; - -class AsyncOutputStream { - // Asynchronous equivalent of OutputStream (from io.h). - -public: - virtual Promise write(const void* buffer, size_t size) KJ_WARN_UNUSED_RESULT = 0; - virtual Promise write(ArrayPtr> pieces) - KJ_WARN_UNUSED_RESULT = 0; - - virtual Maybe> tryPumpFrom( - AsyncInputStream& input, uint64_t amount = kj::maxValue); - // Implements double-dispatch for AsyncInputStream::pumpTo(). - // - // This method should only be called from within an implementation of pumpTo(). - // - // This method examines the type of `input` to find optimized ways to pump data from it to this - // output stream. If it finds one, it performs the pump. Otherwise, it returns null. - // - // The default implementation always returns null. -}; - -class AsyncIoStream: public AsyncInputStream, public AsyncOutputStream { - // A combination input and output stream. - -public: - virtual void shutdownWrite() = 0; - // Cleanly shut down just the write end of the stream, while keeping the read end open. - - virtual void abortRead() {} - // Similar to shutdownWrite, but this will shut down the read end of the stream, and should only - // be called when an error has occurred. - - virtual void getsockopt(int level, int option, void* value, uint* length); - virtual void setsockopt(int level, int option, const void* value, uint length); - // Corresponds to getsockopt() and setsockopt() syscalls. Will throw an "unimplemented" exception - // if the stream is not a socket or the option is not appropriate for the socket type. The - // default implementations always throw "unimplemented". - - virtual void getsockname(struct sockaddr* addr, uint* length); - virtual void getpeername(struct sockaddr* addr, uint* length); - // Corresponds to getsockname() and getpeername() syscalls. Will throw an "unimplemented" - // exception if the stream is not a socket. The default implementations always throw - // "unimplemented". - // - // Note that we don't provide methods that return NetworkAddress because it usually wouldn't - // be useful. You can't connect() to or listen() on these addresses, obviously, because they are - // ephemeral addresses for a single connection. -}; - -struct OneWayPipe { - // A data pipe with an input end and an output end. (Typically backed by pipe() system call.) - - Own in; - Own out; -}; - -struct TwoWayPipe { - // A data pipe that supports sending in both directions. Each end's output sends data to the - // other end's input. (Typically backed by socketpair() system call.) - - Own ends[2]; -}; - -class ConnectionReceiver { - // Represents a server socket listening on a port. - -public: - virtual Promise> accept() = 0; - // Accept the next incoming connection. - - virtual uint getPort() = 0; - // Gets the port number, if applicable (i.e. if listening on IP). This is useful if you didn't - // specify a port when constructing the NetworkAddress -- one will have been assigned - // automatically. - - virtual void getsockopt(int level, int option, void* value, uint* length); - virtual void setsockopt(int level, int option, const void* value, uint length); - // Same as the methods of AsyncIoStream. -}; - -// ======================================================================================= -// Datagram I/O - -class AncillaryMessage { - // Represents an ancillary message (aka control message) received using the recvmsg() system - // call (or equivalent). Most apps will not use this. - -public: - inline AncillaryMessage(int level, int type, ArrayPtr data); - AncillaryMessage() = default; - - inline int getLevel() const; - // Originating protocol / socket level. - - inline int getType() const; - // Protocol-specific message type. - - template - inline Maybe as(); - // Interpret the ancillary message as the given struct type. Most ancillary messages are some - // sort of struct, so this is a convenient way to access it. Returns nullptr if the message - // is smaller than the struct -- this can happen if the message was truncated due to - // insufficient ancillary buffer space. - - template - inline ArrayPtr asArray(); - // Interpret the ancillary message as an array of items. If the message size does not evenly - // divide into elements of type T, the remainder is discarded -- this can happen if the message - // was truncated due to insufficient ancillary buffer space. - -private: - int level; - int type; - ArrayPtr data; - // Message data. In most cases you should use `as()` or `asArray()`. -}; - -class DatagramReceiver { - // Class encapsulating the recvmsg() system call. You must specify the DatagramReceiver's - // capacity in advance; if a received packet is larger than the capacity, it will be truncated. - -public: - virtual Promise receive() = 0; - // Receive a new message, overwriting this object's content. - // - // receive() may reuse the same buffers for content and ancillary data with each call. - - template - struct MaybeTruncated { - T value; - - bool isTruncated; - // True if the Receiver's capacity was insufficient to receive the value and therefore the - // value is truncated. - }; - - virtual MaybeTruncated> getContent() = 0; - // Get the content of the datagram. - - virtual MaybeTruncated> getAncillary() = 0; - // Ancilarry messages received with the datagram. See the recvmsg() system call and the cmsghdr - // struct. Most apps don't need this. - // - // If the returned value is truncated, then the last message in the array may itself be - // truncated, meaning its as() method will return nullptr or its asArray() method will - // return fewer elements than expected. Truncation can also mean that additional messages were - // available but discarded. - - virtual NetworkAddress& getSource() = 0; - // Get the datagram sender's address. - - struct Capacity { - size_t content = 8192; - // How much space to allocate for the datagram content. If a datagram is received that is - // larger than this, it will be truncated, with no way to recover the tail. - - size_t ancillary = 0; - // How much space to allocate for ancillary messages. As with content, if the ancillary data - // is larger than this, it will be truncated. - }; -}; - -class DatagramPort { -public: - virtual Promise send(const void* buffer, size_t size, NetworkAddress& destination) = 0; - virtual Promise send(ArrayPtr> pieces, - NetworkAddress& destination) = 0; - - virtual Own makeReceiver( - DatagramReceiver::Capacity capacity = DatagramReceiver::Capacity()) = 0; - // Create a new `Receiver` that can be used to receive datagrams. `capacity` specifies how much - // space to allocate for the received message. The `DatagramPort` must outlive the `Receiver`. - - virtual uint getPort() = 0; - // Gets the port number, if applicable (i.e. if listening on IP). This is useful if you didn't - // specify a port when constructing the NetworkAddress -- one will have been assigned - // automatically. - - virtual void getsockopt(int level, int option, void* value, uint* length); - virtual void setsockopt(int level, int option, const void* value, uint length); - // Same as the methods of AsyncIoStream. -}; - -// ======================================================================================= -// Networks - -class NetworkAddress { - // Represents a remote address to which the application can connect. - -public: - virtual Promise> connect() = 0; - // Make a new connection to this address. - // - // The address must not be a wildcard ("*"). If it is an IP address, it must have a port number. - - virtual Own listen() = 0; - // Listen for incoming connections on this address. - // - // The address must be local. - - virtual Own bindDatagramPort(); - // Open this address as a datagram (e.g. UDP) port. - // - // The address must be local. - - virtual Own clone() = 0; - // Returns an equivalent copy of this NetworkAddress. - - virtual String toString() = 0; - // Produce a human-readable string which hopefully can be passed to Network::parseAddress() - // to reproduce this address, although whether or not that works of course depends on the Network - // implementation. This should be called only to display the address to human users, who will - // hopefully know what they are able to do with it. -}; - -class Network { - // Factory for NetworkAddress instances, representing the network services offered by the - // operating system. - // - // This interface typically represents broad authority, and well-designed code should limit its - // use to high-level startup code and user interaction. Low-level APIs should accept - // NetworkAddress instances directly and work from there, if at all possible. - -public: - virtual Promise> parseAddress(StringPtr addr, uint portHint = 0) = 0; - // Construct a network address from a user-provided string. The format of the address - // strings is not specified at the API level, and application code should make no assumptions - // about them. These strings should always be provided by humans, and said humans will know - // what format to use in their particular context. - // - // `portHint`, if provided, specifies the "standard" IP port number for the application-level - // service in play. If the address turns out to be an IP address (v4 or v6), and it lacks a - // port number, this port will be used. If `addr` lacks a port number *and* `portHint` is - // omitted, then the returned address will only support listen() and bindDatagramPort() - // (not connect()), and an unused port will be chosen each time one of those methods is called. - - virtual Own getSockaddr(const void* sockaddr, uint len) = 0; - // Construct a network address from a legacy struct sockaddr. -}; - -// ======================================================================================= -// I/O Provider - -class AsyncIoProvider { - // Class which constructs asynchronous wrappers around the operating system's I/O facilities. - // - // Generally, the implementation of this interface must integrate closely with a particular - // `EventLoop` implementation. Typically, the EventLoop implementation itself will provide - // an AsyncIoProvider. - -public: - virtual OneWayPipe newOneWayPipe() = 0; - // Creates an input/output stream pair representing the ends of a one-way pipe (e.g. created with - // the pipe(2) system call). - - virtual TwoWayPipe newTwoWayPipe() = 0; - // Creates two AsyncIoStreams representing the two ends of a two-way pipe (e.g. created with - // socketpair(2) system call). Data written to one end can be read from the other. - - virtual Network& getNetwork() = 0; - // Creates a new `Network` instance representing the networks exposed by the operating system. - // - // DO NOT CALL THIS except at the highest levels of your code, ideally in the main() function. If - // you call this from low-level code, then you are preventing higher-level code from injecting an - // alternative implementation. Instead, if your code needs to use network functionality, it - // should ask for a `Network` as a constructor or method parameter, so that higher-level code can - // chose what implementation to use. The system network is essentially a singleton. See: - // http://www.object-oriented-security.org/lets-argue/singletons - // - // Code that uses the system network should not make any assumptions about what kinds of - // addresses it will parse, as this could differ across platforms. String addresses should come - // strictly from the user, who will know how to write them correctly for their system. - // - // With that said, KJ currently supports the following string address formats: - // - IPv4: "1.2.3.4", "1.2.3.4:80" - // - IPv6: "1234:5678::abcd", "[1234:5678::abcd]:80" - // - Local IP wildcard (covers both v4 and v6): "*", "*:80" - // - Symbolic names: "example.com", "example.com:80", "example.com:http", "1.2.3.4:http" - // - Unix domain: "unix:/path/to/socket" - - struct PipeThread { - // A combination of a thread and a two-way pipe that communicates with that thread. - // - // The fields are intentionally ordered so that the pipe will be destroyed (and therefore - // disconnected) before the thread is destroyed (and therefore joined). Thus if the thread - // arranges to exit when it detects disconnect, destruction should be clean. - - Own thread; - Own pipe; - }; - - virtual PipeThread newPipeThread( - Function startFunc) = 0; - // Create a new thread and set up a two-way pipe (socketpair) which can be used to communicate - // with it. One end of the pipe is passed to the thread's start function and the other end of - // the pipe is returned. The new thread also gets its own `AsyncIoProvider` instance and will - // already have an active `EventLoop` when `startFunc` is called. - // - // TODO(someday): I'm not entirely comfortable with this interface. It seems to be doing too - // much at once but I'm not sure how to cleanly break it down. - - virtual Timer& getTimer() = 0; - // Returns a `Timer` based on real time. Time does not pass while event handlers are running -- - // it only updates when the event loop polls for system events. This means that calling `now()` - // on this timer does not require a system call. - // - // This timer is not affected by changes to the system date. It is unspecified whether the timer - // continues to count while the system is suspended. -}; - -class LowLevelAsyncIoProvider { - // Similar to `AsyncIoProvider`, but represents a lower-level interface that may differ on - // different operating systems. You should prefer to use `AsyncIoProvider` over this interface - // whenever possible, as `AsyncIoProvider` is portable and friendlier to dependency-injection. - // - // On Unix, this interface can be used to import native file descriptors into the async framework. - // Different implementations of this interface might work on top of different event handling - // primitives, such as poll vs. epoll vs. kqueue vs. some higher-level event library. - // - // On Windows, this interface can be used to import native HANDLEs into the async framework. - // Different implementations of this interface might work on top of different event handling - // primitives, such as I/O completion ports vs. completion routines. - // - // TODO(port): Actually implement Windows support. - -public: - // --------------------------------------------------------------------------- - // Unix-specific stuff - - enum Flags { - // Flags controlling how to wrap a file descriptor. - - TAKE_OWNERSHIP = 1 << 0, - // The returned object should own the file descriptor, automatically closing it when destroyed. - // The close-on-exec flag will be set on the descriptor if it is not already. - // - // If this flag is not used, then the file descriptor is not automatically closed and the - // close-on-exec flag is not modified. - -#if !_WIN32 - ALREADY_CLOEXEC = 1 << 1, - // Indicates that the close-on-exec flag is known already to be set, so need not be set again. - // Only relevant when combined with TAKE_OWNERSHIP. - // - // On Linux, all system calls which yield new file descriptors have flags or variants which - // set the close-on-exec flag immediately. Unfortunately, other OS's do not. - - ALREADY_NONBLOCK = 1 << 2 - // Indicates that the file descriptor is known already to be in non-blocking mode, so the flag - // need not be set again. Otherwise, all wrap*Fd() methods will enable non-blocking mode - // automatically. - // - // On Linux, all system calls which yield new file descriptors have flags or variants which - // enable non-blocking mode immediately. Unfortunately, other OS's do not. -#endif - }; - -#if _WIN32 - typedef uintptr_t Fd; - // On Windows, the `fd` parameter to each of these methods must be a SOCKET, and must have the - // flag WSA_FLAG_OVERLAPPED (which socket() uses by default, but WSASocket() wants you to specify - // explicitly). -#else - typedef int Fd; - // On Unix, any arbitrary file descriptor is supported. -#endif - - virtual Own wrapInputFd(Fd fd, uint flags = 0) = 0; - // Create an AsyncInputStream wrapping a file descriptor. - // - // `flags` is a bitwise-OR of the values of the `Flags` enum. - - virtual Own wrapOutputFd(Fd fd, uint flags = 0) = 0; - // Create an AsyncOutputStream wrapping a file descriptor. - // - // `flags` is a bitwise-OR of the values of the `Flags` enum. - - virtual Own wrapSocketFd(Fd fd, uint flags = 0) = 0; - // Create an AsyncIoStream wrapping a socket file descriptor. - // - // `flags` is a bitwise-OR of the values of the `Flags` enum. - - virtual Promise> wrapConnectingSocketFd( - Fd fd, const struct sockaddr* addr, uint addrlen, uint flags = 0) = 0; - // Create an AsyncIoStream wrapping a socket and initiate a connection to the given address. - // The returned promise does not resolve until connection has completed. - // - // `flags` is a bitwise-OR of the values of the `Flags` enum. - - virtual Own wrapListenSocketFd(Fd fd, uint flags = 0) = 0; - // Create an AsyncIoStream wrapping a listen socket file descriptor. This socket should already - // have had `bind()` and `listen()` called on it, so it's ready for `accept()`. - // - // `flags` is a bitwise-OR of the values of the `Flags` enum. - - virtual Own wrapDatagramSocketFd(Fd fd, uint flags = 0); - - virtual Timer& getTimer() = 0; - // Returns a `Timer` based on real time. Time does not pass while event handlers are running -- - // it only updates when the event loop polls for system events. This means that calling `now()` - // on this timer does not require a system call. - // - // This timer is not affected by changes to the system date. It is unspecified whether the timer - // continues to count while the system is suspended. -}; - -Own newAsyncIoProvider(LowLevelAsyncIoProvider& lowLevel); -// Make a new AsyncIoProvider wrapping a `LowLevelAsyncIoProvider`. - -struct AsyncIoContext { - Own lowLevelProvider; - Own provider; - WaitScope& waitScope; - -#if _WIN32 - Win32EventPort& win32EventPort; -#else - UnixEventPort& unixEventPort; - // TEMPORARY: Direct access to underlying UnixEventPort, mainly for waiting on signals. This - // field will go away at some point when we have a chance to improve these interfaces. -#endif -}; - -AsyncIoContext setupAsyncIo(); -// Convenience method which sets up the current thread with everything it needs to do async I/O. -// The returned objects contain an `EventLoop` which is wrapping an appropriate `EventPort` for -// doing I/O on the host system, so everything is ready for the thread to start making async calls -// and waiting on promises. -// -// You would typically call this in your main() loop or in the start function of a thread. -// Example: -// -// int main() { -// auto ioContext = kj::setupAsyncIo(); -// -// // Now we can call an async function. -// Promise textPromise = getHttp(*ioContext.provider, "http://example.com"); -// -// // And we can wait for the promise to complete. Note that you can only use `wait()` -// // from the top level, not from inside a promise callback. -// String text = textPromise.wait(ioContext.waitScope); -// print(text); -// return 0; -// } -// -// WARNING: An AsyncIoContext can only be used in the thread and process that created it. In -// particular, note that after a fork(), an AsyncIoContext created in the parent process will -// not work correctly in the child, even if the parent ceases to use its copy. In particular -// note that this means that server processes which daemonize themselves at startup must wait -// until after daemonization to create an AsyncIoContext. - -// ======================================================================================= -// inline implementation details - -inline AncillaryMessage::AncillaryMessage( - int level, int type, ArrayPtr data) - : level(level), type(type), data(data) {} - -inline int AncillaryMessage::getLevel() const { return level; } -inline int AncillaryMessage::getType() const { return type; } - -template -inline Maybe AncillaryMessage::as() { - if (data.size() >= sizeof(T)) { - return *reinterpret_cast(data.begin()); - } else { - return nullptr; - } -} - -template -inline ArrayPtr AncillaryMessage::asArray() { - return arrayPtr(reinterpret_cast(data.begin()), data.size() / sizeof(T)); -} - -} // namespace kj - -#endif // KJ_ASYNC_IO_H_ diff --git a/phonelibs/capnp-cpp/include/kj/async-prelude.h b/phonelibs/capnp-cpp/include/kj/async-prelude.h deleted file mode 100644 index 0a5843f88a..0000000000 --- a/phonelibs/capnp-cpp/include/kj/async-prelude.h +++ /dev/null @@ -1,218 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// This file contains a bunch of internal declarations that must appear before async.h can start. -// We don't define these directly in async.h because it makes the file hard to read. - -#ifndef KJ_ASYNC_PRELUDE_H_ -#define KJ_ASYNC_PRELUDE_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "exception.h" -#include "tuple.h" - -namespace kj { - -class EventLoop; -template -class Promise; -class WaitScope; - -template -Promise> joinPromises(Array>&& promises); -Promise joinPromises(Array>&& promises); - -namespace _ { // private - -template struct JoinPromises_ { typedef T Type; }; -template struct JoinPromises_> { typedef T Type; }; - -template -using JoinPromises = typename JoinPromises_::Type; -// If T is Promise, resolves to U, otherwise resolves to T. -// -// TODO(cleanup): Rename to avoid confusion with joinPromises() call which is completely -// unrelated. - -class PropagateException { - // A functor which accepts a kj::Exception as a parameter and returns a broken promise of - // arbitrary type which simply propagates the exception. -public: - class Bottom { - public: - Bottom(Exception&& exception): exception(kj::mv(exception)) {} - - Exception asException() { return kj::mv(exception); } - - private: - Exception exception; - }; - - Bottom operator()(Exception&& e) { - return Bottom(kj::mv(e)); - } - Bottom operator()(const Exception& e) { - return Bottom(kj::cp(e)); - } -}; - -template -struct ReturnType_ { typedef decltype(instance()(instance())) Type; }; -template -struct ReturnType_ { typedef decltype(instance()()) Type; }; - -template -using ReturnType = typename ReturnType_::Type; -// The return type of functor Func given a parameter of type T, with the special exception that if -// T is void, this is the return type of Func called with no arguments. - -template struct SplitTuplePromise_ { typedef Promise Type; }; -template -struct SplitTuplePromise_> { - typedef kj::Tuple>...> Type; -}; - -template -using SplitTuplePromise = typename SplitTuplePromise_::Type; -// T -> Promise -// Tuple -> Tuple> - -struct Void {}; -// Application code should NOT refer to this! See `kj::READY_NOW` instead. - -template struct FixVoid_ { typedef T Type; }; -template <> struct FixVoid_ { typedef Void Type; }; -template using FixVoid = typename FixVoid_::Type; -// FixVoid is just T unless T is void in which case it is _::Void (an empty struct). - -template struct UnfixVoid_ { typedef T Type; }; -template <> struct UnfixVoid_ { typedef void Type; }; -template using UnfixVoid = typename UnfixVoid_::Type; -// UnfixVoid is the opposite of FixVoid. - -template -struct MaybeVoidCaller { - // Calls the function converting a Void input to an empty parameter list and a void return - // value to a Void output. - - template - static inline Out apply(Func& func, In&& in) { - return func(kj::mv(in)); - } -}; -template -struct MaybeVoidCaller { - template - static inline Out apply(Func& func, In& in) { - return func(in); - } -}; -template -struct MaybeVoidCaller { - template - static inline Out apply(Func& func, Void&& in) { - return func(); - } -}; -template -struct MaybeVoidCaller { - template - static inline Void apply(Func& func, In&& in) { - func(kj::mv(in)); - return Void(); - } -}; -template -struct MaybeVoidCaller { - template - static inline Void apply(Func& func, In& in) { - func(in); - return Void(); - } -}; -template <> -struct MaybeVoidCaller { - template - static inline Void apply(Func& func, Void&& in) { - func(); - return Void(); - } -}; - -template -inline T&& returnMaybeVoid(T&& t) { - return kj::fwd(t); -} -inline void returnMaybeVoid(Void&& v) {} - -class ExceptionOrValue; -class PromiseNode; -class ChainPromiseNode; -template -class ForkHub; - -class TaskSetImpl; - -class Event; - -class PromiseBase { -public: - kj::String trace(); - // Dump debug info about this promise. - -private: - Own node; - - PromiseBase() = default; - PromiseBase(Own&& node): node(kj::mv(node)) {} - - friend class kj::EventLoop; - friend class ChainPromiseNode; - template - friend class kj::Promise; - friend class TaskSetImpl; - template - friend Promise> kj::joinPromises(Array>&& promises); - friend Promise kj::joinPromises(Array>&& promises); -}; - -void detach(kj::Promise&& promise); -void waitImpl(Own<_::PromiseNode>&& node, _::ExceptionOrValue& result, WaitScope& waitScope); -Promise yield(); -Own neverDone(); - -class NeverDone { -public: - template - operator Promise() const { - return Promise(false, neverDone()); - } - - KJ_NORETURN(void wait(WaitScope& waitScope) const); -}; - -} // namespace _ (private) -} // namespace kj - -#endif // KJ_ASYNC_PRELUDE_H_ diff --git a/phonelibs/capnp-cpp/include/kj/async-unix.h b/phonelibs/capnp-cpp/include/kj/async-unix.h deleted file mode 100644 index 06f128a50e..0000000000 --- a/phonelibs/capnp-cpp/include/kj/async-unix.h +++ /dev/null @@ -1,274 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_ASYNC_UNIX_H_ -#define KJ_ASYNC_UNIX_H_ - -#if _WIN32 -#error "This file is Unix-specific. On Windows, include async-win32.h instead." -#endif - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "async.h" -#include "time.h" -#include "vector.h" -#include "io.h" -#include - -#if __linux__ && !__BIONIC__ && !defined(KJ_USE_EPOLL) -// Default to epoll on Linux, except on Bionic (Android) which doesn't have signalfd.h. -#define KJ_USE_EPOLL 1 -#endif - -namespace kj { - -class UnixEventPort: public EventPort { - // An EventPort implementation which can wait for events on file descriptors as well as signals. - // This API only makes sense on Unix. - // - // The implementation uses `poll()` or possibly a platform-specific API (e.g. epoll, kqueue). - // To also wait on signals without race conditions, the implementation may block signals until - // just before `poll()` while using a signal handler which `siglongjmp()`s back to just before - // the signal was unblocked, or it may use a nicer platform-specific API like signalfd. - // - // The implementation reserves a signal for internal use. By default, it uses SIGUSR1. If you - // need to use SIGUSR1 for something else, you must offer a different signal by calling - // setReservedSignal() at startup. - // - // WARNING: A UnixEventPort can only be used in the thread and process that created it. In - // particular, note that after a fork(), a UnixEventPort created in the parent process will - // not work correctly in the child, even if the parent ceases to use its copy. In particular - // note that this means that server processes which daemonize themselves at startup must wait - // until after daemonization to create a UnixEventPort. - -public: - UnixEventPort(); - ~UnixEventPort() noexcept(false); - - class FdObserver; - // Class that watches an fd for readability or writability. See definition below. - - Promise onSignal(int signum); - // When the given signal is delivered to this thread, return the corresponding siginfo_t. - // The signal must have been captured using `captureSignal()`. - // - // If `onSignal()` has not been called, the signal will remain blocked in this thread. - // Therefore, a signal which arrives before `onSignal()` was called will not be "missed" -- the - // next call to 'onSignal()' will receive it. Also, you can control which thread receives a - // process-wide signal by only calling `onSignal()` on that thread's event loop. - // - // The result of waiting on the same signal twice at once is undefined. - - static void captureSignal(int signum); - // Arranges for the given signal to be captured and handled via UnixEventPort, so that you may - // then pass it to `onSignal()`. This method is static because it registers a signal handler - // which applies process-wide. If any other threads exist in the process when `captureSignal()` - // is called, you *must* set the signal mask in those threads to block this signal, otherwise - // terrible things will happen if the signal happens to be delivered to those threads. If at - // all possible, call `captureSignal()` *before* creating threads, so that threads you create in - // the future will inherit the proper signal mask. - // - // To un-capture a signal, simply install a different signal handler and then un-block it from - // the signal mask. - - static void setReservedSignal(int signum); - // Sets the signal number which `UnixEventPort` reserves for internal use. If your application - // needs to use SIGUSR1, call this at startup (before any calls to `captureSignal()` and before - // constructing an `UnixEventPort`) to offer a different signal. - - Timer& getTimer() { return timerImpl; } - - // implements EventPort ------------------------------------------------------ - bool wait() override; - bool poll() override; - void wake() const override; - -private: - struct TimerSet; // Defined in source file to avoid STL include. - class TimerPromiseAdapter; - class SignalPromiseAdapter; - - TimerImpl timerImpl; - - SignalPromiseAdapter* signalHead = nullptr; - SignalPromiseAdapter** signalTail = &signalHead; - - TimePoint readClock(); - void gotSignal(const siginfo_t& siginfo); - - friend class TimerPromiseAdapter; - -#if KJ_USE_EPOLL - AutoCloseFd epollFd; - AutoCloseFd signalFd; - AutoCloseFd eventFd; // Used for cross-thread wakeups. - - sigset_t signalFdSigset; - // Signal mask as currently set on the signalFd. Tracked so we can detect whether or not it - // needs updating. - - bool doEpollWait(int timeout); - -#else - class PollContext; - - FdObserver* observersHead = nullptr; - FdObserver** observersTail = &observersHead; - - unsigned long long threadId; // actually pthread_t -#endif -}; - -class UnixEventPort::FdObserver { - // Object which watches a file descriptor to determine when it is readable or writable. - // - // For listen sockets, "readable" means that there is a connection to accept(). For everything - // else, it means that read() (or recv()) will return data. - // - // The presence of out-of-band data should NOT fire this event. However, the event may - // occasionally fire spuriously (when there is actually no data to read), and one thing that can - // cause such spurious events is the arrival of OOB data on certain platforms whose event - // interfaces fail to distinguish between regular and OOB data (e.g. Mac OSX). - // - // WARNING: The exact behavior of this class differs across systems, since event interfaces - // vary wildly. Be sure to read the documentation carefully and avoid depending on unspecified - // behavior. If at all possible, use the higher-level AsyncInputStream interface instead. - -public: - enum Flags { - OBSERVE_READ = 1, - OBSERVE_WRITE = 2, - OBSERVE_URGENT = 4, - OBSERVE_READ_WRITE = OBSERVE_READ | OBSERVE_WRITE - }; - - FdObserver(UnixEventPort& eventPort, int fd, uint flags); - // Begin watching the given file descriptor for readability. Only one ReadObserver may exist - // for a given file descriptor at a time. - - ~FdObserver() noexcept(false); - - KJ_DISALLOW_COPY(FdObserver); - - Promise whenBecomesReadable(); - // Resolves the next time the file descriptor transitions from having no data to read to having - // some data to read. - // - // KJ uses "edge-triggered" event notification whenever possible. As a result, it is an error - // to call this method when there is already data in the read buffer which has been there since - // prior to the last turn of the event loop or prior to creation FdWatcher. In this case, it is - // unspecified whether the promise will ever resolve -- it depends on the underlying event - // mechanism being used. - // - // In order to avoid this problem, make sure that you only call `whenBecomesReadable()` - // only at times when you know the buffer is empty. You know this for sure when one of the - // following happens: - // * read() or recv() fails with EAGAIN or EWOULDBLOCK. (You MUST have non-blocking mode - // enabled on the fd!) - // * The file descriptor is a regular byte-oriented object (like a socket or pipe), - // read() or recv() returns fewer than the number of bytes requested, and `atEndHint()` - // returns false. This can only happen if the buffer is empty but EOF is not reached. (Note, - // though, that for record-oriented file descriptors like Linux's inotify interface, this - // rule does not hold, because it could simply be that the next record did not fit into the - // space available.) - // - // It is an error to call `whenBecomesReadable()` again when the promise returned previously - // has not yet resolved. If you do this, the previous promise may throw an exception. - - inline Maybe atEndHint() { return atEnd; } - // Returns true if the event system has indicated that EOF has been received. There may still - // be data in the read buffer, but once that is gone, there's nothing left. - // - // Returns false if the event system has indicated that EOF had NOT been received as of the - // last turn of the event loop. - // - // Returns nullptr if the event system does not know whether EOF has been reached. In this - // case, the only way to know for sure is to call read() or recv() and check if it returns - // zero. - // - // This hint may be useful as an optimization to avoid an unnecessary system call. - - Promise whenBecomesWritable(); - // Resolves the next time the file descriptor transitions from having no space available in the - // write buffer to having some space available. - // - // KJ uses "edge-triggered" event notification whenever possible. As a result, it is an error - // to call this method when there is already space in the write buffer which has been there - // since prior to the last turn of the event loop or prior to creation FdWatcher. In this case, - // it is unspecified whether the promise will ever resolve -- it depends on the underlying - // event mechanism being used. - // - // In order to avoid this problem, make sure that you only call `whenBecomesWritable()` - // only at times when you know the buffer is full. You know this for sure when one of the - // following happens: - // * write() or send() fails with EAGAIN or EWOULDBLOCK. (You MUST have non-blocking mode - // enabled on the fd!) - // * write() or send() succeeds but accepts fewer than the number of bytes provided. This can - // only happen if the buffer is full. - // - // It is an error to call `whenBecomesWritable()` again when the promise returned previously - // has not yet resolved. If you do this, the previous promise may throw an exception. - - Promise whenUrgentDataAvailable(); - // Resolves the next time the file descriptor's read buffer contains "urgent" data. - // - // The conditions for availability of urgent data are specific to the file descriptor's - // underlying implementation. - // - // It is an error to call `whenUrgentDataAvailable()` again when the promise returned previously - // has not yet resolved. If you do this, the previous promise may throw an exception. - // - // WARNING: This has some known weird behavior on macOS. See - // https://github.com/sandstorm-io/capnproto/issues/374. - -private: - UnixEventPort& eventPort; - int fd; - uint flags; - - kj::Maybe>> readFulfiller; - kj::Maybe>> writeFulfiller; - kj::Maybe>> urgentFulfiller; - // Replaced each time `whenBecomesReadable()` or `whenBecomesWritable()` is called. Reverted to - // null every time an event is fired. - - Maybe atEnd; - - void fire(short events); - -#if !KJ_USE_EPOLL - FdObserver* next; - FdObserver** prev; - // Linked list of observers which currently have a non-null readFulfiller or writeFulfiller. - // If `prev` is null then the observer is not currently in the list. - - short getEventMask(); -#endif - - friend class UnixEventPort; -}; - -} // namespace kj - -#endif // KJ_ASYNC_UNIX_H_ diff --git a/phonelibs/capnp-cpp/include/kj/async-win32.h b/phonelibs/capnp-cpp/include/kj/async-win32.h deleted file mode 100644 index b70c42e016..0000000000 --- a/phonelibs/capnp-cpp/include/kj/async-win32.h +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright (c) 2016 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_ASYNC_WIN32_H_ -#define KJ_ASYNC_WIN32_H_ - -#if !_WIN32 -#error "This file is Windows-specific. On Unix, include async-unix.h instead." -#endif - -#include "async.h" -#include "time.h" -#include "io.h" -#include -#include - -// Include windows.h as lean as possible. (If you need more of the Windows API for your app, -// #include windows.h yourself before including this header.) -#define WIN32_LEAN_AND_MEAN 1 -#define NOSERVICE 1 -#define NOMCX 1 -#define NOIME 1 -#include -#include "windows-sanity.h" - -namespace kj { - -class Win32EventPort: public EventPort { - // Abstract base interface for EventPorts that can listen on Win32 event types. Due to the - // absurd complexity of the Win32 API, it's not possible to standardize on a single - // implementation of EventPort. In particular, there is no way for a single thread to use I/O - // completion ports (the most efficient way of handling I/O) while at the same time waiting for - // signalable handles or UI messages. - // - // Note that UI messages are not supported at all by this interface because the message queue - // is implemented by user32.dll and we want libkj to depend only on kernel32.dll. A separate - // compat library could provide a Win32EventPort implementation that works with the UI message - // queue. - -public: - // --------------------------------------------------------------------------- - // overlapped I/O - - struct IoResult { - DWORD errorCode; - DWORD bytesTransferred; - }; - - class IoOperation { - public: - virtual LPOVERLAPPED getOverlapped() = 0; - // Gets the OVERLAPPED structure to pass to the Win32 I/O call. Do NOT modify it; just pass it - // on. - - virtual Promise onComplete() = 0; - // After making the Win32 call, if the return value indicates that the operation was - // successfully queued (i.e. the completion event will definitely occur), call this to wait - // for completion. - // - // You MUST call this if the operation was successfully queued, and you MUST NOT call this - // otherwise. If the Win32 call failed (without queuing any operation or event) then you should - // simply drop the IoOperation object. - // - // Dropping the returned Promise cancels the operation via Win32's CancelIoEx(). The destructor - // will wait for the cancellation to complete, such that after dropping the proimse it is safe - // to free the buffer that the operation was reading from / writing to. - // - // You may safely drop the `IoOperation` while still waiting for this promise. You may not, - // however, drop the `IoObserver`. - }; - - class IoObserver { - public: - virtual Own newOperation(uint64_t offset) = 0; - // Begin an I/O operation. For file operations, `offset` is the offset within the file at - // which the operation will start. For stream operations, `offset` is ignored. - }; - - virtual Own observeIo(HANDLE handle) = 0; - // Given a handle which supports overlapped I/O, arrange to receive I/O completion events via - // this EventPort. - // - // Different Win32EventPort implementations may handle this in different ways, such as by using - // completion routines (APCs) or by using I/O completion ports. The caller should not assume - // any particular technique. - // - // WARNING: It is only safe to call observeIo() on a particular handle once during its lifetime. - // You cannot observe the same handle from multiple Win32EventPorts, even if not at the same - // time. This is because the Win32 API provides no way to disassociate a handle from an I/O - // completion port once it is associated. - - // --------------------------------------------------------------------------- - // signalable handles - // - // Warning: Due to limitations in the Win32 API, implementations of EventPort may be forced to - // spawn additional threads to wait for signaled objects. This is necessary if the EventPort - // implementation is based on I/O completion ports, or if you need to wait on more than 64 - // handles at once. - - class SignalObserver { - public: - virtual Promise onSignaled() = 0; - // Returns a promise that completes the next time the handle enters the signaled state. - // - // Depending on the type of handle, the handle may automatically be reset to a non-signaled - // state before the promise resolves. The underlying implementaiton uses WaitForSingleObject() - // or an equivalent wait call, so check the documentation for that to understand the semantics. - // - // If the handle is a mutex and it is abandoned without being unlocked, the promise breaks with - // an exception. - - virtual Promise onSignaledOrAbandoned() = 0; - // Like onSingaled(), but instead of throwing when a mutex is abandoned, resolves to `true`. - // Resolves to `false` for non-abandoned signals. - }; - - virtual Own observeSignalState(HANDLE handle) = 0; - // Given a handle that supports waiting for it to become "signaled" via WaitForSingleObject(), - // return an object that can wait for this state using the EventPort. - - // --------------------------------------------------------------------------- - // APCs - - virtual void allowApc() = 0; - // If this is ever called, the Win32EventPort will switch modes so that APCs can be scheduled - // on the thread, e.g. through the Win32 QueueUserAPC() call. In the future, this may be enabled - // by default. However, as of this writing, Wine does not support the necessary - // GetQueuedCompletionStatusEx() call, thus allowApc() breaks Wine support. (Tested on Wine - // 1.8.7.) - // - // If the event port implementation can't support APCs for some reason, this throws. - - // --------------------------------------------------------------------------- - // time - - virtual Timer& getTimer() = 0; -}; - -class Win32WaitObjectThreadPool { - // Helper class that implements Win32EventPort::observeSignalState() by spawning additional - // threads as needed to perform the actual waiting. - // - // This class is intended to be used to assist in building Win32EventPort implementations. - -public: - Win32WaitObjectThreadPool(uint mainThreadCount = 0); - // `mainThreadCount` indicates the number of objects the main thread is able to listen on - // directly. Typically this would be zero (e.g. if the main thread watches an I/O completion - // port) or MAXIMUM_WAIT_OBJECTS (e.g. if the main thread is a UI thread but can use - // MsgWaitForMultipleObjectsEx() to wait on some handles at the same time as messages). - - Own observeSignalState(HANDLE handle); - // Implemetns Win32EventPort::observeSignalState(). - - uint prepareMainThreadWait(HANDLE* handles[]); - // Call immediately before invoking WaitForMultipleObjects() or similar in the main thread. - // Fills in `handles` with the handle pointers to wait on, and returns the number of handles - // in this array. (The array should be allocated to be at least the size passed to the - // constructor). - // - // There's no need to call this if `mainThreadCount` as passed to the constructor was zero. - - bool finishedMainThreadWait(DWORD returnCode); - // Call immediately after invoking WaitForMultipleObjects() or similar in the main thread, - // passing the value returend by that call. Returns true if the event indicated by `returnCode` - // has been handled (i.e. it was WAIT_OBJECT_n or WAIT_ABANDONED_n where n is in-range for the - // last call to prepareMainThreadWait()). -}; - -class Win32IocpEventPort final: public Win32EventPort { - // An EventPort implementation which uses Windows I/O completion ports to listen for events. - // - // With this implementation, observeSignalState() requires spawning a separate thread. - -public: - Win32IocpEventPort(); - ~Win32IocpEventPort() noexcept(false); - - // implements EventPort ------------------------------------------------------ - bool wait() override; - bool poll() override; - void wake() const override; - - // implements Win32IocpEventPort --------------------------------------------- - Own observeIo(HANDLE handle) override; - Own observeSignalState(HANDLE handle) override; - Timer& getTimer() override { return timerImpl; } - void allowApc() override { isAllowApc = true; } - -private: - class IoPromiseAdapter; - class IoOperationImpl; - class IoObserverImpl; - - AutoCloseHandle iocp; - AutoCloseHandle thread; - Win32WaitObjectThreadPool waitThreads; - TimerImpl timerImpl; - mutable std::atomic sentWake {false}; - bool isAllowApc = false; - - static TimePoint readClock(); - - void waitIocp(DWORD timeoutMs); - // Wait on the I/O completion port for up to timeoutMs and pump events. Does not advance the - // timer; caller must do that. - - bool receivedWake(); - - static AutoCloseHandle newIocpHandle(); - static AutoCloseHandle openCurrentThread(); -}; - -} // namespace kj - -#endif // KJ_ASYNC_WIN32_H_ diff --git a/phonelibs/capnp-cpp/include/kj/async.h b/phonelibs/capnp-cpp/include/kj/async.h deleted file mode 100644 index 5a9d9bdae7..0000000000 --- a/phonelibs/capnp-cpp/include/kj/async.h +++ /dev/null @@ -1,682 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_ASYNC_H_ -#define KJ_ASYNC_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "async-prelude.h" -#include "exception.h" -#include "refcount.h" - -namespace kj { - -class EventLoop; -class WaitScope; - -template -class Promise; -template -class ForkedPromise; -template -class PromiseFulfiller; -template -struct PromiseFulfillerPair; - -template -using PromiseForResult = Promise<_::JoinPromises<_::ReturnType>>; -// Evaluates to the type of Promise for the result of calling functor type Func with parameter type -// T. If T is void, then the promise is for the result of calling Func with no arguments. If -// Func itself returns a promise, the promises are joined, so you never get Promise>. - -// ======================================================================================= -// Promises - -template -class Promise: protected _::PromiseBase { - // The basic primitive of asynchronous computation in KJ. Similar to "futures", but designed - // specifically for event loop concurrency. Similar to E promises and JavaScript Promises/A. - // - // A Promise represents a promise to produce a value of type T some time in the future. Once - // that value has been produced, the promise is "fulfilled". Alternatively, a promise can be - // "broken", with an Exception describing what went wrong. You may implicitly convert a value of - // type T to an already-fulfilled Promise. You may implicitly convert the constant - // `kj::READY_NOW` to an already-fulfilled Promise. You may also implicitly convert a - // `kj::Exception` to an already-broken promise of any type. - // - // Promises are linear types -- they are moveable but not copyable. If a Promise is destroyed - // or goes out of scope (without being moved elsewhere), any ongoing asynchronous operations - // meant to fulfill the promise will be canceled if possible. All methods of `Promise` (unless - // otherwise noted) actually consume the promise in the sense of move semantics. (Arguably they - // should be rvalue-qualified, but at the time this interface was created compilers didn't widely - // support that yet and anyway it would be pretty ugly typing kj::mv(promise).whatever().) If - // you want to use one Promise in two different places, you must fork it with `fork()`. - // - // To use the result of a Promise, you must call `then()` and supply a callback function to - // call with the result. `then()` returns another promise, for the result of the callback. - // Any time that this would result in Promise>, the promises are collapsed into a - // simple Promise that first waits for the outer promise, then the inner. Example: - // - // // Open a remote file, read the content, and then count the - // // number of lines of text. - // // Note that none of the calls here block. `file`, `content` - // // and `lineCount` are all initialized immediately before any - // // asynchronous operations occur. The lambda callbacks are - // // called later. - // Promise> file = openFtp("ftp://host/foo/bar"); - // Promise content = file.then( - // [](Own file) -> Promise { - // return file.readAll(); - // }); - // Promise lineCount = content.then( - // [](String text) -> int { - // uint count = 0; - // for (char c: text) count += (c == '\n'); - // return count; - // }); - // - // For `then()` to work, the current thread must have an active `EventLoop`. Each callback - // is scheduled to execute in that loop. Since `then()` schedules callbacks only on the current - // thread's event loop, you do not need to worry about two callbacks running at the same time. - // You will need to set up at least one `EventLoop` at the top level of your program before you - // can use promises. - // - // To adapt a non-Promise-based asynchronous API to promises, use `newAdaptedPromise()`. - // - // Systems using promises should consider supporting the concept of "pipelining". Pipelining - // means allowing a caller to start issuing method calls against a promised object before the - // promise has actually been fulfilled. This is particularly useful if the promise is for a - // remote object living across a network, as this can avoid round trips when chaining a series - // of calls. It is suggested that any class T which supports pipelining implement a subclass of - // Promise which adds "eventual send" methods -- methods which, when called, say "please - // invoke the corresponding method on the promised value once it is available". These methods - // should in turn return promises for the eventual results of said invocations. Cap'n Proto, - // for example, implements the type `RemotePromise` which supports pipelining RPC requests -- see - // `capnp/capability.h`. - // - // KJ Promises are based on E promises: - // http://wiki.erights.org/wiki/Walnut/Distributed_Computing#Promises - // - // KJ Promises are also inspired in part by the evolving standards for JavaScript/ECMAScript - // promises, which are themselves influenced by E promises: - // http://promisesaplus.com/ - // https://github.com/domenic/promises-unwrapping - -public: - Promise(_::FixVoid value); - // Construct an already-fulfilled Promise from a value of type T. For non-void promises, the - // parameter type is simply T. So, e.g., in a function that returns `Promise`, you can - // say `return 123;` to return a promise that is already fulfilled to 123. - // - // For void promises, use `kj::READY_NOW` as the value, e.g. `return kj::READY_NOW`. - - Promise(kj::Exception&& e); - // Construct an already-broken Promise. - - inline Promise(decltype(nullptr)) {} - - template - PromiseForResult then(Func&& func, ErrorFunc&& errorHandler = _::PropagateException()) - KJ_WARN_UNUSED_RESULT; - // Register a continuation function to be executed when the promise completes. The continuation - // (`func`) takes the promised value (an rvalue of type `T`) as its parameter. The continuation - // may return a new value; `then()` itself returns a promise for the continuation's eventual - // result. If the continuation itself returns a `Promise`, then `then()` shall also return - // a `Promise` which first waits for the original promise, then executes the continuation, - // then waits for the inner promise (i.e. it automatically "unwraps" the promise). - // - // In all cases, `then()` returns immediately. The continuation is executed later. The - // continuation is always executed on the same EventLoop (and, therefore, the same thread) which - // called `then()`, therefore no synchronization is necessary on state shared by the continuation - // and the surrounding scope. If no EventLoop is running on the current thread, `then()` throws - // an exception. - // - // You may also specify an error handler continuation as the second parameter. `errorHandler` - // must be a functor taking a parameter of type `kj::Exception&&`. It must return the same - // type as `func` returns (except when `func` returns `Promise`, in which case `errorHandler` - // may return either `Promise` or just `U`). The default error handler simply propagates the - // exception to the returned promise. - // - // Either `func` or `errorHandler` may, of course, throw an exception, in which case the promise - // is broken. When compiled with -fno-exceptions, the framework will still detect when a - // recoverable exception was thrown inside of a continuation and will consider the promise - // broken even though a (presumably garbage) result was returned. - // - // If the returned promise is destroyed before the callback runs, the callback will be canceled - // (it will never run). - // - // Note that `then()` -- like all other Promise methods -- consumes the promise on which it is - // called, in the sense of move semantics. After returning, the original promise is no longer - // valid, but `then()` returns a new promise. - // - // *Advanced implementation tips:* Most users will never need to worry about the below, but - // it is good to be aware of. - // - // As an optimization, if the callback function `func` does _not_ return another promise, then - // execution of `func` itself may be delayed until its result is known to be needed. The - // expectation here is that `func` is just doing some transformation on the results, not - // scheduling any other actions, therefore the system doesn't need to be proactive about - // evaluating it. This way, a chain of trivial then() transformations can be executed all at - // once without repeatedly re-scheduling through the event loop. Use the `eagerlyEvaluate()` - // method to suppress this behavior. - // - // On the other hand, if `func` _does_ return another promise, then the system evaluates `func` - // as soon as possible, because the promise it returns might be for a newly-scheduled - // long-running asynchronous task. - // - // As another optimization, when a callback function registered with `then()` is actually - // scheduled, it is scheduled to occur immediately, preempting other work in the event queue. - // This allows a long chain of `then`s to execute all at once, improving cache locality by - // clustering operations on the same data. However, this implies that starvation can occur - // if a chain of `then()`s takes a very long time to execute without ever stopping to wait for - // actual I/O. To solve this, use `kj::evalLater()` to yield control; this way, all other events - // in the queue will get a chance to run before your callback is executed. - - Promise ignoreResult() KJ_WARN_UNUSED_RESULT { return then([](T&&) {}); } - // Convenience method to convert the promise to a void promise by ignoring the return value. - // - // You must still wait on the returned promise if you want the task to execute. - - template - Promise catch_(ErrorFunc&& errorHandler) KJ_WARN_UNUSED_RESULT; - // Equivalent to `.then(identityFunc, errorHandler)`, where `identifyFunc` is a function that - // just returns its input. - - T wait(WaitScope& waitScope); - // Run the event loop until the promise is fulfilled, then return its result. If the promise - // is rejected, throw an exception. - // - // wait() is primarily useful at the top level of a program -- typically, within the function - // that allocated the EventLoop. For example, a program that performs one or two RPCs and then - // exits would likely use wait() in its main() function to wait on each RPC. On the other hand, - // server-side code generally cannot use wait(), because it has to be able to accept multiple - // requests at once. - // - // If the promise is rejected, `wait()` throws an exception. If the program was compiled without - // exceptions (-fno-exceptions), this will usually abort. In this case you really should first - // use `then()` to set an appropriate handler for the exception case, so that the promise you - // actually wait on never throws. - // - // `waitScope` is an object proving that the caller is in a scope where wait() is allowed. By - // convention, any function which might call wait(), or which might call another function which - // might call wait(), must take `WaitScope&` as one of its parameters. This is needed for two - // reasons: - // * `wait()` is not allowed during an event callback, because event callbacks are themselves - // called during some other `wait()`, and such recursive `wait()`s would only be able to - // complete in LIFO order, which might mean that the outer `wait()` ends up waiting longer - // than it is supposed to. To prevent this, a `WaitScope` cannot be constructed or used during - // an event callback. - // * Since `wait()` runs the event loop, unrelated event callbacks may execute before `wait()` - // returns. This means that anyone calling `wait()` must be reentrant -- state may change - // around them in arbitrary ways. Therefore, callers really need to know if a function they - // are calling might wait(), and the `WaitScope&` parameter makes this clear. - // - // TODO(someday): Implement fibers, and let them call wait() even when they are handling an - // event. - - ForkedPromise fork() KJ_WARN_UNUSED_RESULT; - // Forks the promise, so that multiple different clients can independently wait on the result. - // `T` must be copy-constructable for this to work. Or, in the special case where `T` is - // `Own`, `U` must have a method `Own addRef()` which returns a new reference to the same - // (or an equivalent) object (probably implemented via reference counting). - - _::SplitTuplePromise split(); - // Split a promise for a tuple into a tuple of promises. - // - // E.g. if you have `Promise>`, `split()` returns - // `kj::Tuple, Promise>`. - - Promise exclusiveJoin(Promise&& other) KJ_WARN_UNUSED_RESULT; - // Return a new promise that resolves when either the original promise resolves or `other` - // resolves (whichever comes first). The promise that didn't resolve first is canceled. - - // TODO(someday): inclusiveJoin(), or perhaps just join(), which waits for both completions - // and produces a tuple? - - template - Promise attach(Attachments&&... attachments) KJ_WARN_UNUSED_RESULT; - // "Attaches" one or more movable objects (often, Owns) to the promise, such that they will - // be destroyed when the promise resolves. This is useful when a promise's callback contains - // pointers into some object and you want to make sure the object still exists when the callback - // runs -- after calling then(), use attach() to add necessary objects to the result. - - template - Promise eagerlyEvaluate(ErrorFunc&& errorHandler) KJ_WARN_UNUSED_RESULT; - Promise eagerlyEvaluate(decltype(nullptr)) KJ_WARN_UNUSED_RESULT; - // Force eager evaluation of this promise. Use this if you are going to hold on to the promise - // for awhile without consuming the result, but you want to make sure that the system actually - // processes it. - // - // `errorHandler` is a function that takes `kj::Exception&&`, like the second parameter to - // `then()`, except that it must return void. We make you specify this because otherwise it's - // easy to forget to handle errors in a promise that you never use. You may specify nullptr for - // the error handler if you are sure that ignoring errors is fine, or if you know that you'll - // eventually wait on the promise somewhere. - - template - void detach(ErrorFunc&& errorHandler); - // Allows the promise to continue running in the background until it completes or the - // `EventLoop` is destroyed. Be careful when using this: since you can no longer cancel this - // promise, you need to make sure that the promise owns all the objects it touches or make sure - // those objects outlive the EventLoop. - // - // `errorHandler` is a function that takes `kj::Exception&&`, like the second parameter to - // `then()`, except that it must return void. - // - // This function exists mainly to implement the Cap'n Proto requirement that RPC calls cannot be - // canceled unless the callee explicitly permits it. - - kj::String trace(); - // Returns a dump of debug info about this promise. Not for production use. Requires RTTI. - // This method does NOT consume the promise as other methods do. - -private: - Promise(bool, Own<_::PromiseNode>&& node): PromiseBase(kj::mv(node)) {} - // Second parameter prevent ambiguity with immediate-value constructor. - - template - friend class Promise; - friend class EventLoop; - template - friend Promise newAdaptedPromise(Params&&... adapterConstructorParams); - template - friend PromiseFulfillerPair newPromiseAndFulfiller(); - template - friend class _::ForkHub; - friend class _::TaskSetImpl; - friend Promise _::yield(); - friend class _::NeverDone; - template - friend Promise> joinPromises(Array>&& promises); - friend Promise joinPromises(Array>&& promises); -}; - -template -class ForkedPromise { - // The result of `Promise::fork()` and `EventLoop::fork()`. Allows branches to be created. - // Like `Promise`, this is a pass-by-move type. - -public: - inline ForkedPromise(decltype(nullptr)) {} - - Promise addBranch(); - // Add a new branch to the fork. The branch is equivalent to the original promise. - -private: - Own<_::ForkHub<_::FixVoid>> hub; - - inline ForkedPromise(bool, Own<_::ForkHub<_::FixVoid>>&& hub): hub(kj::mv(hub)) {} - - friend class Promise; - friend class EventLoop; -}; - -constexpr _::Void READY_NOW = _::Void(); -// Use this when you need a Promise that is already fulfilled -- this value can be implicitly -// cast to `Promise`. - -constexpr _::NeverDone NEVER_DONE = _::NeverDone(); -// The opposite of `READY_NOW`, return this when the promise should never resolve. This can be -// implicitly converted to any promise type. You may also call `NEVER_DONE.wait()` to wait -// forever (useful for servers). - -template -PromiseForResult evalLater(Func&& func) KJ_WARN_UNUSED_RESULT; -// Schedule for the given zero-parameter function to be executed in the event loop at some -// point in the near future. Returns a Promise for its result -- or, if `func()` itself returns -// a promise, `evalLater()` returns a Promise for the result of resolving that promise. -// -// Example usage: -// Promise x = evalLater([]() { return 123; }); -// -// The above is exactly equivalent to: -// Promise x = Promise(READY_NOW).then([]() { return 123; }); -// -// If the returned promise is destroyed before the callback runs, the callback will be canceled -// (never called). -// -// If you schedule several evaluations with `evalLater` during the same callback, they are -// guaranteed to be executed in order. - -template -PromiseForResult evalNow(Func&& func) KJ_WARN_UNUSED_RESULT; -// Run `func()` and return a promise for its result. `func()` executes before `evalNow()` returns. -// If `func()` throws an exception, the exception is caught and wrapped in a promise -- this is the -// main reason why `evalNow()` is useful. - -template -Promise> joinPromises(Array>&& promises); -// Join an array of promises into a promise for an array. - -// ======================================================================================= -// Hack for creating a lambda that holds an owned pointer. - -template -class CaptureByMove { -public: - inline CaptureByMove(Func&& func, MovedParam&& param) - : func(kj::mv(func)), param(kj::mv(param)) {} - - template - inline auto operator()(Params&&... params) - -> decltype(kj::instance()(kj::instance(), kj::fwd(params)...)) { - return func(kj::mv(param), kj::fwd(params)...); - } - -private: - Func func; - MovedParam param; -}; - -template -inline CaptureByMove> mvCapture(MovedParam&& param, Func&& func) { - // Hack to create a "lambda" which captures a variable by moving it rather than copying or - // referencing. C++14 generalized captures should make this obsolete, but for now in C++11 this - // is commonly needed for Promise continuations that own their state. Example usage: - // - // Own ptr = makeFoo(); - // Promise promise = callRpc(); - // promise.then(mvCapture(ptr, [](Own&& ptr, int result) { - // return ptr->finish(result); - // })); - - return CaptureByMove>(kj::fwd(func), kj::mv(param)); -} - -// ======================================================================================= -// Advanced promise construction - -template -class PromiseFulfiller { - // A callback which can be used to fulfill a promise. Only the first call to fulfill() or - // reject() matters; subsequent calls are ignored. - -public: - virtual void fulfill(T&& value) = 0; - // Fulfill the promise with the given value. - - virtual void reject(Exception&& exception) = 0; - // Reject the promise with an error. - - virtual bool isWaiting() = 0; - // Returns true if the promise is still unfulfilled and someone is potentially waiting for it. - // Returns false if fulfill()/reject() has already been called *or* if the promise to be - // fulfilled has been discarded and therefore the result will never be used anyway. - - template - bool rejectIfThrows(Func&& func); - // Call the function (with no arguments) and return true. If an exception is thrown, call - // `fulfiller.reject()` and then return false. When compiled with exceptions disabled, - // non-fatal exceptions are still detected and handled correctly. -}; - -template <> -class PromiseFulfiller { - // Specialization of PromiseFulfiller for void promises. See PromiseFulfiller. - -public: - virtual void fulfill(_::Void&& value = _::Void()) = 0; - // Call with zero parameters. The parameter is a dummy that only exists so that subclasses don't - // have to specialize for . - - virtual void reject(Exception&& exception) = 0; - virtual bool isWaiting() = 0; - - template - bool rejectIfThrows(Func&& func); -}; - -template -Promise newAdaptedPromise(Params&&... adapterConstructorParams); -// Creates a new promise which owns an instance of `Adapter` which encapsulates the operation -// that will eventually fulfill the promise. This is primarily useful for adapting non-KJ -// asynchronous APIs to use promises. -// -// An instance of `Adapter` will be allocated and owned by the returned `Promise`. A -// `PromiseFulfiller&` will be passed as the first parameter to the adapter's constructor, -// and `adapterConstructorParams` will be forwarded as the subsequent parameters. The adapter -// is expected to perform some asynchronous operation and call the `PromiseFulfiller` once -// it is finished. -// -// The adapter is destroyed when its owning Promise is destroyed. This may occur before the -// Promise has been fulfilled. In this case, the adapter's destructor should cancel the -// asynchronous operation. Once the adapter is destroyed, the fulfillment callback cannot be -// called. -// -// An adapter implementation should be carefully written to ensure that it cannot accidentally -// be left unfulfilled permanently because of an exception. Consider making liberal use of -// `PromiseFulfiller::rejectIfThrows()`. - -template -struct PromiseFulfillerPair { - Promise<_::JoinPromises> promise; - Own> fulfiller; -}; - -template -PromiseFulfillerPair newPromiseAndFulfiller(); -// Construct a Promise and a separate PromiseFulfiller which can be used to fulfill the promise. -// If the PromiseFulfiller is destroyed before either of its methods are called, the Promise is -// implicitly rejected. -// -// Although this function is easier to use than `newAdaptedPromise()`, it has the serious drawback -// that there is no way to handle cancellation (i.e. detect when the Promise is discarded). -// -// You can arrange to fulfill a promise with another promise by using a promise type for T. E.g. -// `newPromiseAndFulfiller>()` will produce a promise of type `Promise` but the -// fulfiller will be of type `PromiseFulfiller>`. Thus you pass a `Promise` to the -// `fulfill()` callback, and the promises are chained. - -// ======================================================================================= -// TaskSet - -class TaskSet { - // Holds a collection of Promises and ensures that each executes to completion. Memory - // associated with each promise is automatically freed when the promise completes. Destroying - // the TaskSet itself automatically cancels all unfinished promises. - // - // This is useful for "daemon" objects that perform background tasks which aren't intended to - // fulfill any particular external promise, but which may need to be canceled (and thus can't - // use `Promise::detach()`). The daemon object holds a TaskSet to collect these tasks it is - // working on. This way, if the daemon itself is destroyed, the TaskSet is detroyed as well, - // and everything the daemon is doing is canceled. - -public: - class ErrorHandler { - public: - virtual void taskFailed(kj::Exception&& exception) = 0; - }; - - TaskSet(ErrorHandler& errorHandler); - // `loop` will be used to wait on promises. `errorHandler` will be executed any time a task - // throws an exception, and will execute within the given EventLoop. - - ~TaskSet() noexcept(false); - - void add(Promise&& promise); - - kj::String trace(); - // Return debug info about all promises currently in the TaskSet. - -private: - Own<_::TaskSetImpl> impl; -}; - -// ======================================================================================= -// The EventLoop class - -class EventPort { - // Interfaces between an `EventLoop` and events originating from outside of the loop's thread. - // All such events come in through the `EventPort` implementation. - // - // An `EventPort` implementation may interface with low-level operating system APIs and/or other - // threads. You can also write an `EventPort` which wraps some other (non-KJ) event loop - // framework, allowing the two to coexist in a single thread. - -public: - virtual bool wait() = 0; - // Wait for an external event to arrive, sleeping if necessary. Once at least one event has - // arrived, queue it to the event loop (e.g. by fulfilling a promise) and return. - // - // This is called during `Promise::wait()` whenever the event queue becomes empty, in order to - // wait for new events to populate the queue. - // - // It is safe to return even if nothing has actually been queued, so long as calling `wait()` in - // a loop will eventually sleep. (That is to say, false positives are fine.) - // - // Returns true if wake() has been called from another thread. (Precisely, returns true if - // no previous call to wait `wait()` nor `poll()` has returned true since `wake()` was last - // called.) - - virtual bool poll() = 0; - // Check if any external events have arrived, but do not sleep. If any events have arrived, - // add them to the event queue (e.g. by fulfilling promises) before returning. - // - // This may be called during `Promise::wait()` when the EventLoop has been executing for a while - // without a break but is still non-empty. - // - // Returns true if wake() has been called from another thread. (Precisely, returns true if - // no previous call to wait `wait()` nor `poll()` has returned true since `wake()` was last - // called.) - - virtual void setRunnable(bool runnable); - // Called to notify the `EventPort` when the `EventLoop` has work to do; specifically when it - // transitions from empty -> runnable or runnable -> empty. This is typically useful when - // integrating with an external event loop; if the loop is currently runnable then you should - // arrange to call run() on it soon. The default implementation does nothing. - - virtual void wake() const; - // Wake up the EventPort's thread from another thread. - // - // Unlike all other methods on this interface, `wake()` may be called from another thread, hence - // it is `const`. - // - // Technically speaking, `wake()` causes the target thread to cease sleeping and not to sleep - // again until `wait()` or `poll()` has returned true at least once. - // - // The default implementation throws an UNIMPLEMENTED exception. -}; - -class EventLoop { - // Represents a queue of events being executed in a loop. Most code won't interact with - // EventLoop directly, but instead use `Promise`s to interact with it indirectly. See the - // documentation for `Promise`. - // - // Each thread can have at most one current EventLoop. To make an `EventLoop` current for - // the thread, create a `WaitScope`. Async APIs require that the thread has a current EventLoop, - // or they will throw exceptions. APIs that use `Promise::wait()` additionally must explicitly - // be passed a reference to the `WaitScope` to make the caller aware that they might block. - // - // Generally, you will want to construct an `EventLoop` at the top level of your program, e.g. - // in the main() function, or in the start function of a thread. You can then use it to - // construct some promises and wait on the result. Example: - // - // int main() { - // // `loop` becomes the official EventLoop for the thread. - // MyEventPort eventPort; - // EventLoop loop(eventPort); - // - // // Now we can call an async function. - // Promise textPromise = getHttp("http://example.com"); - // - // // And we can wait for the promise to complete. Note that you can only use `wait()` - // // from the top level, not from inside a promise callback. - // String text = textPromise.wait(); - // print(text); - // return 0; - // } - // - // Most applications that do I/O will prefer to use `setupAsyncIo()` from `async-io.h` rather - // than allocate an `EventLoop` directly. - -public: - EventLoop(); - // Construct an `EventLoop` which does not receive external events at all. - - explicit EventLoop(EventPort& port); - // Construct an `EventLoop` which receives external events through the given `EventPort`. - - ~EventLoop() noexcept(false); - - void run(uint maxTurnCount = maxValue); - // Run the event loop for `maxTurnCount` turns or until there is nothing left to be done, - // whichever comes first. This never calls the `EventPort`'s `sleep()` or `poll()`. It will - // call the `EventPort`'s `setRunnable(false)` if the queue becomes empty. - - bool isRunnable(); - // Returns true if run() would currently do anything, or false if the queue is empty. - -private: - EventPort& port; - - bool running = false; - // True while looping -- wait() is then not allowed. - - bool lastRunnableState = false; - // What did we last pass to port.setRunnable()? - - _::Event* head = nullptr; - _::Event** tail = &head; - _::Event** depthFirstInsertPoint = &head; - - Own<_::TaskSetImpl> daemons; - - bool turn(); - void setRunnable(bool runnable); - void enterScope(); - void leaveScope(); - - friend void _::detach(kj::Promise&& promise); - friend void _::waitImpl(Own<_::PromiseNode>&& node, _::ExceptionOrValue& result, - WaitScope& waitScope); - friend class _::Event; - friend class WaitScope; -}; - -class WaitScope { - // Represents a scope in which asynchronous programming can occur. A `WaitScope` should usually - // be allocated on the stack and serves two purposes: - // * While the `WaitScope` exists, its `EventLoop` is registered as the current loop for the - // thread. Most operations dealing with `Promise` (including all of its methods) do not work - // unless the thread has a current `EventLoop`. - // * `WaitScope` may be passed to `Promise::wait()` to synchronously wait for a particular - // promise to complete. See `Promise::wait()` for an extended discussion. - -public: - inline explicit WaitScope(EventLoop& loop): loop(loop) { loop.enterScope(); } - inline ~WaitScope() { loop.leaveScope(); } - KJ_DISALLOW_COPY(WaitScope); - -private: - EventLoop& loop; - friend class EventLoop; - friend void _::waitImpl(Own<_::PromiseNode>&& node, _::ExceptionOrValue& result, - WaitScope& waitScope); -}; - -} // namespace kj - -#include "async-inl.h" - -#endif // KJ_ASYNC_H_ diff --git a/phonelibs/capnp-cpp/include/kj/common.h b/phonelibs/capnp-cpp/include/kj/common.h deleted file mode 100644 index 4a908ae000..0000000000 --- a/phonelibs/capnp-cpp/include/kj/common.h +++ /dev/null @@ -1,1400 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// Header that should be #included by everyone. -// -// This defines very simple utilities that are widely applicable. - -#ifndef KJ_COMMON_H_ -#define KJ_COMMON_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#ifndef KJ_NO_COMPILER_CHECK -#if __cplusplus < 201103L && !__CDT_PARSER__ && !_MSC_VER - #error "This code requires C++11. Either your compiler does not support it or it is not enabled." - #ifdef __GNUC__ - // Compiler claims compatibility with GCC, so presumably supports -std. - #error "Pass -std=c++11 on the compiler command line to enable C++11." - #endif -#endif - -#ifdef __GNUC__ - #if __clang__ - #if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 2) - #warning "This library requires at least Clang 3.2." - #elif defined(__apple_build_version__) && __apple_build_version__ <= 4250028 - #warning "This library requires at least Clang 3.2. XCode 4.6's Clang, which claims to be "\ - "version 4.2 (wat?), is actually built from some random SVN revision between 3.1 "\ - "and 3.2. Unfortunately, it is insufficient for compiling this library. You can "\ - "download the real Clang 3.2 (or newer) from the Clang web site. Step-by-step "\ - "instructions can be found in Cap'n Proto's documentation: "\ - "http://kentonv.github.io/capnproto/install.html#clang_32_on_mac_osx" - #elif __cplusplus >= 201103L && !__has_include() - #warning "Your compiler supports C++11 but your C++ standard library does not. If your "\ - "system has libc++ installed (as should be the case on e.g. Mac OSX), try adding "\ - "-stdlib=libc++ to your CXXFLAGS." - #endif - #else - #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 7) - #warning "This library requires at least GCC 4.7." - #endif - #endif -#elif defined(_MSC_VER) - #if _MSC_VER < 1900 - #error "You need Visual Studio 2015 or better to compile this code." - #endif -#else - #warning "I don't recognize your compiler. As of this writing, Clang and GCC are the only "\ - "known compilers with enough C++11 support for this library. "\ - "#define KJ_NO_COMPILER_CHECK to make this warning go away." -#endif -#endif - -#include -#include - -#if __linux__ && __cplusplus > 201200L -// Hack around stdlib bug with C++14 that exists on some Linux systems. -// Apparently in this mode the C library decides not to define gets() but the C++ library still -// tries to import it into the std namespace. This bug has been fixed at the source but is still -// widely present in the wild e.g. on Ubuntu 14.04. -#undef _GLIBCXX_HAVE_GETS -#endif - -#if defined(_MSC_VER) -#ifndef NOMINMAX -#define NOMINMAX 1 -#endif -#include // __popcnt -#endif - -// ======================================================================================= - -namespace kj { - -typedef unsigned int uint; -typedef unsigned char byte; - -// ======================================================================================= -// Common macros, especially for common yet compiler-specific features. - -// Detect whether RTTI and exceptions are enabled, assuming they are unless we have specific -// evidence to the contrary. Clients can always define KJ_NO_RTTI or KJ_NO_EXCEPTIONS explicitly -// to override these checks. -#ifdef __GNUC__ - #if !defined(KJ_NO_RTTI) && !__GXX_RTTI - #define KJ_NO_RTTI 1 - #endif - #if !defined(KJ_NO_EXCEPTIONS) && !__EXCEPTIONS - #define KJ_NO_EXCEPTIONS 1 - #endif -#elif defined(_MSC_VER) - #if !defined(KJ_NO_RTTI) && !defined(_CPPRTTI) - #define KJ_NO_RTTI 1 - #endif - #if !defined(KJ_NO_EXCEPTIONS) && !defined(_CPPUNWIND) - #define KJ_NO_EXCEPTIONS 1 - #endif -#endif - -#if !defined(KJ_DEBUG) && !defined(KJ_NDEBUG) -// Heuristically decide whether to enable debug mode. If DEBUG or NDEBUG is defined, use that. -// Otherwise, fall back to checking whether optimization is enabled. -#if defined(DEBUG) || defined(_DEBUG) -#define KJ_DEBUG -#elif defined(NDEBUG) -#define KJ_NDEBUG -#elif __OPTIMIZE__ -#define KJ_NDEBUG -#else -#define KJ_DEBUG -#endif -#endif - -#define KJ_DISALLOW_COPY(classname) \ - classname(const classname&) = delete; \ - classname& operator=(const classname&) = delete -// Deletes the implicit copy constructor and assignment operator. - -#ifdef __GNUC__ -#define KJ_LIKELY(condition) __builtin_expect(condition, true) -#define KJ_UNLIKELY(condition) __builtin_expect(condition, false) -// Branch prediction macros. Evaluates to the condition given, but also tells the compiler that we -// expect the condition to be true/false enough of the time that it's worth hard-coding branch -// prediction. -#else -#define KJ_LIKELY(condition) (condition) -#define KJ_UNLIKELY(condition) (condition) -#endif - -#if defined(KJ_DEBUG) || __NO_INLINE__ -#define KJ_ALWAYS_INLINE(...) inline __VA_ARGS__ -// Don't force inline in debug mode. -#else -#if defined(_MSC_VER) -#define KJ_ALWAYS_INLINE(...) __forceinline __VA_ARGS__ -#else -#define KJ_ALWAYS_INLINE(...) inline __VA_ARGS__ __attribute__((always_inline)) -#endif -// Force a function to always be inlined. Apply only to the prototype, not to the definition. -#endif - -#if defined(_MSC_VER) -#define KJ_NOINLINE __declspec(noinline) -#else -#define KJ_NOINLINE __attribute__((noinline)) -#endif - -#if defined(_MSC_VER) -#define KJ_NORETURN(prototype) __declspec(noreturn) prototype -#define KJ_UNUSED -#define KJ_WARN_UNUSED_RESULT -// TODO(msvc): KJ_WARN_UNUSED_RESULT can use _Check_return_ on MSVC, but it's a prefix, so -// wrapping the whole prototype is needed. http://msdn.microsoft.com/en-us/library/jj159529.aspx -// Similarly, KJ_UNUSED could use __pragma(warning(suppress:...)), but again that's a prefix. -#else -#define KJ_NORETURN(prototype) prototype __attribute__((noreturn)) -#define KJ_UNUSED __attribute__((unused)) -#define KJ_WARN_UNUSED_RESULT __attribute__((warn_unused_result)) -#endif - -#if __clang__ -#define KJ_UNUSED_MEMBER __attribute__((unused)) -// Inhibits "unused" warning for member variables. Only Clang produces such a warning, while GCC -// complains if the attribute is set on members. -#else -#define KJ_UNUSED_MEMBER -#endif - -#if __clang__ -#define KJ_DEPRECATED(reason) \ - __attribute__((deprecated(reason))) -#define KJ_UNAVAILABLE(reason) \ - __attribute__((unavailable(reason))) -#elif __GNUC__ -#define KJ_DEPRECATED(reason) \ - __attribute__((deprecated)) -#define KJ_UNAVAILABLE(reason) -#else -#define KJ_DEPRECATED(reason) -#define KJ_UNAVAILABLE(reason) -// TODO(msvc): Again, here, MSVC prefers a prefix, __declspec(deprecated). -#endif - -namespace _ { // private - -KJ_NORETURN(void inlineRequireFailure( - const char* file, int line, const char* expectation, const char* macroArgs, - const char* message = nullptr)); - -KJ_NORETURN(void unreachable()); - -} // namespace _ (private) - -#ifdef KJ_DEBUG -#if _MSC_VER -#define KJ_IREQUIRE(condition, ...) \ - if (KJ_LIKELY(condition)); else ::kj::_::inlineRequireFailure( \ - __FILE__, __LINE__, #condition, "" #__VA_ARGS__, __VA_ARGS__) -// Version of KJ_DREQUIRE() which is safe to use in headers that are #included by users. Used to -// check preconditions inside inline methods. KJ_IREQUIRE is particularly useful in that -// it will be enabled depending on whether the application is compiled in debug mode rather than -// whether libkj is. -#else -#define KJ_IREQUIRE(condition, ...) \ - if (KJ_LIKELY(condition)); else ::kj::_::inlineRequireFailure( \ - __FILE__, __LINE__, #condition, #__VA_ARGS__, ##__VA_ARGS__) -// Version of KJ_DREQUIRE() which is safe to use in headers that are #included by users. Used to -// check preconditions inside inline methods. KJ_IREQUIRE is particularly useful in that -// it will be enabled depending on whether the application is compiled in debug mode rather than -// whether libkj is. -#endif -#else -#define KJ_IREQUIRE(condition, ...) -#endif - -#define KJ_IASSERT KJ_IREQUIRE - -#define KJ_UNREACHABLE ::kj::_::unreachable(); -// Put this on code paths that cannot be reached to suppress compiler warnings about missing -// returns. - -#if __clang__ -#define KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT -#else -#define KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT KJ_UNREACHABLE -#endif - -// #define KJ_STACK_ARRAY(type, name, size, minStack, maxStack) -// -// Allocate an array, preferably on the stack, unless it is too big. On GCC this will use -// variable-sized arrays. For other compilers we could just use a fixed-size array. `minStack` -// is the stack array size to use if variable-width arrays are not supported. `maxStack` is the -// maximum stack array size if variable-width arrays *are* supported. -#if __GNUC__ && !__clang__ -#define KJ_STACK_ARRAY(type, name, size, minStack, maxStack) \ - size_t name##_size = (size); \ - bool name##_isOnStack = name##_size <= (maxStack); \ - type name##_stack[name##_isOnStack ? size : 0]; \ - ::kj::Array name##_heap = name##_isOnStack ? \ - nullptr : kj::heapArray(name##_size); \ - ::kj::ArrayPtr name = name##_isOnStack ? \ - kj::arrayPtr(name##_stack, name##_size) : name##_heap -#else -#define KJ_STACK_ARRAY(type, name, size, minStack, maxStack) \ - size_t name##_size = (size); \ - bool name##_isOnStack = name##_size <= (minStack); \ - type name##_stack[minStack]; \ - ::kj::Array name##_heap = name##_isOnStack ? \ - nullptr : kj::heapArray(name##_size); \ - ::kj::ArrayPtr name = name##_isOnStack ? \ - kj::arrayPtr(name##_stack, name##_size) : name##_heap -#endif - -#define KJ_CONCAT_(x, y) x##y -#define KJ_CONCAT(x, y) KJ_CONCAT_(x, y) -#define KJ_UNIQUE_NAME(prefix) KJ_CONCAT(prefix, __LINE__) -// Create a unique identifier name. We use concatenate __LINE__ rather than __COUNTER__ so that -// the name can be used multiple times in the same macro. - -#if _MSC_VER - -#define KJ_CONSTEXPR(...) __VA_ARGS__ -// Use in cases where MSVC barfs on constexpr. A replacement keyword (e.g. "const") can be -// provided, or just leave blank to remove the keyword entirely. -// -// TODO(msvc): Remove this hack once MSVC fully supports constexpr. - -#ifndef __restrict__ -#define __restrict__ __restrict -// TODO(msvc): Would it be better to define a KJ_RESTRICT macro? -#endif - -#pragma warning(disable: 4521 4522) -// This warning complains when there are two copy constructors, one for a const reference and -// one for a non-const reference. It is often quite necessary to do this in wrapper templates, -// therefore this warning is dumb and we disable it. - -#pragma warning(disable: 4458) -// Warns when a parameter name shadows a class member. Unfortunately my code does this a lot, -// since I don't use a special name format for members. - -#else // _MSC_VER -#define KJ_CONSTEXPR(...) constexpr -#endif - -// ======================================================================================= -// Template metaprogramming helpers. - -template struct NoInfer_ { typedef T Type; }; -template using NoInfer = typename NoInfer_::Type; -// Use NoInfer::Type in place of T for a template function parameter to prevent inference of -// the type based on the parameter value. - -template struct RemoveConst_ { typedef T Type; }; -template struct RemoveConst_ { typedef T Type; }; -template using RemoveConst = typename RemoveConst_::Type; - -template struct IsLvalueReference_ { static constexpr bool value = false; }; -template struct IsLvalueReference_ { static constexpr bool value = true; }; -template -inline constexpr bool isLvalueReference() { return IsLvalueReference_::value; } - -template struct Decay_ { typedef T Type; }; -template struct Decay_ { typedef typename Decay_::Type Type; }; -template struct Decay_ { typedef typename Decay_::Type Type; }; -template struct Decay_ { typedef typename Decay_::Type Type; }; -template struct Decay_ { typedef typename Decay_::Type Type; }; -template struct Decay_ { typedef typename Decay_::Type Type; }; -template struct Decay_ { typedef typename Decay_::Type Type; }; -template struct Decay_ { typedef typename Decay_::Type Type; }; -template struct Decay_ { typedef typename Decay_::Type Type; }; -template using Decay = typename Decay_::Type; - -template struct EnableIf_; -template <> struct EnableIf_ { typedef void Type; }; -template using EnableIf = typename EnableIf_::Type; -// Use like: -// -// template ()> -// void func(T&& t); - -template struct VoidSfinae_ { using Type = void; }; -template using VoidSfinae = typename VoidSfinae_::Type; -// Note: VoidSfinae is std::void_t from C++17. - -template -T instance() noexcept; -// Like std::declval, but doesn't transform T into an rvalue reference. If you want that, specify -// instance(). - -struct DisallowConstCopy { - // Inherit from this, or declare a member variable of this type, to prevent the class from being - // copyable from a const reference -- instead, it will only be copyable from non-const references. - // This is useful for enforcing transitive constness of contained pointers. - // - // For example, say you have a type T which contains a pointer. T has non-const methods which - // modify the value at that pointer, but T's const methods are designed to allow reading only. - // Unfortunately, if T has a regular copy constructor, someone can simply make a copy of T and - // then use it to modify the pointed-to value. However, if T inherits DisallowConstCopy, then - // callers will only be able to copy non-const instances of T. Ideally, there is some - // parallel type ImmutableT which is like a version of T that only has const methods, and can - // be copied from a const T. - // - // Note that due to C++ rules about implicit copy constructors and assignment operators, any - // type that contains or inherits from a type that disallows const copies will also automatically - // disallow const copies. Hey, cool, that's exactly what we want. - -#if CAPNP_DEBUG_TYPES - // Alas! Declaring a defaulted non-const copy constructor tickles a bug which causes GCC and - // Clang to disagree on ABI, using different calling conventions to pass this type, leading to - // immediate segfaults. See: - // https://bugs.llvm.org/show_bug.cgi?id=23764 - // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58074 - // - // Because of this, we can't use this technique. We guard it by CAPNP_DEBUG_TYPES so that it - // still applies to the Cap'n Proto developers during internal testing. - - DisallowConstCopy() = default; - DisallowConstCopy(DisallowConstCopy&) = default; - DisallowConstCopy(DisallowConstCopy&&) = default; - DisallowConstCopy& operator=(DisallowConstCopy&) = default; - DisallowConstCopy& operator=(DisallowConstCopy&&) = default; -#endif -}; - -#if _MSC_VER - -#define KJ_CPCAP(obj) obj=::kj::cp(obj) -// TODO(msvc): MSVC refuses to invoke non-const versions of copy constructors in by-value lambda -// captures. Wrap your captured object in this macro to force the compiler to perform a copy. -// Example: -// -// struct Foo: DisallowConstCopy {}; -// Foo foo; -// auto lambda = [KJ_CPCAP(foo)] {}; - -#else - -#define KJ_CPCAP(obj) obj -// Clang and gcc both already perform copy capturing correctly with non-const copy constructors. - -#endif - -template -struct DisallowConstCopyIfNotConst: public DisallowConstCopy { - // Inherit from this when implementing a template that contains a pointer to T and which should - // enforce transitive constness. If T is a const type, this has no effect. Otherwise, it is - // an alias for DisallowConstCopy. -}; - -template -struct DisallowConstCopyIfNotConst {}; - -template struct IsConst_ { static constexpr bool value = false; }; -template struct IsConst_ { static constexpr bool value = true; }; -template constexpr bool isConst() { return IsConst_::value; } - -template struct EnableIfNotConst_ { typedef T Type; }; -template struct EnableIfNotConst_; -template using EnableIfNotConst = typename EnableIfNotConst_::Type; - -template struct EnableIfConst_; -template struct EnableIfConst_ { typedef T Type; }; -template using EnableIfConst = typename EnableIfConst_::Type; - -template struct RemoveConstOrDisable_ { struct Type; }; -template struct RemoveConstOrDisable_ { typedef T Type; }; -template using RemoveConstOrDisable = typename RemoveConstOrDisable_::Type; - -template struct IsReference_ { static constexpr bool value = false; }; -template struct IsReference_ { static constexpr bool value = true; }; -template constexpr bool isReference() { return IsReference_::value; } - -template -struct PropagateConst_ { typedef To Type; }; -template -struct PropagateConst_ { typedef const To Type; }; -template -using PropagateConst = typename PropagateConst_::Type; - -namespace _ { // private - -template -T refIfLvalue(T&&); - -} // namespace _ (private) - -#define KJ_DECLTYPE_REF(exp) decltype(::kj::_::refIfLvalue(exp)) -// Like decltype(exp), but if exp is an lvalue, produces a reference type. -// -// int i; -// decltype(i) i1(i); // i1 has type int. -// KJ_DECLTYPE_REF(i + 1) i2(i + 1); // i2 has type int. -// KJ_DECLTYPE_REF(i) i3(i); // i3 has type int&. -// KJ_DECLTYPE_REF(kj::mv(i)) i4(kj::mv(i)); // i4 has type int. - -template -struct CanConvert_ { - static int sfinae(T); - static bool sfinae(...); -}; - -template -constexpr bool canConvert() { - return sizeof(CanConvert_::sfinae(instance())) == sizeof(int); -} - -#if __GNUC__ && !__clang__ && __GNUC__ < 5 -template -constexpr bool canMemcpy() { - // Returns true if T can be copied using memcpy instead of using the copy constructor or - // assignment operator. - - // GCC 4 does not have __is_trivially_constructible and friends, and there doesn't seem to be - // any reliable alternative. __has_trivial_copy() and __has_trivial_assign() return the right - // thing at one point but later on they changed such that a deleted copy constructor was - // considered "trivial" (apparently technically correct, though useless). So, on GCC 4 we give up - // and assume we can't memcpy() at all, and must explicitly copy-construct everything. - return false; -} -#define KJ_ASSERT_CAN_MEMCPY(T) -#else -template -constexpr bool canMemcpy() { - // Returns true if T can be copied using memcpy instead of using the copy constructor or - // assignment operator. - - return __is_trivially_constructible(T, const T&) && __is_trivially_assignable(T, const T&); -} -#define KJ_ASSERT_CAN_MEMCPY(T) \ - static_assert(kj::canMemcpy(), "this code expects this type to be memcpy()-able"); -#endif - -// ======================================================================================= -// Equivalents to std::move() and std::forward(), since these are very commonly needed and the -// std header pulls in lots of other stuff. -// -// We use abbreviated names mv and fwd because these helpers (especially mv) are so commonly used -// that the cost of typing more letters outweighs the cost of being slightly harder to understand -// when first encountered. - -template constexpr T&& mv(T& t) noexcept { return static_cast(t); } -template constexpr T&& fwd(NoInfer& t) noexcept { return static_cast(t); } - -template constexpr T cp(T& t) noexcept { return t; } -template constexpr T cp(const T& t) noexcept { return t; } -// Useful to force a copy, particularly to pass into a function that expects T&&. - -template struct ChooseType_; -template struct ChooseType_ { typedef T Type; }; -template struct ChooseType_ { typedef T Type; }; -template struct ChooseType_ { typedef U Type; }; - -template -using WiderType = typename ChooseType_= sizeof(U)>::Type; - -template -inline constexpr auto min(T&& a, U&& b) -> WiderType, Decay> { - return a < b ? WiderType, Decay>(a) : WiderType, Decay>(b); -} - -template -inline constexpr auto max(T&& a, U&& b) -> WiderType, Decay> { - return a > b ? WiderType, Decay>(a) : WiderType, Decay>(b); -} - -template -inline constexpr size_t size(T (&arr)[s]) { return s; } -template -inline constexpr size_t size(T&& arr) { return arr.size(); } -// Returns the size of the parameter, whether the parameter is a regular C array or a container -// with a `.size()` method. - -class MaxValue_ { -private: - template - inline constexpr T maxSigned() const { - return (1ull << (sizeof(T) * 8 - 1)) - 1; - } - template - inline constexpr T maxUnsigned() const { - return ~static_cast(0u); - } - -public: -#define _kJ_HANDLE_TYPE(T) \ - inline constexpr operator signed T() const { return MaxValue_::maxSigned < signed T>(); } \ - inline constexpr operator unsigned T() const { return MaxValue_::maxUnsigned(); } - _kJ_HANDLE_TYPE(char) - _kJ_HANDLE_TYPE(short) - _kJ_HANDLE_TYPE(int) - _kJ_HANDLE_TYPE(long) - _kJ_HANDLE_TYPE(long long) -#undef _kJ_HANDLE_TYPE - - inline constexpr operator char() const { - // `char` is different from both `signed char` and `unsigned char`, and may be signed or - // unsigned on different platforms. Ugh. - return char(-1) < 0 ? MaxValue_::maxSigned() - : MaxValue_::maxUnsigned(); - } -}; - -class MinValue_ { -private: - template - inline constexpr T minSigned() const { - return 1ull << (sizeof(T) * 8 - 1); - } - template - inline constexpr T minUnsigned() const { - return 0u; - } - -public: -#define _kJ_HANDLE_TYPE(T) \ - inline constexpr operator signed T() const { return MinValue_::minSigned < signed T>(); } \ - inline constexpr operator unsigned T() const { return MinValue_::minUnsigned(); } - _kJ_HANDLE_TYPE(char) - _kJ_HANDLE_TYPE(short) - _kJ_HANDLE_TYPE(int) - _kJ_HANDLE_TYPE(long) - _kJ_HANDLE_TYPE(long long) -#undef _kJ_HANDLE_TYPE - - inline constexpr operator char() const { - // `char` is different from both `signed char` and `unsigned char`, and may be signed or - // unsigned on different platforms. Ugh. - return char(-1) < 0 ? MinValue_::minSigned() - : MinValue_::minUnsigned(); - } -}; - -static KJ_CONSTEXPR(const) MaxValue_ maxValue = MaxValue_(); -// A special constant which, when cast to an integer type, takes on the maximum possible value of -// that type. This is useful to use as e.g. a parameter to a function because it will be robust -// in the face of changes to the parameter's type. -// -// `char` is not supported, but `signed char` and `unsigned char` are. - -static KJ_CONSTEXPR(const) MinValue_ minValue = MinValue_(); -// A special constant which, when cast to an integer type, takes on the minimum possible value -// of that type. This is useful to use as e.g. a parameter to a function because it will be robust -// in the face of changes to the parameter's type. -// -// `char` is not supported, but `signed char` and `unsigned char` are. - -template -inline bool operator==(T t, MaxValue_) { return t == Decay(maxValue); } -template -inline bool operator==(T t, MinValue_) { return t == Decay(minValue); } - -template -inline constexpr unsigned long long maxValueForBits() { - // Get the maximum integer representable in the given number of bits. - - // 1ull << 64 is unfortunately undefined. - return (bits == 64 ? 0 : (1ull << bits)) - 1; -} - -struct ThrowOverflow { - // Functor which throws an exception complaining about integer overflow. Usually this is used - // with the interfaces in units.h, but is defined here because Cap'n Proto wants to avoid - // including units.h when not using CAPNP_DEBUG_TYPES. - void operator()() const; -}; - -#if __GNUC__ -inline constexpr float inf() { return __builtin_huge_valf(); } -inline constexpr float nan() { return __builtin_nanf(""); } - -#elif _MSC_VER - -// Do what MSVC math.h does -#pragma warning(push) -#pragma warning(disable: 4756) // "overflow in constant arithmetic" -inline constexpr float inf() { return (float)(1e300 * 1e300); } -#pragma warning(pop) - -float nan(); -// Unfortunatley, inf() * 0.0f produces a NaN with the sign bit set, whereas our preferred -// canonical NaN should not have the sign bit set. std::numeric_limits::quiet_NaN() -// returns the correct NaN, but we don't want to #include that here. So, we give up and make -// this out-of-line on MSVC. -// -// TODO(msvc): Can we do better? - -#else -#error "Not sure how to support your compiler." -#endif - -inline constexpr bool isNaN(float f) { return f != f; } -inline constexpr bool isNaN(double f) { return f != f; } - -inline int popCount(unsigned int x) { -#if defined(_MSC_VER) - return __popcnt(x); - // Note: __popcnt returns unsigned int, but the value is clearly guaranteed to fit into an int -#else - return __builtin_popcount(x); -#endif -} - -// ======================================================================================= -// Useful fake containers - -template -class Range { -public: - inline constexpr Range(const T& begin, const T& end): begin_(begin), end_(end) {} - inline explicit constexpr Range(const T& end): begin_(0), end_(end) {} - - class Iterator { - public: - Iterator() = default; - inline Iterator(const T& value): value(value) {} - - inline const T& operator* () const { return value; } - inline const T& operator[](size_t index) const { return value + index; } - inline Iterator& operator++() { ++value; return *this; } - inline Iterator operator++(int) { return Iterator(value++); } - inline Iterator& operator--() { --value; return *this; } - inline Iterator operator--(int) { return Iterator(value--); } - inline Iterator& operator+=(ptrdiff_t amount) { value += amount; return *this; } - inline Iterator& operator-=(ptrdiff_t amount) { value -= amount; return *this; } - inline Iterator operator+ (ptrdiff_t amount) const { return Iterator(value + amount); } - inline Iterator operator- (ptrdiff_t amount) const { return Iterator(value - amount); } - inline ptrdiff_t operator- (const Iterator& other) const { return value - other.value; } - - inline bool operator==(const Iterator& other) const { return value == other.value; } - inline bool operator!=(const Iterator& other) const { return value != other.value; } - inline bool operator<=(const Iterator& other) const { return value <= other.value; } - inline bool operator>=(const Iterator& other) const { return value >= other.value; } - inline bool operator< (const Iterator& other) const { return value < other.value; } - inline bool operator> (const Iterator& other) const { return value > other.value; } - - private: - T value; - }; - - inline Iterator begin() const { return Iterator(begin_); } - inline Iterator end() const { return Iterator(end_); } - - inline auto size() const -> decltype(instance() - instance()) { return end_ - begin_; } - -private: - T begin_; - T end_; -}; - -template -inline constexpr Range, Decay>> range(T begin, U end) { - return Range, Decay>>(begin, end); -} - -template -inline constexpr Range> range(T begin, T end) { return Range>(begin, end); } -// Returns a fake iterable container containing all values of T from `begin` (inclusive) to `end` -// (exclusive). Example: -// -// // Prints 1, 2, 3, 4, 5, 6, 7, 8, 9. -// for (int i: kj::range(1, 10)) { print(i); } - -template -inline constexpr Range> zeroTo(T end) { return Range>(end); } -// Returns a fake iterable container containing all values of T from zero (inclusive) to `end` -// (exclusive). Example: -// -// // Prints 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. -// for (int i: kj::zeroTo(10)) { print(i); } - -template -inline constexpr Range indices(T&& container) { - // Shortcut for iterating over the indices of a container: - // - // for (size_t i: kj::indices(myArray)) { handle(myArray[i]); } - - return range(0, kj::size(container)); -} - -template -class Repeat { -public: - inline constexpr Repeat(const T& value, size_t count): value(value), count(count) {} - - class Iterator { - public: - Iterator() = default; - inline Iterator(const T& value, size_t index): value(value), index(index) {} - - inline const T& operator* () const { return value; } - inline const T& operator[](ptrdiff_t index) const { return value; } - inline Iterator& operator++() { ++index; return *this; } - inline Iterator operator++(int) { return Iterator(value, index++); } - inline Iterator& operator--() { --index; return *this; } - inline Iterator operator--(int) { return Iterator(value, index--); } - inline Iterator& operator+=(ptrdiff_t amount) { index += amount; return *this; } - inline Iterator& operator-=(ptrdiff_t amount) { index -= amount; return *this; } - inline Iterator operator+ (ptrdiff_t amount) const { return Iterator(value, index + amount); } - inline Iterator operator- (ptrdiff_t amount) const { return Iterator(value, index - amount); } - inline ptrdiff_t operator- (const Iterator& other) const { return index - other.index; } - - inline bool operator==(const Iterator& other) const { return index == other.index; } - inline bool operator!=(const Iterator& other) const { return index != other.index; } - inline bool operator<=(const Iterator& other) const { return index <= other.index; } - inline bool operator>=(const Iterator& other) const { return index >= other.index; } - inline bool operator< (const Iterator& other) const { return index < other.index; } - inline bool operator> (const Iterator& other) const { return index > other.index; } - - private: - T value; - size_t index; - }; - - inline Iterator begin() const { return Iterator(value, 0); } - inline Iterator end() const { return Iterator(value, count); } - - inline size_t size() const { return count; } - inline const T& operator[](ptrdiff_t) const { return value; } - -private: - T value; - size_t count; -}; - -template -inline constexpr Repeat> repeat(T&& value, size_t count) { - // Returns a fake iterable which contains `count` repeats of `value`. Useful for e.g. creating - // a bunch of spaces: `kj::repeat(' ', indent * 2)` - - return Repeat>(value, count); -} - -// ======================================================================================= -// Manually invoking constructors and destructors -// -// ctor(x, ...) and dtor(x) invoke x's constructor or destructor, respectively. - -// We want placement new, but we don't want to #include . operator new cannot be defined in -// a namespace, and defining it globally conflicts with the definition in . So we have to -// define a dummy type and an operator new that uses it. - -namespace _ { // private -struct PlacementNew {}; -} // namespace _ (private) -} // namespace kj - -inline void* operator new(size_t, kj::_::PlacementNew, void* __p) noexcept { - return __p; -} - -inline void operator delete(void*, kj::_::PlacementNew, void* __p) noexcept {} - -namespace kj { - -template -inline void ctor(T& location, Params&&... params) { - new (_::PlacementNew(), &location) T(kj::fwd(params)...); -} - -template -inline void dtor(T& location) { - location.~T(); -} - -// ======================================================================================= -// Maybe -// -// Use in cases where you want to indicate that a value may be null. Using Maybe instead of T* -// forces the caller to handle the null case in order to satisfy the compiler, thus reliably -// preventing null pointer dereferences at runtime. -// -// Maybe can be implicitly constructed from T and from nullptr. Additionally, it can be -// implicitly constructed from T*, in which case the pointer is checked for nullness at runtime. -// To read the value of a Maybe, do: -// -// KJ_IF_MAYBE(value, someFuncReturningMaybe()) { -// doSomething(*value); -// } else { -// maybeWasNull(); -// } -// -// KJ_IF_MAYBE's first parameter is a variable name which will be defined within the following -// block. The variable will behave like a (guaranteed non-null) pointer to the Maybe's value, -// though it may or may not actually be a pointer. -// -// Note that Maybe actually just wraps a pointer, whereas Maybe wraps a T and a boolean -// indicating nullness. - -template -class Maybe; - -namespace _ { // private - -template -class NullableValue { - // Class whose interface behaves much like T*, but actually contains an instance of T and a - // boolean flag indicating nullness. - -public: - inline NullableValue(NullableValue&& other) noexcept(noexcept(T(instance()))) - : isSet(other.isSet) { - if (isSet) { - ctor(value, kj::mv(other.value)); - } - } - inline NullableValue(const NullableValue& other) - : isSet(other.isSet) { - if (isSet) { - ctor(value, other.value); - } - } - inline NullableValue(NullableValue& other) - : isSet(other.isSet) { - if (isSet) { - ctor(value, other.value); - } - } - inline ~NullableValue() -#if _MSC_VER - // TODO(msvc): MSVC has a hard time with noexcept specifier expressions that are more complex - // than `true` or `false`. We had a workaround for VS2015, but VS2017 regressed. - noexcept(false) -#else - noexcept(noexcept(instance().~T())) -#endif - { - if (isSet) { - dtor(value); - } - } - - inline T& operator*() & { return value; } - inline const T& operator*() const & { return value; } - inline T&& operator*() && { return kj::mv(value); } - inline const T&& operator*() const && { return kj::mv(value); } - inline T* operator->() { return &value; } - inline const T* operator->() const { return &value; } - inline operator T*() { return isSet ? &value : nullptr; } - inline operator const T*() const { return isSet ? &value : nullptr; } - - template - inline T& emplace(Params&&... params) { - if (isSet) { - isSet = false; - dtor(value); - } - ctor(value, kj::fwd(params)...); - isSet = true; - return value; - } - -private: // internal interface used by friends only - inline NullableValue() noexcept: isSet(false) {} - inline NullableValue(T&& t) noexcept(noexcept(T(instance()))) - : isSet(true) { - ctor(value, kj::mv(t)); - } - inline NullableValue(T& t) - : isSet(true) { - ctor(value, t); - } - inline NullableValue(const T& t) - : isSet(true) { - ctor(value, t); - } - inline NullableValue(const T* t) - : isSet(t != nullptr) { - if (isSet) ctor(value, *t); - } - template - inline NullableValue(NullableValue&& other) noexcept(noexcept(T(instance()))) - : isSet(other.isSet) { - if (isSet) { - ctor(value, kj::mv(other.value)); - } - } - template - inline NullableValue(const NullableValue& other) - : isSet(other.isSet) { - if (isSet) { - ctor(value, other.value); - } - } - template - inline NullableValue(const NullableValue& other) - : isSet(other.isSet) { - if (isSet) { - ctor(value, *other.ptr); - } - } - inline NullableValue(decltype(nullptr)): isSet(false) {} - - inline NullableValue& operator=(NullableValue&& other) { - if (&other != this) { - // Careful about throwing destructors/constructors here. - if (isSet) { - isSet = false; - dtor(value); - } - if (other.isSet) { - ctor(value, kj::mv(other.value)); - isSet = true; - } - } - return *this; - } - - inline NullableValue& operator=(NullableValue& other) { - if (&other != this) { - // Careful about throwing destructors/constructors here. - if (isSet) { - isSet = false; - dtor(value); - } - if (other.isSet) { - ctor(value, other.value); - isSet = true; - } - } - return *this; - } - - inline NullableValue& operator=(const NullableValue& other) { - if (&other != this) { - // Careful about throwing destructors/constructors here. - if (isSet) { - isSet = false; - dtor(value); - } - if (other.isSet) { - ctor(value, other.value); - isSet = true; - } - } - return *this; - } - - inline bool operator==(decltype(nullptr)) const { return !isSet; } - inline bool operator!=(decltype(nullptr)) const { return isSet; } - -private: - bool isSet; - -#if _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4624) -// Warns that the anonymous union has a deleted destructor when T is non-trivial. This warning -// seems broken. -#endif - - union { - T value; - }; - -#if _MSC_VER -#pragma warning(pop) -#endif - - friend class kj::Maybe; - template - friend NullableValue&& readMaybe(Maybe&& maybe); -}; - -template -inline NullableValue&& readMaybe(Maybe&& maybe) { return kj::mv(maybe.ptr); } -template -inline T* readMaybe(Maybe& maybe) { return maybe.ptr; } -template -inline const T* readMaybe(const Maybe& maybe) { return maybe.ptr; } -template -inline T* readMaybe(Maybe&& maybe) { return maybe.ptr; } -template -inline T* readMaybe(const Maybe& maybe) { return maybe.ptr; } - -template -inline T* readMaybe(T* ptr) { return ptr; } -// Allow KJ_IF_MAYBE to work on regular pointers. - -} // namespace _ (private) - -#define KJ_IF_MAYBE(name, exp) if (auto name = ::kj::_::readMaybe(exp)) - -template -class Maybe { - // A T, or nullptr. - - // IF YOU CHANGE THIS CLASS: Note that there is a specialization of it in memory.h. - -public: - Maybe(): ptr(nullptr) {} - Maybe(T&& t) noexcept(noexcept(T(instance()))): ptr(kj::mv(t)) {} - Maybe(T& t): ptr(t) {} - Maybe(const T& t): ptr(t) {} - Maybe(const T* t) noexcept: ptr(t) {} - Maybe(Maybe&& other) noexcept(noexcept(T(instance()))): ptr(kj::mv(other.ptr)) {} - Maybe(const Maybe& other): ptr(other.ptr) {} - Maybe(Maybe& other): ptr(other.ptr) {} - - template - Maybe(Maybe&& other) noexcept(noexcept(T(instance()))) { - KJ_IF_MAYBE(val, kj::mv(other)) { - ptr.emplace(kj::mv(*val)); - } - } - template - Maybe(const Maybe& other) { - KJ_IF_MAYBE(val, other) { - ptr.emplace(*val); - } - } - - Maybe(decltype(nullptr)) noexcept: ptr(nullptr) {} - - template - inline T& emplace(Params&&... params) { - // Replace this Maybe's content with a new value constructed by passing the given parametrs to - // T's constructor. This can be used to initialize a Maybe without copying or even moving a T. - // Returns a reference to the newly-constructed value. - - return ptr.emplace(kj::fwd(params)...); - } - - inline Maybe& operator=(Maybe&& other) { ptr = kj::mv(other.ptr); return *this; } - inline Maybe& operator=(Maybe& other) { ptr = other.ptr; return *this; } - inline Maybe& operator=(const Maybe& other) { ptr = other.ptr; return *this; } - - inline bool operator==(decltype(nullptr)) const { return ptr == nullptr; } - inline bool operator!=(decltype(nullptr)) const { return ptr != nullptr; } - - T& orDefault(T& defaultValue) { - if (ptr == nullptr) { - return defaultValue; - } else { - return *ptr; - } - } - const T& orDefault(const T& defaultValue) const { - if (ptr == nullptr) { - return defaultValue; - } else { - return *ptr; - } - } - - template - auto map(Func&& f) & -> Maybe()))> { - if (ptr == nullptr) { - return nullptr; - } else { - return f(*ptr); - } - } - - template - auto map(Func&& f) const & -> Maybe()))> { - if (ptr == nullptr) { - return nullptr; - } else { - return f(*ptr); - } - } - - template - auto map(Func&& f) && -> Maybe()))> { - if (ptr == nullptr) { - return nullptr; - } else { - return f(kj::mv(*ptr)); - } - } - - template - auto map(Func&& f) const && -> Maybe()))> { - if (ptr == nullptr) { - return nullptr; - } else { - return f(kj::mv(*ptr)); - } - } - -private: - _::NullableValue ptr; - - template - friend class Maybe; - template - friend _::NullableValue&& _::readMaybe(Maybe&& maybe); - template - friend U* _::readMaybe(Maybe& maybe); - template - friend const U* _::readMaybe(const Maybe& maybe); -}; - -template -class Maybe: public DisallowConstCopyIfNotConst { -public: - Maybe() noexcept: ptr(nullptr) {} - Maybe(T& t) noexcept: ptr(&t) {} - Maybe(T* t) noexcept: ptr(t) {} - - template - inline Maybe(Maybe& other) noexcept: ptr(other.ptr) {} - template - inline Maybe(const Maybe& other) noexcept: ptr(other.ptr) {} - inline Maybe(decltype(nullptr)) noexcept: ptr(nullptr) {} - - inline Maybe& operator=(T& other) noexcept { ptr = &other; return *this; } - inline Maybe& operator=(T* other) noexcept { ptr = other; return *this; } - template - inline Maybe& operator=(Maybe& other) noexcept { ptr = other.ptr; return *this; } - template - inline Maybe& operator=(const Maybe& other) noexcept { ptr = other.ptr; return *this; } - - inline bool operator==(decltype(nullptr)) const { return ptr == nullptr; } - inline bool operator!=(decltype(nullptr)) const { return ptr != nullptr; } - - T& orDefault(T& defaultValue) { - if (ptr == nullptr) { - return defaultValue; - } else { - return *ptr; - } - } - const T& orDefault(const T& defaultValue) const { - if (ptr == nullptr) { - return defaultValue; - } else { - return *ptr; - } - } - - template - auto map(Func&& f) -> Maybe()))> { - if (ptr == nullptr) { - return nullptr; - } else { - return f(*ptr); - } - } - -private: - T* ptr; - - template - friend class Maybe; - template - friend U* _::readMaybe(Maybe&& maybe); - template - friend U* _::readMaybe(const Maybe& maybe); -}; - -// ======================================================================================= -// ArrayPtr -// -// So common that we put it in common.h rather than array.h. - -template -class ArrayPtr: public DisallowConstCopyIfNotConst { - // A pointer to an array. Includes a size. Like any pointer, it doesn't own the target data, - // and passing by value only copies the pointer, not the target. - -public: - inline constexpr ArrayPtr(): ptr(nullptr), size_(0) {} - inline constexpr ArrayPtr(decltype(nullptr)): ptr(nullptr), size_(0) {} - inline constexpr ArrayPtr(T* ptr, size_t size): ptr(ptr), size_(size) {} - inline constexpr ArrayPtr(T* begin, T* end): ptr(begin), size_(end - begin) {} - inline KJ_CONSTEXPR() ArrayPtr(::std::initializer_list> init) - : ptr(init.begin()), size_(init.size()) {} - - template - inline constexpr ArrayPtr(T (&native)[size]): ptr(native), size_(size) {} - // Construct an ArrayPtr from a native C-style array. - - inline operator ArrayPtr() const { - return ArrayPtr(ptr, size_); - } - inline ArrayPtr asConst() const { - return ArrayPtr(ptr, size_); - } - - inline size_t size() const { return size_; } - inline const T& operator[](size_t index) const { - KJ_IREQUIRE(index < size_, "Out-of-bounds ArrayPtr access."); - return ptr[index]; - } - inline T& operator[](size_t index) { - KJ_IREQUIRE(index < size_, "Out-of-bounds ArrayPtr access."); - return ptr[index]; - } - - inline T* begin() { return ptr; } - inline T* end() { return ptr + size_; } - inline T& front() { return *ptr; } - inline T& back() { return *(ptr + size_ - 1); } - inline const T* begin() const { return ptr; } - inline const T* end() const { return ptr + size_; } - inline const T& front() const { return *ptr; } - inline const T& back() const { return *(ptr + size_ - 1); } - - inline ArrayPtr slice(size_t start, size_t end) const { - KJ_IREQUIRE(start <= end && end <= size_, "Out-of-bounds ArrayPtr::slice()."); - return ArrayPtr(ptr + start, end - start); - } - inline ArrayPtr slice(size_t start, size_t end) { - KJ_IREQUIRE(start <= end && end <= size_, "Out-of-bounds ArrayPtr::slice()."); - return ArrayPtr(ptr + start, end - start); - } - - inline ArrayPtr> asBytes() const { - // Reinterpret the array as a byte array. This is explicitly legal under C++ aliasing - // rules. - return { reinterpret_cast*>(ptr), size_ * sizeof(T) }; - } - inline ArrayPtr> asChars() const { - // Reinterpret the array as a char array. This is explicitly legal under C++ aliasing - // rules. - return { reinterpret_cast*>(ptr), size_ * sizeof(T) }; - } - - inline bool operator==(decltype(nullptr)) const { return size_ == 0; } - inline bool operator!=(decltype(nullptr)) const { return size_ != 0; } - - inline bool operator==(const ArrayPtr& other) const { - if (size_ != other.size_) return false; - for (size_t i = 0; i < size_; i++) { - if (ptr[i] != other[i]) return false; - } - return true; - } - inline bool operator!=(const ArrayPtr& other) const { return !(*this == other); } - -private: - T* ptr; - size_t size_; -}; - -template -inline constexpr ArrayPtr arrayPtr(T* ptr, size_t size) { - // Use this function to construct ArrayPtrs without writing out the type name. - return ArrayPtr(ptr, size); -} - -template -inline constexpr ArrayPtr arrayPtr(T* begin, T* end) { - // Use this function to construct ArrayPtrs without writing out the type name. - return ArrayPtr(begin, end); -} - -// ======================================================================================= -// Casts - -template -To implicitCast(From&& from) { - // `implicitCast(value)` casts `value` to type `T` only if the conversion is implicit. Useful - // for e.g. resolving ambiguous overloads without sacrificing type-safety. - return kj::fwd(from); -} - -template -Maybe dynamicDowncastIfAvailable(From& from) { - // If RTTI is disabled, always returns nullptr. Otherwise, works like dynamic_cast. Useful - // in situations where dynamic_cast could allow an optimization, but isn't strictly necessary - // for correctness. It is highly recommended that you try to arrange all your dynamic_casts - // this way, as a dynamic_cast that is necessary for correctness implies a flaw in the interface - // design. - - // Force a compile error if To is not a subtype of From. Cross-casting is rare; if it is needed - // we should have a separate cast function like dynamicCrosscastIfAvailable(). - if (false) { - kj::implicitCast(kj::implicitCast(nullptr)); - } - -#if KJ_NO_RTTI - return nullptr; -#else - return dynamic_cast(&from); -#endif -} - -template -To& downcast(From& from) { - // Down-cast a value to a sub-type, asserting that the cast is valid. In opt mode this is a - // static_cast, but in debug mode (when RTTI is enabled) a dynamic_cast will be used to verify - // that the value really has the requested type. - - // Force a compile error if To is not a subtype of From. - if (false) { - kj::implicitCast(kj::implicitCast(nullptr)); - } - -#if !KJ_NO_RTTI - KJ_IREQUIRE(dynamic_cast(&from) != nullptr, "Value cannot be downcast() to requested type."); -#endif - - return static_cast(from); -} - -// ======================================================================================= -// Defer - -namespace _ { // private - -template -class Deferred { -public: - inline Deferred(Func&& func): func(kj::fwd(func)), canceled(false) {} - inline ~Deferred() noexcept(false) { if (!canceled) func(); } - KJ_DISALLOW_COPY(Deferred); - - // This move constructor is usually optimized away by the compiler. - inline Deferred(Deferred&& other): func(kj::mv(other.func)), canceled(false) { - other.canceled = true; - } -private: - Func func; - bool canceled; -}; - -} // namespace _ (private) - -template -_::Deferred defer(Func&& func) { - // Returns an object which will invoke the given functor in its destructor. The object is not - // copyable but is movable with the semantics you'd expect. Since the return type is private, - // you need to assign to an `auto` variable. - // - // The KJ_DEFER macro provides slightly more convenient syntax for the common case where you - // want some code to run at current scope exit. - - return _::Deferred(kj::fwd(func)); -} - -#define KJ_DEFER(code) auto KJ_UNIQUE_NAME(_kjDefer) = ::kj::defer([&](){code;}) -// Run the given code when the function exits, whether by return or exception. - -} // namespace kj - -#endif // KJ_COMMON_H_ diff --git a/phonelibs/capnp-cpp/include/kj/compat/gtest.h b/phonelibs/capnp-cpp/include/kj/compat/gtest.h deleted file mode 100644 index 016dbdfac3..0000000000 --- a/phonelibs/capnp-cpp/include/kj/compat/gtest.h +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_COMPAT_GTEST_H_ -#define KJ_COMPAT_GTEST_H_ -// This file defines compatibility macros converting Google Test tests into KJ tests. -// -// This is only intended to cover the most common functionality. Many tests will likely need -// additional tweaks. For instance: -// - Using operator<< to print information on failure is not supported. Instead, switch to -// KJ_ASSERT/KJ_EXPECT and pass in stuff to print as additional parameters. -// - Test fixtures are not supported. Allocate your "test fixture" on the stack instead. Do setup -// in the constructor, teardown in the destructor. - -#include "../test.h" - -namespace kj { - -namespace _ { // private - -template -T abs(T value) { return value < 0 ? -value : value; } - -inline bool floatAlmostEqual(float a, float b) { - return a == b || abs(a - b) < (abs(a) + abs(b)) * 1e-5; -} - -inline bool doubleAlmostEqual(double a, double b) { - return a == b || abs(a - b) < (abs(a) + abs(b)) * 1e-12; -} - -} // namespace _ (private) - -#define EXPECT_FALSE(x) KJ_EXPECT(!(x)) -#define EXPECT_TRUE(x) KJ_EXPECT(x) -#define EXPECT_EQ(x, y) KJ_EXPECT((x) == (y), x, y) -#define EXPECT_NE(x, y) KJ_EXPECT((x) != (y), x, y) -#define EXPECT_LE(x, y) KJ_EXPECT((x) <= (y), x, y) -#define EXPECT_GE(x, y) KJ_EXPECT((x) >= (y), x, y) -#define EXPECT_LT(x, y) KJ_EXPECT((x) < (y), x, y) -#define EXPECT_GT(x, y) KJ_EXPECT((x) > (y), x, y) -#define EXPECT_STREQ(x, y) KJ_EXPECT(::strcmp(x, y) == 0, x, y) -#define EXPECT_FLOAT_EQ(x, y) KJ_EXPECT(::kj::_::floatAlmostEqual(y, x), y, x); -#define EXPECT_DOUBLE_EQ(x, y) KJ_EXPECT(::kj::_::doubleAlmostEqual(y, x), y, x); - -#define ASSERT_FALSE(x) KJ_ASSERT(!(x)) -#define ASSERT_TRUE(x) KJ_ASSERT(x) -#define ASSERT_EQ(x, y) KJ_ASSERT((x) == (y), x, y) -#define ASSERT_NE(x, y) KJ_ASSERT((x) != (y), x, y) -#define ASSERT_LE(x, y) KJ_ASSERT((x) <= (y), x, y) -#define ASSERT_GE(x, y) KJ_ASSERT((x) >= (y), x, y) -#define ASSERT_LT(x, y) KJ_ASSERT((x) < (y), x, y) -#define ASSERT_GT(x, y) KJ_ASSERT((x) > (y), x, y) -#define ASSERT_STREQ(x, y) KJ_ASSERT(::strcmp(x, y) == 0, x, y) -#define ASSERT_FLOAT_EQ(x, y) KJ_ASSERT(::kj::_::floatAlmostEqual(y, x), y, x); -#define ASSERT_DOUBLE_EQ(x, y) KJ_ASSERT(::kj::_::doubleAlmostEqual(y, x), y, x); - -class AddFailureAdapter { -public: - AddFailureAdapter(const char* file, int line): file(file), line(line) {} - - ~AddFailureAdapter() { - if (!handled) { - _::Debug::log(file, line, LogSeverity::ERROR, "expectation failed"); - } - } - - template - void operator<<(T&& info) { - handled = true; - _::Debug::log(file, line, LogSeverity::ERROR, "\"expectation failed\", info", - "expectation failed", kj::fwd(info)); - } - -private: - bool handled = false; - const char* file; - int line; -}; - -#define ADD_FAILURE() ::kj::AddFailureAdapter(__FILE__, __LINE__) - -#if KJ_NO_EXCEPTIONS -#define EXPECT_ANY_THROW(code) \ - KJ_EXPECT(::kj::_::expectFatalThrow(nullptr, nullptr, [&]() { code; })) -#else -#define EXPECT_ANY_THROW(code) \ - KJ_EXPECT(::kj::runCatchingExceptions([&]() { code; }) != nullptr) -#endif - -#define EXPECT_NONFATAL_FAILURE(code) \ - EXPECT_TRUE(kj::runCatchingExceptions([&]() { code; }) != nullptr); - -#ifdef KJ_DEBUG -#define EXPECT_DEBUG_ANY_THROW EXPECT_ANY_THROW -#else -#define EXPECT_DEBUG_ANY_THROW(EXP) -#endif - -#define TEST(x, y) KJ_TEST("legacy test: " #x "/" #y) - -} // namespace kj - -#endif // KJ_COMPAT_GTEST_H_ diff --git a/phonelibs/capnp-cpp/include/kj/compat/http.h b/phonelibs/capnp-cpp/include/kj/compat/http.h deleted file mode 100644 index 8d455cc258..0000000000 --- a/phonelibs/capnp-cpp/include/kj/compat/http.h +++ /dev/null @@ -1,636 +0,0 @@ -// Copyright (c) 2017 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_COMPAT_HTTP_H_ -#define KJ_COMPAT_HTTP_H_ -// The KJ HTTP client/server library. -// -// This is a simple library which can be used to implement an HTTP client or server. Properties -// of this library include: -// - Uses KJ async framework. -// - Agnostic to transport layer -- you can provide your own. -// - Header parsing is zero-copy -- it results in strings that point directly into the buffer -// received off the wire. -// - Application code which reads and writes headers refers to headers by symbolic names, not by -// string literals, with lookups being array-index-based, not map-based. To make this possible, -// the application announces what headers it cares about in advance, in order to assign numeric -// values to them. -// - Methods are identified by an enum. - -#include -#include -#include -#include -#include - -namespace kj { - -#define KJ_HTTP_FOR_EACH_METHOD(MACRO) \ - MACRO(GET) \ - MACRO(HEAD) \ - MACRO(POST) \ - MACRO(PUT) \ - MACRO(DELETE) \ - MACRO(PATCH) \ - MACRO(PURGE) \ - MACRO(OPTIONS) \ - MACRO(TRACE) \ - /* standard methods */ \ - /* */ \ - /* (CONNECT is intentionally omitted since it is handled specially in HttpHandler) */ \ - \ - MACRO(COPY) \ - MACRO(LOCK) \ - MACRO(MKCOL) \ - MACRO(MOVE) \ - MACRO(PROPFIND) \ - MACRO(PROPPATCH) \ - MACRO(SEARCH) \ - MACRO(UNLOCK) \ - /* WebDAV */ \ - \ - MACRO(REPORT) \ - MACRO(MKACTIVITY) \ - MACRO(CHECKOUT) \ - MACRO(MERGE) \ - /* Subversion */ \ - \ - MACRO(MSEARCH) \ - MACRO(NOTIFY) \ - MACRO(SUBSCRIBE) \ - MACRO(UNSUBSCRIBE) - /* UPnP */ - -#define KJ_HTTP_FOR_EACH_CONNECTION_HEADER(MACRO) \ - MACRO(connection, "Connection") \ - MACRO(contentLength, "Content-Length") \ - MACRO(keepAlive, "Keep-Alive") \ - MACRO(te, "TE") \ - MACRO(trailer, "Trailer") \ - MACRO(transferEncoding, "Transfer-Encoding") \ - MACRO(upgrade, "Upgrade") - -enum class HttpMethod { - // Enum of known HTTP methods. - // - // We use an enum rather than a string to allow for faster parsing and switching and to reduce - // ambiguity. - -#define DECLARE_METHOD(id) id, -KJ_HTTP_FOR_EACH_METHOD(DECLARE_METHOD) -#undef DECLARE_METHOD -}; - -kj::StringPtr KJ_STRINGIFY(HttpMethod method); -kj::Maybe tryParseHttpMethod(kj::StringPtr name); - -class HttpHeaderTable; - -class HttpHeaderId { - // Identifies an HTTP header by numeric ID that indexes into an HttpHeaderTable. - // - // The KJ HTTP API prefers that headers be identified by these IDs for a few reasons: - // - Integer lookups are much more efficient than string lookups. - // - Case-insensitivity is awkward to deal with when const strings are being passed to the lookup - // method. - // - Writing out strings less often means fewer typos. - // - // See HttpHeaderTable for usage hints. - -public: - HttpHeaderId() = default; - - inline bool operator==(const HttpHeaderId& other) const { return id == other.id; } - inline bool operator!=(const HttpHeaderId& other) const { return id != other.id; } - inline bool operator< (const HttpHeaderId& other) const { return id < other.id; } - inline bool operator> (const HttpHeaderId& other) const { return id > other.id; } - inline bool operator<=(const HttpHeaderId& other) const { return id <= other.id; } - inline bool operator>=(const HttpHeaderId& other) const { return id >= other.id; } - - inline size_t hashCode() const { return id; } - - kj::StringPtr toString() const; - - void requireFrom(HttpHeaderTable& table) const; - // In debug mode, throws an exception if the HttpHeaderId is not from the given table. - // - // In opt mode, no-op. - -#define KJ_HTTP_FOR_EACH_BUILTIN_HEADER(MACRO) \ - MACRO(HOST, "Host") \ - MACRO(DATE, "Date") \ - MACRO(LOCATION, "Location") \ - MACRO(CONTENT_TYPE, "Content-Type") - // For convenience, these very-common headers are valid for all HttpHeaderTables. You can refer - // to them like: - // - // HttpHeaderId::HOST - // - // TODO(0.7): Fill this out with more common headers. - -#define DECLARE_HEADER(id, name) \ - static const HttpHeaderId id; - // Declare a constant for each builtin header, e.g.: HttpHeaderId::CONNECTION - - KJ_HTTP_FOR_EACH_BUILTIN_HEADER(DECLARE_HEADER); -#undef DECLARE_HEADER - -private: - HttpHeaderTable* table; - uint id; - - inline explicit constexpr HttpHeaderId(HttpHeaderTable* table, uint id): table(table), id(id) {} - friend class HttpHeaderTable; - friend class HttpHeaders; -}; - -class HttpHeaderTable { - // Construct an HttpHeaderTable to declare which headers you'll be interested in later on, and - // to manufacture IDs for them. - // - // Example: - // - // // Build a header table with the headers we are interested in. - // kj::HttpHeaderTable::Builder builder; - // const HttpHeaderId accept = builder.add("Accept"); - // const HttpHeaderId contentType = builder.add("Content-Type"); - // kj::HttpHeaderTable table(kj::mv(builder)); - // - // // Create an HTTP client. - // auto client = kj::newHttpClient(table, network); - // - // // Get http://example.com. - // HttpHeaders headers(table); - // headers.set(accept, "text/html"); - // auto response = client->send(kj::HttpMethod::GET, "http://example.com", headers) - // .wait(waitScope); - // auto msg = kj::str("Response content type: ", response.headers.get(contentType)); - - struct IdsByNameMap; - -public: - HttpHeaderTable(); - // Constructs a table that only contains the builtin headers. - - class Builder { - public: - Builder(); - HttpHeaderId add(kj::StringPtr name); - Own build(); - - HttpHeaderTable& getFutureTable(); - // Get the still-unbuilt header table. You cannot actually use it until build() has been - // called. - // - // This method exists to help when building a shared header table -- the Builder may be passed - // to several components, each of which will register the headers they need and get a reference - // to the future table. - - private: - kj::Own table; - }; - - KJ_DISALLOW_COPY(HttpHeaderTable); // Can't copy because HttpHeaderId points to the table. - ~HttpHeaderTable() noexcept(false); - - uint idCount(); - // Return the number of IDs in the table. - - kj::Maybe stringToId(kj::StringPtr name); - // Try to find an ID for the given name. The matching is case-insensitive, per the HTTP spec. - // - // Note: if `name` contains characters that aren't allowed in HTTP header names, this may return - // a bogus value rather than null, due to optimizations used in case-insensitive matching. - - kj::StringPtr idToString(HttpHeaderId id); - // Get the canonical string name for the given ID. - -private: - kj::Vector namesById; - kj::Own idsByName; -}; - -class HttpHeaders { - // Represents a set of HTTP headers. - // - // This class guards against basic HTTP header injection attacks: Trying to set a header name or - // value containing a newline, carriage return, or other invalid character will throw an - // exception. - -public: - explicit HttpHeaders(HttpHeaderTable& table); - - KJ_DISALLOW_COPY(HttpHeaders); - HttpHeaders(HttpHeaders&&) = default; - HttpHeaders& operator=(HttpHeaders&&) = default; - - void clear(); - // Clears all contents, as if the object was freshly-allocated. However, calling this rather - // than actually re-allocating the object may avoid re-allocation of internal objects. - - HttpHeaders clone() const; - // Creates a deep clone of the HttpHeaders. The returned object owns all strings it references. - - HttpHeaders cloneShallow() const; - // Creates a shallow clone of the HttpHeaders. The returned object references the same strings - // as the original, owning none of them. - - kj::Maybe get(HttpHeaderId id) const; - // Read a header. - - template - void forEach(Func&& func) const; - // Calls `func(name, value)` for each header in the set -- including headers that aren't mapped - // to IDs in the header table. Both inputs are of type kj::StringPtr. - - void set(HttpHeaderId id, kj::StringPtr value); - void set(HttpHeaderId id, kj::String&& value); - // Sets a header value, overwriting the existing value. - // - // The String&& version is equivalent to calling the other version followed by takeOwnership(). - // - // WARNING: It is the caller's responsibility to ensure that `value` remains valid until the - // HttpHeaders object is destroyed. This allows string literals to be passed without making a - // copy, but complicates the use of dynamic values. Hint: Consider using `takeOwnership()`. - - void add(kj::StringPtr name, kj::StringPtr value); - void add(kj::StringPtr name, kj::String&& value); - void add(kj::String&& name, kj::String&& value); - // Append a header. `name` will be looked up in the header table, but if it's not mapped, the - // header will be added to the list of unmapped headers. - // - // The String&& versions are equivalent to calling the other version followed by takeOwnership(). - // - // WARNING: It is the caller's responsibility to ensure that `name` and `value` remain valid - // until the HttpHeaders object is destroyed. This allows string literals to be passed without - // making a copy, but complicates the use of dynamic values. Hint: Consider using - // `takeOwnership()`. - - void unset(HttpHeaderId id); - // Removes a header. - // - // It's not possible to remove a header by string name because non-indexed headers would take - // O(n) time to remove. Instead, construct a new HttpHeaders object and copy contents. - - void takeOwnership(kj::String&& string); - void takeOwnership(kj::Array&& chars); - void takeOwnership(HttpHeaders&& otherHeaders); - // Takes overship of a string so that it lives until the HttpHeaders object is destroyed. Useful - // when you've passed a dynamic value to set() or add() or parse*(). - - struct ConnectionHeaders { - // These headers govern details of the specific HTTP connection or framing of the content. - // Hence, they are managed internally within the HTTP library, and never appear in an - // HttpHeaders structure. - -#define DECLARE_HEADER(id, name) \ - kj::StringPtr id; - KJ_HTTP_FOR_EACH_CONNECTION_HEADER(DECLARE_HEADER) -#undef DECLARE_HEADER - }; - - struct Request { - HttpMethod method; - kj::StringPtr url; - ConnectionHeaders connectionHeaders; - }; - struct Response { - uint statusCode; - kj::StringPtr statusText; - ConnectionHeaders connectionHeaders; - }; - - kj::Maybe tryParseRequest(kj::ArrayPtr content); - kj::Maybe tryParseResponse(kj::ArrayPtr content); - // Parse an HTTP header blob and add all the headers to this object. - // - // `content` should be all text from the start of the request to the first occurrance of two - // newlines in a row -- including the first of these two newlines, but excluding the second. - // - // The parse is performed with zero copies: The callee clobbers `content` with '\0' characters - // to split it into a bunch of shorter strings. The caller must keep `content` valid until the - // `HttpHeaders` is destroyed, or pass it to `takeOwnership()`. - - kj::String serializeRequest(HttpMethod method, kj::StringPtr url, - const ConnectionHeaders& connectionHeaders) const; - kj::String serializeResponse(uint statusCode, kj::StringPtr statusText, - const ConnectionHeaders& connectionHeaders) const; - // Serialize the headers as a complete request or response blob. The blob uses '\r\n' newlines - // and includes the double-newline to indicate the end of the headers. - - kj::String toString() const; - -private: - HttpHeaderTable* table; - - kj::Array indexedHeaders; - // Size is always table->idCount(). - - struct Header { - kj::StringPtr name; - kj::StringPtr value; - }; - kj::Vector

unindexedHeaders; - - kj::Vector> ownedStrings; - - kj::Maybe addNoCheck(kj::StringPtr name, kj::StringPtr value); - - kj::StringPtr cloneToOwn(kj::StringPtr str); - - kj::String serialize(kj::ArrayPtr word1, - kj::ArrayPtr word2, - kj::ArrayPtr word3, - const ConnectionHeaders& connectionHeaders) const; - - bool parseHeaders(char* ptr, char* end, ConnectionHeaders& connectionHeaders); - - // TODO(perf): Arguably we should store a map, but header sets are never very long - // TODO(perf): We could optimize for common headers by storing them directly as fields. We could - // also add direct accessors for those headers. -}; - -class WebSocket { -public: - WebSocket(kj::Own stream); - // Create a WebSocket wrapping the given I/O stream. - - kj::Promise send(kj::ArrayPtr message); - kj::Promise send(kj::ArrayPtr message); -}; - -class HttpClient { - // Interface to the client end of an HTTP connection. - // - // There are two kinds of clients: - // * Host clients are used when talking to a specific host. The `url` specified in a request - // is actually just a path. (A `Host` header is still required in all requests.) - // * Proxy clients are used when the target could be any arbitrary host on the internet. - // The `url` specified in a request is a full URL including protocol and hostname. - -public: - struct Response { - uint statusCode; - kj::StringPtr statusText; - const HttpHeaders* headers; - kj::Own body; - // `statusText` and `headers` remain valid until `body` is dropped. - }; - - struct Request { - kj::Own body; - // Write the request entity body to this stream, then drop it when done. - // - // May be null for GET and HEAD requests (which have no body) and requests that have - // Content-Length: 0. - - kj::Promise response; - // Promise for the eventual respnose. - }; - - virtual Request request(HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, - kj::Maybe expectedBodySize = nullptr) = 0; - // Perform an HTTP request. - // - // `url` may be a full URL (with protocol and host) or it may be only the path part of the URL, - // depending on whether the client is a proxy client or a host client. - // - // `url` and `headers` need only remain valid until `request()` returns (they can be - // stack-allocated). - // - // `expectedBodySize`, if provided, must be exactly the number of bytes that will be written to - // the body. This will trigger use of the `Content-Length` connection header. Otherwise, - // `Transfer-Encoding: chunked` will be used. - - struct WebSocketResponse { - uint statusCode; - kj::StringPtr statusText; - const HttpHeaders* headers; - kj::OneOf, kj::Own> upstreamOrBody; - // `statusText` and `headers` remain valid until `upstreamOrBody` is dropped. - }; - virtual kj::Promise openWebSocket( - kj::StringPtr url, const HttpHeaders& headers, kj::Own downstream); - // Tries to open a WebSocket. Default implementation calls send() and never returns a WebSocket. - // - // `url` and `headers` are invalidated when the returned promise resolves. - - virtual kj::Promise> connect(kj::String host); - // Handles CONNECT requests. Only relevant for proxy clients. Default implementation throws - // UNIMPLEMENTED. -}; - -class HttpService { - // Interface which HTTP services should implement. - // - // This interface is functionally equivalent to HttpClient, but is intended for applications to - // implement rather than call. The ergonomics and performance of the method signatures are - // optimized for the serving end. - // - // As with clients, there are two kinds of services: - // * Host services are used when talking to a specific host. The `url` specified in a request - // is actually just a path. (A `Host` header is still required in all requests, and the service - // may in fact serve multiple origins via this header.) - // * Proxy services are used when the target could be any arbitrary host on the internet, i.e. to - // implement an HTTP proxy. The `url` specified in a request is a full URL including protocol - // and hostname. - -public: - class Response { - public: - virtual kj::Own send( - uint statusCode, kj::StringPtr statusText, const HttpHeaders& headers, - kj::Maybe expectedBodySize = nullptr) = 0; - // Begin the response. - // - // `statusText` and `headers` need only remain valid until send() returns (they can be - // stack-allocated). - }; - - virtual kj::Promise request( - HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, - kj::AsyncInputStream& requestBody, Response& response) = 0; - // Perform an HTTP request. - // - // `url` may be a full URL (with protocol and host) or it may be only the path part of the URL, - // depending on whether the service is a proxy service or a host service. - // - // `url` and `headers` are invalidated on the first read from `requestBody` or when the returned - // promise resolves, whichever comes first. - - class WebSocketResponse: public Response { - public: - kj::Own startWebSocket( - uint statusCode, kj::StringPtr statusText, const HttpHeaders& headers, - WebSocket& upstream); - // Begin the response. - // - // `statusText` and `headers` need only remain valid until startWebSocket() returns (they can - // be stack-allocated). - }; - - virtual kj::Promise openWebSocket( - kj::StringPtr url, const HttpHeaders& headers, WebSocketResponse& response); - // Tries to open a WebSocket. Default implementation calls request() and never returns a - // WebSocket. - // - // `url` and `headers` are invalidated when the returned promise resolves. - - virtual kj::Promise> connect(kj::String host); - // Handles CONNECT requests. Only relevant for proxy services. Default implementation throws - // UNIMPLEMENTED. -}; - -kj::Own newHttpClient(HttpHeaderTable& responseHeaderTable, kj::Network& network, - kj::Maybe tlsNetwork = nullptr); -// Creates a proxy HttpClient that connects to hosts over the given network. -// -// `responseHeaderTable` is used when parsing HTTP responses. Requests can use any header table. -// -// `tlsNetwork` is required to support HTTPS destination URLs. Otherwise, only HTTP URLs can be -// fetched. - -kj::Own newHttpClient(HttpHeaderTable& responseHeaderTable, kj::AsyncIoStream& stream); -// Creates an HttpClient that speaks over the given pre-established connection. The client may -// be used as a proxy client or a host client depending on whether the peer is operating as -// a proxy. -// -// Note that since this client has only one stream to work with, it will try to pipeline all -// requests on this stream. If one request or response has an I/O failure, all subsequent requests -// fail as well. If the destination server chooses to close the connection after a response, -// subsequent requests will fail. If a response takes a long time, it blocks subsequent responses. -// If a WebSocket is opened successfully, all subsequent requests fail. - -kj::Own newHttpClient(HttpService& service); -kj::Own newHttpService(HttpClient& client); -// Adapts an HttpClient to an HttpService and vice versa. - -struct HttpServerSettings { - kj::Duration headerTimeout = 15 * kj::SECONDS; - // After initial connection open, or after receiving the first byte of a pipelined request, - // the client must send the complete request within this time. - - kj::Duration pipelineTimeout = 5 * kj::SECONDS; - // After one request/response completes, we'll wait up to this long for a pipelined request to - // arrive. -}; - -class HttpServer: private kj::TaskSet::ErrorHandler { - // Class which listens for requests on ports or connections and sends them to an HttpService. - -public: - typedef HttpServerSettings Settings; - - HttpServer(kj::Timer& timer, HttpHeaderTable& requestHeaderTable, HttpService& service, - Settings settings = Settings()); - // Set up an HttpServer that directs incoming connections to the given service. The service - // may be a host service or a proxy service depending on whether you are intending to implement - // an HTTP server or an HTTP proxy. - - kj::Promise drain(); - // Stop accepting new connections or new requests on existing connections. Finish any requests - // that are already executing, then close the connections. Returns once no more requests are - // in-flight. - - kj::Promise listenHttp(kj::ConnectionReceiver& port); - // Accepts HTTP connections on the given port and directs them to the handler. - // - // The returned promise never completes normally. It may throw if port.accept() throws. Dropping - // the returned promise will cause the server to stop listening on the port, but already-open - // connections will continue to be served. Destroy the whole HttpServer to cancel all I/O. - - kj::Promise listenHttp(kj::Own connection); - // Reads HTTP requests from the given connection and directs them to the handler. A successful - // completion of the promise indicates that all requests received on the connection resulted in - // a complete response, and the client closed the connection gracefully or drain() was called. - // The promise throws if an unparseable request is received or if some I/O error occurs. Dropping - // the returned promise will cancel all I/O on the connection and cancel any in-flight requests. - -private: - class Connection; - - kj::Timer& timer; - HttpHeaderTable& requestHeaderTable; - HttpService& service; - Settings settings; - - bool draining = false; - kj::ForkedPromise onDrain; - kj::Own> drainFulfiller; - - uint connectionCount = 0; - kj::Maybe>> zeroConnectionsFulfiller; - - kj::TaskSet tasks; - - HttpServer(kj::Timer& timer, HttpHeaderTable& requestHeaderTable, HttpService& service, - Settings settings, kj::PromiseFulfillerPair paf); - - kj::Promise listenLoop(kj::ConnectionReceiver& port); - - void taskFailed(kj::Exception&& exception) override; -}; - -// ======================================================================================= -// inline implementation - -inline void HttpHeaderId::requireFrom(HttpHeaderTable& table) const { - KJ_IREQUIRE(this->table == nullptr || this->table == &table, - "the provided HttpHeaderId is from the wrong HttpHeaderTable"); -} - -inline kj::Own HttpHeaderTable::Builder::build() { return kj::mv(table); } -inline HttpHeaderTable& HttpHeaderTable::Builder::getFutureTable() { return *table; } - -inline uint HttpHeaderTable::idCount() { return namesById.size(); } - -inline kj::StringPtr HttpHeaderTable::idToString(HttpHeaderId id) { - id.requireFrom(*this); - return namesById[id.id]; -} - -inline kj::Maybe HttpHeaders::get(HttpHeaderId id) const { - id.requireFrom(*table); - auto result = indexedHeaders[id.id]; - return result == nullptr ? kj::Maybe(nullptr) : result; -} - -inline void HttpHeaders::unset(HttpHeaderId id) { - id.requireFrom(*table); - indexedHeaders[id.id] = nullptr; -} - -template -inline void HttpHeaders::forEach(Func&& func) const { - for (auto i: kj::indices(indexedHeaders)) { - if (indexedHeaders[i] != nullptr) { - func(table->idToString(HttpHeaderId(table, i)), indexedHeaders[i]); - } - } - - for (auto& header: unindexedHeaders) { - func(header.name, header.value); - } -} - -} // namespace kj - -#endif // KJ_COMPAT_HTTP_H_ diff --git a/phonelibs/capnp-cpp/include/kj/debug.h b/phonelibs/capnp-cpp/include/kj/debug.h deleted file mode 100644 index fff7f98bc0..0000000000 --- a/phonelibs/capnp-cpp/include/kj/debug.h +++ /dev/null @@ -1,555 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// This file declares convenient macros for debug logging and error handling. The macros make -// it excessively easy to extract useful context information from code. Example: -// -// KJ_ASSERT(a == b, a, b, "a and b must be the same."); -// -// On failure, this will throw an exception whose description looks like: -// -// myfile.c++:43: bug in code: expected a == b; a = 14; b = 72; a and b must be the same. -// -// As you can see, all arguments after the first provide additional context. -// -// The macros available are: -// -// * `KJ_LOG(severity, ...)`: Just writes a log message, to stderr by default (but you can -// intercept messages by implementing an ExceptionCallback). `severity` is `INFO`, `WARNING`, -// `ERROR`, or `FATAL`. By default, `INFO` logs are not written, but for command-line apps the -// user should be able to pass a flag like `--verbose` to enable them. Other log levels are -// enabled by default. Log messages -- like exceptions -- can be intercepted by registering an -// ExceptionCallback. -// -// * `KJ_DBG(...)`: Like `KJ_LOG`, but intended specifically for temporary log lines added while -// debugging a particular problem. Calls to `KJ_DBG` should always be deleted before committing -// code. It is suggested that you set up a pre-commit hook that checks for this. -// -// * `KJ_ASSERT(condition, ...)`: Throws an exception if `condition` is false, or aborts if -// exceptions are disabled. This macro should be used to check for bugs in the surrounding code -// and its dependencies, but NOT to check for invalid input. The macro may be followed by a -// brace-delimited code block; if so, the block will be executed in the case where the assertion -// fails, before throwing the exception. If control jumps out of the block (e.g. with "break", -// "return", or "goto"), then the error is considered "recoverable" -- in this case, if -// exceptions are disabled, execution will continue normally rather than aborting (but if -// exceptions are enabled, an exception will still be thrown on exiting the block). A "break" -// statement in particular will jump to the code immediately after the block (it does not break -// any surrounding loop or switch). Example: -// -// KJ_ASSERT(value >= 0, "Value cannot be negative.", value) { -// // Assertion failed. Set value to zero to "recover". -// value = 0; -// // Don't abort if exceptions are disabled. Continue normally. -// // (Still throw an exception if they are enabled, though.) -// break; -// } -// // When exceptions are disabled, we'll get here even if the assertion fails. -// // Otherwise, we get here only if the assertion passes. -// -// * `KJ_REQUIRE(condition, ...)`: Like `KJ_ASSERT` but used to check preconditions -- e.g. to -// validate parameters passed from a caller. A failure indicates that the caller is buggy. -// -// * `KJ_SYSCALL(code, ...)`: Executes `code` assuming it makes a system call. A negative result -// is considered an error, with error code reported via `errno`. EINTR is handled by retrying. -// Other errors are handled by throwing an exception. If you need to examine the return code, -// assign it to a variable like so: -// -// int fd; -// KJ_SYSCALL(fd = open(filename, O_RDONLY), filename); -// -// `KJ_SYSCALL` can be followed by a recovery block, just like `KJ_ASSERT`. -// -// * `KJ_NONBLOCKING_SYSCALL(code, ...)`: Like KJ_SYSCALL, but will not throw an exception on -// EAGAIN/EWOULDBLOCK. The calling code should check the syscall's return value to see if it -// indicates an error; in this case, it can assume the error was EAGAIN because any other error -// would have caused an exception to be thrown. -// -// * `KJ_CONTEXT(...)`: Notes additional contextual information relevant to any exceptions thrown -// from within the current scope. That is, until control exits the block in which KJ_CONTEXT() -// is used, if any exception is generated, it will contain the given information in its context -// chain. This is helpful because it can otherwise be very difficult to come up with error -// messages that make sense within low-level helper code. Note that the parameters to -// KJ_CONTEXT() are only evaluated if an exception is thrown. This implies that any variables -// used must remain valid until the end of the scope. -// -// Notes: -// * Do not write expressions with side-effects in the message content part of the macro, as the -// message will not necessarily be evaluated. -// * For every macro `FOO` above except `LOG`, there is also a `FAIL_FOO` macro used to report -// failures that already happened. For the macros that check a boolean condition, `FAIL_FOO` -// omits the first parameter and behaves like it was `false`. `FAIL_SYSCALL` and -// `FAIL_RECOVERABLE_SYSCALL` take a string and an OS error number as the first two parameters. -// The string should be the name of the failed system call. -// * For every macro `FOO` above, there is a `DFOO` version (or `RECOVERABLE_DFOO`) which is only -// executed in debug mode, i.e. when KJ_DEBUG is defined. KJ_DEBUG is defined automatically -// by common.h when compiling without optimization (unless NDEBUG is defined), but you can also -// define it explicitly (e.g. -DKJ_DEBUG). Generally, production builds should NOT use KJ_DEBUG -// as it may enable expensive checks that are unlikely to fail. - -#ifndef KJ_DEBUG_H_ -#define KJ_DEBUG_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "string.h" -#include "exception.h" - -#ifdef ERROR -// This is problematic because windows.h #defines ERROR, which we use in an enum here. -#error "Make sure to to undefine ERROR (or just #include ) before this file" -#endif - -namespace kj { - -#if _MSC_VER -// MSVC does __VA_ARGS__ differently from GCC: -// - A trailing comma before an empty __VA_ARGS__ is removed automatically, whereas GCC wants -// you to request this behavior with "##__VA_ARGS__". -// - If __VA_ARGS__ is passed directly as an argument to another macro, it will be treated as a -// *single* argument rather than an argument list. This can be worked around by wrapping the -// outer macro call in KJ_EXPAND(), which appraently forces __VA_ARGS__ to be expanded before -// the macro is evaluated. I don't understand the C preprocessor. -// - Using "#__VA_ARGS__" to stringify __VA_ARGS__ expands to zero tokens when __VA_ARGS__ is -// empty, rather than expanding to an empty string literal. We can work around by concatenating -// with an empty string literal. - -#define KJ_EXPAND(X) X - -#define KJ_LOG(severity, ...) \ - if (!::kj::_::Debug::shouldLog(::kj::LogSeverity::severity)) {} else \ - ::kj::_::Debug::log(__FILE__, __LINE__, ::kj::LogSeverity::severity, \ - "" #__VA_ARGS__, __VA_ARGS__) - -#define KJ_DBG(...) KJ_EXPAND(KJ_LOG(DBG, __VA_ARGS__)) - -#define KJ_REQUIRE(cond, ...) \ - if (KJ_LIKELY(cond)) {} else \ - for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ - #cond, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) - -#define KJ_FAIL_REQUIRE(...) \ - for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ - nullptr, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) - -#define KJ_SYSCALL(call, ...) \ - if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, false)) {} else \ - for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ - _kjSyscallResult.getErrorNumber(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) - -#define KJ_NONBLOCKING_SYSCALL(call, ...) \ - if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, true)) {} else \ - for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ - _kjSyscallResult.getErrorNumber(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) - -#define KJ_FAIL_SYSCALL(code, errorNumber, ...) \ - for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ - errorNumber, code, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) - -#if _WIN32 - -#define KJ_WIN32(call, ...) \ - if (::kj::_::Debug::isWin32Success(call)) {} else \ - for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ - ::kj::_::Debug::getWin32Error(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) - -#define KJ_WINSOCK(call, ...) \ - if ((call) != SOCKET_ERROR) {} else \ - for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ - ::kj::_::Debug::getWin32Error(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) - -#define KJ_FAIL_WIN32(code, errorNumber, ...) \ - for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ - ::kj::_::Debug::Win32Error(errorNumber), code, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) - -#endif - -#define KJ_UNIMPLEMENTED(...) \ - for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::UNIMPLEMENTED, \ - nullptr, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) - -// TODO(msvc): MSVC mis-deduces `ContextImpl` as `ContextImpl` in some edge -// cases, such as inside nested lambdas inside member functions. Wrapping the type in -// `decltype(instance<...>())` helps it deduce the context function's type correctly. -#define KJ_CONTEXT(...) \ - auto KJ_UNIQUE_NAME(_kjContextFunc) = [&]() -> ::kj::_::Debug::Context::Value { \ - return ::kj::_::Debug::Context::Value(__FILE__, __LINE__, \ - ::kj::_::Debug::makeDescription("" #__VA_ARGS__, __VA_ARGS__)); \ - }; \ - decltype(::kj::instance<::kj::_::Debug::ContextImpl>()) \ - KJ_UNIQUE_NAME(_kjContext)(KJ_UNIQUE_NAME(_kjContextFunc)) - -#define KJ_REQUIRE_NONNULL(value, ...) \ - (*[&] { \ - auto _kj_result = ::kj::_::readMaybe(value); \ - if (KJ_UNLIKELY(!_kj_result)) { \ - ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ - #value " != nullptr", "" #__VA_ARGS__, __VA_ARGS__).fatal(); \ - } \ - return _kj_result; \ - }()) - -#define KJ_EXCEPTION(type, ...) \ - ::kj::Exception(::kj::Exception::Type::type, __FILE__, __LINE__, \ - ::kj::_::Debug::makeDescription("" #__VA_ARGS__, __VA_ARGS__)) - -#else - -#define KJ_LOG(severity, ...) \ - if (!::kj::_::Debug::shouldLog(::kj::LogSeverity::severity)) {} else \ - ::kj::_::Debug::log(__FILE__, __LINE__, ::kj::LogSeverity::severity, \ - #__VA_ARGS__, ##__VA_ARGS__) - -#define KJ_DBG(...) KJ_LOG(DBG, ##__VA_ARGS__) - -#define KJ_REQUIRE(cond, ...) \ - if (KJ_LIKELY(cond)) {} else \ - for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ - #cond, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) - -#define KJ_FAIL_REQUIRE(...) \ - for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ - nullptr, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) - -#define KJ_SYSCALL(call, ...) \ - if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, false)) {} else \ - for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ - _kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) - -#define KJ_NONBLOCKING_SYSCALL(call, ...) \ - if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, true)) {} else \ - for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ - _kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) - -#define KJ_FAIL_SYSCALL(code, errorNumber, ...) \ - for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ - errorNumber, code, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) - -#if _WIN32 - -#define KJ_WIN32(call, ...) \ - if (::kj::_::Debug::isWin32Success(call)) {} else \ - for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ - ::kj::_::Debug::getWin32Error(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) - -#define KJ_WINSOCK(call, ...) \ - if ((call) != SOCKET_ERROR) {} else \ - for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ - ::kj::_::Debug::getWin32Error(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) - -#define KJ_FAIL_WIN32(code, errorNumber, ...) \ - for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ - ::kj::_::Debug::Win32Error(errorNumber), code, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) - -#endif - -#define KJ_UNIMPLEMENTED(...) \ - for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::UNIMPLEMENTED, \ - nullptr, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) - -#define KJ_CONTEXT(...) \ - auto KJ_UNIQUE_NAME(_kjContextFunc) = [&]() -> ::kj::_::Debug::Context::Value { \ - return ::kj::_::Debug::Context::Value(__FILE__, __LINE__, \ - ::kj::_::Debug::makeDescription(#__VA_ARGS__, ##__VA_ARGS__)); \ - }; \ - ::kj::_::Debug::ContextImpl \ - KJ_UNIQUE_NAME(_kjContext)(KJ_UNIQUE_NAME(_kjContextFunc)) - -#define KJ_REQUIRE_NONNULL(value, ...) \ - (*({ \ - auto _kj_result = ::kj::_::readMaybe(value); \ - if (KJ_UNLIKELY(!_kj_result)) { \ - ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ - #value " != nullptr", #__VA_ARGS__, ##__VA_ARGS__).fatal(); \ - } \ - kj::mv(_kj_result); \ - })) - -#define KJ_EXCEPTION(type, ...) \ - ::kj::Exception(::kj::Exception::Type::type, __FILE__, __LINE__, \ - ::kj::_::Debug::makeDescription(#__VA_ARGS__, ##__VA_ARGS__)) - -#endif - -#define KJ_SYSCALL_HANDLE_ERRORS(call) \ - if (int _kjSyscallError = ::kj::_::Debug::syscallError([&](){return (call);}, false)) \ - switch (int error = _kjSyscallError) -// Like KJ_SYSCALL, but doesn't throw. Instead, the block after the macro is a switch block on the -// error. Additionally, the int value `error` is defined within the block. So you can do: -// -// KJ_SYSCALL_HANDLE_ERRORS(foo()) { -// case ENOENT: -// handleNoSuchFile(); -// break; -// case EEXIST: -// handleExists(); -// break; -// default: -// KJ_FAIL_SYSCALL("foo()", error); -// } else { -// handleSuccessCase(); -// } - -#define KJ_ASSERT KJ_REQUIRE -#define KJ_FAIL_ASSERT KJ_FAIL_REQUIRE -#define KJ_ASSERT_NONNULL KJ_REQUIRE_NONNULL -// Use "ASSERT" in place of "REQUIRE" when the problem is local to the immediate surrounding code. -// That is, if the assert ever fails, it indicates that the immediate surrounding code is broken. - -#ifdef KJ_DEBUG -#define KJ_DLOG KJ_LOG -#define KJ_DASSERT KJ_ASSERT -#define KJ_DREQUIRE KJ_REQUIRE -#else -#define KJ_DLOG(...) do {} while (false) -#define KJ_DASSERT(...) do {} while (false) -#define KJ_DREQUIRE(...) do {} while (false) -#endif - -namespace _ { // private - -class Debug { -public: - Debug() = delete; - - typedef LogSeverity Severity; // backwards-compatibility - -#if _WIN32 - struct Win32Error { - // Hack for overloading purposes. - uint number; - inline explicit Win32Error(uint number): number(number) {} - }; -#endif - - static inline bool shouldLog(LogSeverity severity) { return severity >= minSeverity; } - // Returns whether messages of the given severity should be logged. - - static inline void setLogLevel(LogSeverity severity) { minSeverity = severity; } - // Set the minimum message severity which will be logged. - // - // TODO(someday): Expose publicly. - - template - static void log(const char* file, int line, LogSeverity severity, const char* macroArgs, - Params&&... params); - - class Fault { - public: - template - Fault(const char* file, int line, Code code, - const char* condition, const char* macroArgs, Params&&... params); - Fault(const char* file, int line, Exception::Type type, - const char* condition, const char* macroArgs); - Fault(const char* file, int line, int osErrorNumber, - const char* condition, const char* macroArgs); -#if _WIN32 - Fault(const char* file, int line, Win32Error osErrorNumber, - const char* condition, const char* macroArgs); -#endif - ~Fault() noexcept(false); - - KJ_NOINLINE KJ_NORETURN(void fatal()); - // Throw the exception. - - private: - void init(const char* file, int line, Exception::Type type, - const char* condition, const char* macroArgs, ArrayPtr argValues); - void init(const char* file, int line, int osErrorNumber, - const char* condition, const char* macroArgs, ArrayPtr argValues); -#if _WIN32 - void init(const char* file, int line, Win32Error osErrorNumber, - const char* condition, const char* macroArgs, ArrayPtr argValues); -#endif - - Exception* exception; - }; - - class SyscallResult { - public: - inline SyscallResult(int errorNumber): errorNumber(errorNumber) {} - inline operator void*() { return errorNumber == 0 ? this : nullptr; } - inline int getErrorNumber() { return errorNumber; } - - private: - int errorNumber; - }; - - template - static SyscallResult syscall(Call&& call, bool nonblocking); - template - static int syscallError(Call&& call, bool nonblocking); - -#if _WIN32 - static bool isWin32Success(int boolean); - static bool isWin32Success(void* handle); - static Win32Error getWin32Error(); -#endif - - class Context: public ExceptionCallback { - public: - Context(); - KJ_DISALLOW_COPY(Context); - virtual ~Context() noexcept(false); - - struct Value { - const char* file; - int line; - String description; - - inline Value(const char* file, int line, String&& description) - : file(file), line(line), description(mv(description)) {} - }; - - virtual Value evaluate() = 0; - - virtual void onRecoverableException(Exception&& exception) override; - virtual void onFatalException(Exception&& exception) override; - virtual void logMessage(LogSeverity severity, const char* file, int line, int contextDepth, - String&& text) override; - - private: - bool logged; - Maybe value; - - Value ensureInitialized(); - }; - - template - class ContextImpl: public Context { - public: - inline ContextImpl(Func& func): func(func) {} - KJ_DISALLOW_COPY(ContextImpl); - - Value evaluate() override { - return func(); - } - private: - Func& func; - }; - - template - static String makeDescription(const char* macroArgs, Params&&... params); - -private: - static LogSeverity minSeverity; - - static void logInternal(const char* file, int line, LogSeverity severity, const char* macroArgs, - ArrayPtr argValues); - static String makeDescriptionInternal(const char* macroArgs, ArrayPtr argValues); - - static int getOsErrorNumber(bool nonblocking); - // Get the error code of the last error (e.g. from errno). Returns -1 on EINTR. -}; - -template -void Debug::log(const char* file, int line, LogSeverity severity, const char* macroArgs, - Params&&... params) { - String argValues[sizeof...(Params)] = {str(params)...}; - logInternal(file, line, severity, macroArgs, arrayPtr(argValues, sizeof...(Params))); -} - -template <> -inline void Debug::log<>(const char* file, int line, LogSeverity severity, const char* macroArgs) { - logInternal(file, line, severity, macroArgs, nullptr); -} - -template -Debug::Fault::Fault(const char* file, int line, Code code, - const char* condition, const char* macroArgs, Params&&... params) - : exception(nullptr) { - String argValues[sizeof...(Params)] = {str(params)...}; - init(file, line, code, condition, macroArgs, - arrayPtr(argValues, sizeof...(Params))); -} - -inline Debug::Fault::Fault(const char* file, int line, int osErrorNumber, - const char* condition, const char* macroArgs) - : exception(nullptr) { - init(file, line, osErrorNumber, condition, macroArgs, nullptr); -} - -inline Debug::Fault::Fault(const char* file, int line, kj::Exception::Type type, - const char* condition, const char* macroArgs) - : exception(nullptr) { - init(file, line, type, condition, macroArgs, nullptr); -} - -#if _WIN32 -inline Debug::Fault::Fault(const char* file, int line, Win32Error osErrorNumber, - const char* condition, const char* macroArgs) - : exception(nullptr) { - init(file, line, osErrorNumber, condition, macroArgs, nullptr); -} - -inline bool Debug::isWin32Success(int boolean) { - return boolean; -} -inline bool Debug::isWin32Success(void* handle) { - // Assume null and INVALID_HANDLE_VALUE mean failure. - return handle != nullptr && handle != (void*)-1; -} -#endif - -template -Debug::SyscallResult Debug::syscall(Call&& call, bool nonblocking) { - while (call() < 0) { - int errorNum = getOsErrorNumber(nonblocking); - // getOsErrorNumber() returns -1 to indicate EINTR. - // Also, if nonblocking is true, then it returns 0 on EAGAIN, which will then be treated as a - // non-error. - if (errorNum != -1) { - return SyscallResult(errorNum); - } - } - return SyscallResult(0); -} - -template -int Debug::syscallError(Call&& call, bool nonblocking) { - while (call() < 0) { - int errorNum = getOsErrorNumber(nonblocking); - // getOsErrorNumber() returns -1 to indicate EINTR. - // Also, if nonblocking is true, then it returns 0 on EAGAIN, which will then be treated as a - // non-error. - if (errorNum != -1) { - return errorNum; - } - } - return 0; -} - -template -String Debug::makeDescription(const char* macroArgs, Params&&... params) { - String argValues[sizeof...(Params)] = {str(params)...}; - return makeDescriptionInternal(macroArgs, arrayPtr(argValues, sizeof...(Params))); -} - -template <> -inline String Debug::makeDescription<>(const char* macroArgs) { - return makeDescriptionInternal(macroArgs, nullptr); -} - -} // namespace _ (private) -} // namespace kj - -#endif // KJ_DEBUG_H_ diff --git a/phonelibs/capnp-cpp/include/kj/exception.h b/phonelibs/capnp-cpp/include/kj/exception.h deleted file mode 100644 index f6c0b2daa6..0000000000 --- a/phonelibs/capnp-cpp/include/kj/exception.h +++ /dev/null @@ -1,363 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_EXCEPTION_H_ -#define KJ_EXCEPTION_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "memory.h" -#include "array.h" -#include "string.h" - -namespace kj { - -class ExceptionImpl; - -class Exception { - // Exception thrown in case of fatal errors. - // - // Actually, a subclass of this which also implements std::exception will be thrown, but we hide - // that fact from the interface to avoid #including . - -public: - enum class Type { - // What kind of failure? - - FAILED = 0, - // Something went wrong. This is the usual error type. KJ_ASSERT and KJ_REQUIRE throw this - // error type. - - OVERLOADED = 1, - // The call failed because of a temporary lack of resources. This could be space resources - // (out of memory, out of disk space) or time resources (request queue overflow, operation - // timed out). - // - // The operation might work if tried again, but it should NOT be repeated immediately as this - // may simply exacerbate the problem. - - DISCONNECTED = 2, - // The call required communication over a connection that has been lost. The callee will need - // to re-establish connections and try again. - - UNIMPLEMENTED = 3 - // The requested method is not implemented. The caller may wish to revert to a fallback - // approach based on other methods. - - // IF YOU ADD A NEW VALUE: - // - Update the stringifier. - // - Update Cap'n Proto's RPC protocol's Exception.Type enum. - }; - - Exception(Type type, const char* file, int line, String description = nullptr) noexcept; - Exception(Type type, String file, int line, String description = nullptr) noexcept; - Exception(const Exception& other) noexcept; - Exception(Exception&& other) = default; - ~Exception() noexcept; - - const char* getFile() const { return file; } - int getLine() const { return line; } - Type getType() const { return type; } - StringPtr getDescription() const { return description; } - ArrayPtr getStackTrace() const { return arrayPtr(trace, traceCount); } - - struct Context { - // Describes a bit about what was going on when the exception was thrown. - - const char* file; - int line; - String description; - Maybe> next; - - Context(const char* file, int line, String&& description, Maybe>&& next) - : file(file), line(line), description(mv(description)), next(mv(next)) {} - Context(const Context& other) noexcept; - }; - - inline Maybe getContext() const { - KJ_IF_MAYBE(c, context) { - return **c; - } else { - return nullptr; - } - } - - void wrapContext(const char* file, int line, String&& description); - // Wraps the context in a new node. This becomes the head node returned by getContext() -- it - // is expected that contexts will be added in reverse order as the exception passes up the - // callback stack. - - KJ_NOINLINE void extendTrace(uint ignoreCount); - // Append the current stack trace to the exception's trace, ignoring the first `ignoreCount` - // frames (see `getStackTrace()` for discussion of `ignoreCount`). - - KJ_NOINLINE void truncateCommonTrace(); - // Remove the part of the stack trace which the exception shares with the caller of this method. - // This is used by the async library to remove the async infrastructure from the stack trace - // before replacing it with the async trace. - - void addTrace(void* ptr); - // Append the given pointer to the backtrace, if it is not already full. This is used by the - // async library to trace through the promise chain that led to the exception. - -private: - String ownFile; - const char* file; - int line; - Type type; - String description; - Maybe> context; - void* trace[32]; - uint traceCount; - - friend class ExceptionImpl; -}; - -StringPtr KJ_STRINGIFY(Exception::Type type); -String KJ_STRINGIFY(const Exception& e); - -// ======================================================================================= - -enum class LogSeverity { - INFO, // Information describing what the code is up to, which users may request to see - // with a flag like `--verbose`. Does not indicate a problem. Not printed by - // default; you must call setLogLevel(INFO) to enable. - WARNING, // A problem was detected but execution can continue with correct output. - ERROR, // Something is wrong, but execution can continue with garbage output. - FATAL, // Something went wrong, and execution cannot continue. - DBG // Temporary debug logging. See KJ_DBG. - - // Make sure to update the stringifier if you add a new severity level. -}; - -StringPtr KJ_STRINGIFY(LogSeverity severity); - -class ExceptionCallback { - // If you don't like C++ exceptions, you may implement and register an ExceptionCallback in order - // to perform your own exception handling. For example, a reasonable thing to do is to have - // onRecoverableException() set a flag indicating that an error occurred, and then check for that - // flag just before writing to storage and/or returning results to the user. If the flag is set, - // discard whatever you have and return an error instead. - // - // ExceptionCallbacks must always be allocated on the stack. When an exception is thrown, the - // newest ExceptionCallback on the calling thread's stack is called. The default implementation - // of each method calls the next-oldest ExceptionCallback for that thread. Thus the callbacks - // behave a lot like try/catch blocks, except that they are called before any stack unwinding - // occurs. - -public: - ExceptionCallback(); - KJ_DISALLOW_COPY(ExceptionCallback); - virtual ~ExceptionCallback() noexcept(false); - - virtual void onRecoverableException(Exception&& exception); - // Called when an exception has been raised, but the calling code has the ability to continue by - // producing garbage output. This method _should_ throw the exception, but is allowed to simply - // return if garbage output is acceptable. - // - // The global default implementation throws an exception unless the library was compiled with - // -fno-exceptions, in which case it logs an error and returns. - - virtual void onFatalException(Exception&& exception); - // Called when an exception has been raised and the calling code cannot continue. If this method - // returns normally, abort() will be called. The method must throw the exception to avoid - // aborting. - // - // The global default implementation throws an exception unless the library was compiled with - // -fno-exceptions, in which case it logs an error and returns. - - virtual void logMessage(LogSeverity severity, const char* file, int line, int contextDepth, - String&& text); - // Called when something wants to log some debug text. `contextDepth` indicates how many levels - // of context the message passed through; it may make sense to indent the message accordingly. - // - // The global default implementation writes the text to stderr. - - enum class StackTraceMode { - FULL, - // Stringifying a stack trace will attempt to determine source file and line numbers. This may - // be expensive. For example, on Linux, this shells out to `addr2line`. - // - // This is the default in debug builds. - - ADDRESS_ONLY, - // Stringifying a stack trace will only generate a list of code addresses. - // - // This is the default in release builds. - - NONE - // Generating a stack trace will always return an empty array. - // - // This avoids ever unwinding the stack. On Windows in particular, the stack unwinding library - // has been observed to be pretty slow, so exception-heavy code might benefit significantly - // from this setting. (But exceptions should be rare...) - }; - - virtual StackTraceMode stackTraceMode(); - // Returns the current preferred stack trace mode. - -protected: - ExceptionCallback& next; - -private: - ExceptionCallback(ExceptionCallback& next); - - class RootExceptionCallback; - friend ExceptionCallback& getExceptionCallback(); -}; - -ExceptionCallback& getExceptionCallback(); -// Returns the current exception callback. - -KJ_NOINLINE KJ_NORETURN(void throwFatalException(kj::Exception&& exception, uint ignoreCount = 0)); -// Invoke the exception callback to throw the given fatal exception. If the exception callback -// returns, abort. - -KJ_NOINLINE void throwRecoverableException(kj::Exception&& exception, uint ignoreCount = 0); -// Invoke the exception callback to throw the given recoverable exception. If the exception -// callback returns, return normally. - -// ======================================================================================= - -namespace _ { class Runnable; } - -template -Maybe runCatchingExceptions(Func&& func) noexcept; -// Executes the given function (usually, a lambda returning nothing) catching any exceptions that -// are thrown. Returns the Exception if there was one, or null if the operation completed normally. -// Non-KJ exceptions will be wrapped. -// -// If exception are disabled (e.g. with -fno-exceptions), this will still detect whether any -// recoverable exceptions occurred while running the function and will return those. - -class UnwindDetector { - // Utility for detecting when a destructor is called due to unwind. Useful for: - // - Avoiding throwing exceptions in this case, which would terminate the program. - // - Detecting whether to commit or roll back a transaction. - // - // To use this class, either inherit privately from it or declare it as a member. The detector - // works by comparing the exception state against that when the constructor was called, so for - // an object that was actually constructed during exception unwind, it will behave as if no - // unwind is taking place. This is usually the desired behavior. - -public: - UnwindDetector(); - - bool isUnwinding() const; - // Returns true if the current thread is in a stack unwind that it wasn't in at the time the - // object was constructed. - - template - void catchExceptionsIfUnwinding(Func&& func) const; - // Runs the given function (e.g., a lambda). If isUnwinding() is true, any exceptions are - // caught and treated as secondary faults, meaning they are considered to be side-effects of the - // exception that is unwinding the stack. Otherwise, exceptions are passed through normally. - -private: - uint uncaughtCount; - - void catchExceptionsAsSecondaryFaults(_::Runnable& runnable) const; -}; - -namespace _ { // private - -class Runnable { -public: - virtual void run() = 0; -}; - -template -class RunnableImpl: public Runnable { -public: - RunnableImpl(Func&& func): func(kj::mv(func)) {} - void run() override { - func(); - } -private: - Func func; -}; - -Maybe runCatchingExceptions(Runnable& runnable) noexcept; - -} // namespace _ (private) - -template -Maybe runCatchingExceptions(Func&& func) noexcept { - _::RunnableImpl> runnable(kj::fwd(func)); - return _::runCatchingExceptions(runnable); -} - -template -void UnwindDetector::catchExceptionsIfUnwinding(Func&& func) const { - if (isUnwinding()) { - _::RunnableImpl> runnable(kj::fwd(func)); - catchExceptionsAsSecondaryFaults(runnable); - } else { - func(); - } -} - -#define KJ_ON_SCOPE_SUCCESS(code) \ - ::kj::UnwindDetector KJ_UNIQUE_NAME(_kjUnwindDetector); \ - KJ_DEFER(if (!KJ_UNIQUE_NAME(_kjUnwindDetector).isUnwinding()) { code; }) -// Runs `code` if the current scope is exited normally (not due to an exception). - -#define KJ_ON_SCOPE_FAILURE(code) \ - ::kj::UnwindDetector KJ_UNIQUE_NAME(_kjUnwindDetector); \ - KJ_DEFER(if (KJ_UNIQUE_NAME(_kjUnwindDetector).isUnwinding()) { code; }) -// Runs `code` if the current scope is exited due to an exception. - -// ======================================================================================= - -KJ_NOINLINE ArrayPtr getStackTrace(ArrayPtr space, uint ignoreCount); -// Attempt to get the current stack trace, returning a list of pointers to instructions. The -// returned array is a slice of `space`. Provide a larger `space` to get a deeper stack trace. -// If the platform doesn't support stack traces, returns an empty array. -// -// `ignoreCount` items will be truncated from the front of the trace. This is useful for chopping -// off a prefix of the trace that is uninteresting to the developer because it's just locations -// inside the debug infrastructure that is requesting the trace. Be careful to mark functions as -// KJ_NOINLINE if you intend to count them in `ignoreCount`. Note that, unfortunately, the -// ignored entries will still waste space in the `space` array (and the returned array's `begin()` -// is never exactly equal to `space.begin()` due to this effect, even if `ignoreCount` is zero -// since `getStackTrace()` needs to ignore its own internal frames). - -String stringifyStackTrace(ArrayPtr); -// Convert the stack trace to a string with file names and line numbers. This may involve executing -// suprocesses. - -String getStackTrace(); -// Get a stack trace right now and stringify it. Useful for debugging. - -void printStackTraceOnCrash(); -// Registers signal handlers on common "crash" signals like SIGSEGV that will (attempt to) print -// a stack trace. You should call this as early as possible on program startup. Programs using -// KJ_MAIN get this automatically. - -kj::StringPtr trimSourceFilename(kj::StringPtr filename); -// Given a source code file name, trim off noisy prefixes like "src/" or -// "/ekam-provider/canonical/". - -} // namespace kj - -#endif // KJ_EXCEPTION_H_ diff --git a/phonelibs/capnp-cpp/include/kj/function.h b/phonelibs/capnp-cpp/include/kj/function.h deleted file mode 100644 index ba6601b560..0000000000 --- a/phonelibs/capnp-cpp/include/kj/function.h +++ /dev/null @@ -1,277 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_FUNCTION_H_ -#define KJ_FUNCTION_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "memory.h" - -namespace kj { - -template -class Function; -// Function wrapper using virtual-based polymorphism. Use this when template polymorphism is -// not possible. You can, for example, accept a Function as a parameter: -// -// void setFilter(Function filter); -// -// The caller of `setFilter()` may then pass any callable object as the parameter. The callable -// object does not have to have the exact signature specified, just one that is "compatible" -- -// i.e. the return type is covariant and the parameters are contravariant. -// -// Unlike `std::function`, `kj::Function`s are movable but not copyable, just like `kj::Own`. This -// is to avoid unexpected heap allocation or slow atomic reference counting. -// -// When a `Function` is constructed from an lvalue, it captures only a reference to the value. -// When constructed from an rvalue, it invokes the value's move constructor. So, for example: -// -// struct AddN { -// int n; -// int operator(int i) { return i + n; } -// } -// -// Function f1 = AddN{2}; -// // f1 owns an instance of AddN. It may safely be moved out -// // of the local scope. -// -// AddN adder(2); -// Function f2 = adder; -// // f2 contains a reference to `adder`. Thus, it becomes invalid -// // when `adder` goes out-of-scope. -// -// AddN adder2(2); -// Function f3 = kj::mv(adder2); -// // f3 owns an insatnce of AddN moved from `adder2`. f3 may safely -// // be moved out of the local scope. -// -// Additionally, a Function may be bound to a class method using KJ_BIND_METHOD(object, methodName). -// For example: -// -// class Printer { -// public: -// void print(int i); -// void print(kj::StringPtr s); -// }; -// -// Printer p; -// -// Function intPrinter = KJ_BIND_METHOD(p, print); -// // Will call Printer::print(int). -// -// Function strPrinter = KJ_BIND_METHOD(p, print); -// // Will call Printer::print(kj::StringPtr). -// -// Notice how KJ_BIND_METHOD is able to figure out which overload to use depending on the kind of -// Function it is binding to. - -template -class ConstFunction; -// Like Function, but wraps a "const" (i.e. thread-safe) call. - -template -class Function { -public: - template - inline Function(F&& f): impl(heap>(kj::fwd(f))) {} - Function() = default; - - // Make sure people don't accidentally end up wrapping a reference when they meant to return - // a function. - KJ_DISALLOW_COPY(Function); - Function(Function&) = delete; - Function& operator=(Function&) = delete; - template Function(const Function&) = delete; - template Function& operator=(const Function&) = delete; - template Function(const ConstFunction&) = delete; - template Function& operator=(const ConstFunction&) = delete; - Function(Function&&) = default; - Function& operator=(Function&&) = default; - - inline Return operator()(Params... params) { - return (*impl)(kj::fwd(params)...); - } - - Function reference() { - // Forms a new Function of the same type that delegates to this Function by reference. - // Therefore, this Function must outlive the returned Function, but otherwise they behave - // exactly the same. - - return *impl; - } - -private: - class Iface { - public: - virtual Return operator()(Params... params) = 0; - }; - - template - class Impl final: public Iface { - public: - explicit Impl(F&& f): f(kj::fwd(f)) {} - - Return operator()(Params... params) override { - return f(kj::fwd(params)...); - } - - private: - F f; - }; - - Own impl; -}; - -template -class ConstFunction { -public: - template - inline ConstFunction(F&& f): impl(heap>(kj::fwd(f))) {} - ConstFunction() = default; - - // Make sure people don't accidentally end up wrapping a reference when they meant to return - // a function. - KJ_DISALLOW_COPY(ConstFunction); - ConstFunction(ConstFunction&) = delete; - ConstFunction& operator=(ConstFunction&) = delete; - template ConstFunction(const ConstFunction&) = delete; - template ConstFunction& operator=(const ConstFunction&) = delete; - template ConstFunction(const Function&) = delete; - template ConstFunction& operator=(const Function&) = delete; - ConstFunction(ConstFunction&&) = default; - ConstFunction& operator=(ConstFunction&&) = default; - - inline Return operator()(Params... params) const { - return (*impl)(kj::fwd(params)...); - } - - ConstFunction reference() const { - // Forms a new ConstFunction of the same type that delegates to this ConstFunction by reference. - // Therefore, this ConstFunction must outlive the returned ConstFunction, but otherwise they - // behave exactly the same. - - return *impl; - } - -private: - class Iface { - public: - virtual Return operator()(Params... params) const = 0; - }; - - template - class Impl final: public Iface { - public: - explicit Impl(F&& f): f(kj::fwd(f)) {} - - Return operator()(Params... params) const override { - return f(kj::fwd(params)...); - } - - private: - F f; - }; - - Own impl; -}; - -#if 1 - -namespace _ { // private - -template -class BoundMethod; - -template ::*method)(Params...)> -class BoundMethod::*)(Params...), method> { -public: - BoundMethod(T&& t): t(kj::fwd(t)) {} - - Return operator()(Params&&... params) { - return (t.*method)(kj::fwd(params)...); - } - -private: - T t; -}; - -template ::*method)(Params...) const> -class BoundMethod::*)(Params...) const, method> { -public: - BoundMethod(T&& t): t(kj::fwd(t)) {} - - Return operator()(Params&&... params) const { - return (t.*method)(kj::fwd(params)...); - } - -private: - T t; -}; - -} // namespace _ (private) - -#define KJ_BIND_METHOD(obj, method) \ - ::kj::_::BoundMethod::method), \ - &::kj::Decay::method>(obj) -// Macro that produces a functor object which forwards to the method `obj.name`. If `obj` is an -// lvalue, the functor will hold a reference to it. If `obj` is an rvalue, the functor will -// contain a copy (by move) of it. -// -// The current implementation requires that the method is not overloaded. -// -// TODO(someday): C++14's generic lambdas may be able to simplify this code considerably, and -// probably make it work with overloaded methods. - -#else -// Here's a better implementation of the above that doesn't work with GCC (but does with Clang) -// because it uses a local class with a template method. Sigh. This implementation supports -// overloaded methods. - -#define KJ_BIND_METHOD(obj, method) \ - ({ \ - typedef KJ_DECLTYPE_REF(obj) T; \ - class F { \ - public: \ - inline F(T&& t): t(::kj::fwd(t)) {} \ - template \ - auto operator()(Params&&... params) \ - -> decltype(::kj::instance().method(::kj::fwd(params)...)) { \ - return t.method(::kj::fwd(params)...); \ - } \ - private: \ - T t; \ - }; \ - (F(obj)); \ - }) -// Macro that produces a functor object which forwards to the method `obj.name`. If `obj` is an -// lvalue, the functor will hold a reference to it. If `obj` is an rvalue, the functor will -// contain a copy (by move) of it. - -#endif - -} // namespace kj - -#endif // KJ_FUNCTION_H_ diff --git a/phonelibs/capnp-cpp/include/kj/io.h b/phonelibs/capnp-cpp/include/kj/io.h deleted file mode 100644 index f5c03bfe7b..0000000000 --- a/phonelibs/capnp-cpp/include/kj/io.h +++ /dev/null @@ -1,419 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_IO_H_ -#define KJ_IO_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include -#include "common.h" -#include "array.h" -#include "exception.h" - -namespace kj { - -// ======================================================================================= -// Abstract interfaces - -class InputStream { -public: - virtual ~InputStream() noexcept(false); - - size_t read(void* buffer, size_t minBytes, size_t maxBytes); - // Reads at least minBytes and at most maxBytes, copying them into the given buffer. Returns - // the size read. Throws an exception on errors. Implemented in terms of tryRead(). - // - // maxBytes is the number of bytes the caller really wants, but minBytes is the minimum amount - // needed by the caller before it can start doing useful processing. If the stream returns less - // than maxBytes, the caller will usually call read() again later to get the rest. Returning - // less than maxBytes is useful when it makes sense for the caller to parallelize processing - // with I/O. - // - // Never blocks if minBytes is zero. If minBytes is zero and maxBytes is non-zero, this may - // attempt a non-blocking read or may just return zero. To force a read, use a non-zero minBytes. - // To detect EOF without throwing an exception, use tryRead(). - // - // If the InputStream can't produce minBytes, it MUST throw an exception, as the caller is not - // expected to understand how to deal with partial reads. - - virtual size_t tryRead(void* buffer, size_t minBytes, size_t maxBytes) = 0; - // Like read(), but may return fewer than minBytes on EOF. - - inline void read(void* buffer, size_t bytes) { read(buffer, bytes, bytes); } - // Convenience method for reading an exact number of bytes. - - virtual void skip(size_t bytes); - // Skips past the given number of bytes, discarding them. The default implementation read()s - // into a scratch buffer. -}; - -class OutputStream { -public: - virtual ~OutputStream() noexcept(false); - - virtual void write(const void* buffer, size_t size) = 0; - // Always writes the full size. Throws exception on error. - - virtual void write(ArrayPtr> pieces); - // Equivalent to write()ing each byte array in sequence, which is what the default implementation - // does. Override if you can do something better, e.g. use writev() to do the write in a single - // syscall. -}; - -class BufferedInputStream: public InputStream { - // An input stream which buffers some bytes in memory to reduce system call overhead. - // - OR - - // An input stream that actually reads from some in-memory data structure and wants to give its - // caller a direct pointer to that memory to potentially avoid a copy. - -public: - virtual ~BufferedInputStream() noexcept(false); - - ArrayPtr getReadBuffer(); - // Get a direct pointer into the read buffer, which contains the next bytes in the input. If the - // caller consumes any bytes, it should then call skip() to indicate this. This always returns a - // non-empty buffer or throws an exception. Implemented in terms of tryGetReadBuffer(). - - virtual ArrayPtr tryGetReadBuffer() = 0; - // Like getReadBuffer() but may return an empty buffer on EOF. -}; - -class BufferedOutputStream: public OutputStream { - // An output stream which buffers some bytes in memory to reduce system call overhead. - // - OR - - // An output stream that actually writes into some in-memory data structure and wants to give its - // caller a direct pointer to that memory to potentially avoid a copy. - -public: - virtual ~BufferedOutputStream() noexcept(false); - - virtual ArrayPtr getWriteBuffer() = 0; - // Get a direct pointer into the write buffer. The caller may choose to fill in some prefix of - // this buffer and then pass it to write(), in which case write() may avoid a copy. It is - // incorrect to pass to write any slice of this buffer which is not a prefix. -}; - -// ======================================================================================= -// Buffered streams implemented as wrappers around regular streams - -class BufferedInputStreamWrapper: public BufferedInputStream { - // Implements BufferedInputStream in terms of an InputStream. - // - // Note that the underlying stream's position is unpredictable once the wrapper is destroyed, - // unless the entire stream was consumed. To read a predictable number of bytes in a buffered - // way without going over, you'd need this wrapper to wrap some other wrapper which itself - // implements an artificial EOF at the desired point. Such a stream should be trivial to write - // but is not provided by the library at this time. - -public: - explicit BufferedInputStreamWrapper(InputStream& inner, ArrayPtr buffer = nullptr); - // Creates a buffered stream wrapping the given non-buffered stream. No guarantee is made about - // the position of the inner stream after a buffered wrapper has been created unless the entire - // input is read. - // - // If the second parameter is non-null, the stream uses the given buffer instead of allocating - // its own. This may improve performance if the buffer can be reused. - - KJ_DISALLOW_COPY(BufferedInputStreamWrapper); - ~BufferedInputStreamWrapper() noexcept(false); - - // implements BufferedInputStream ---------------------------------- - ArrayPtr tryGetReadBuffer() override; - size_t tryRead(void* buffer, size_t minBytes, size_t maxBytes) override; - void skip(size_t bytes) override; - -private: - InputStream& inner; - Array ownedBuffer; - ArrayPtr buffer; - ArrayPtr bufferAvailable; -}; - -class BufferedOutputStreamWrapper: public BufferedOutputStream { - // Implements BufferedOutputStream in terms of an OutputStream. Note that writes to the - // underlying stream may be delayed until flush() is called or the wrapper is destroyed. - -public: - explicit BufferedOutputStreamWrapper(OutputStream& inner, ArrayPtr buffer = nullptr); - // Creates a buffered stream wrapping the given non-buffered stream. - // - // If the second parameter is non-null, the stream uses the given buffer instead of allocating - // its own. This may improve performance if the buffer can be reused. - - KJ_DISALLOW_COPY(BufferedOutputStreamWrapper); - ~BufferedOutputStreamWrapper() noexcept(false); - - void flush(); - // Force the wrapper to write any remaining bytes in its buffer to the inner stream. Note that - // this only flushes this object's buffer; this object has no idea how to flush any other buffers - // that may be present in the underlying stream. - - // implements BufferedOutputStream --------------------------------- - ArrayPtr getWriteBuffer() override; - void write(const void* buffer, size_t size) override; - -private: - OutputStream& inner; - Array ownedBuffer; - ArrayPtr buffer; - byte* bufferPos; - UnwindDetector unwindDetector; -}; - -// ======================================================================================= -// Array I/O - -class ArrayInputStream: public BufferedInputStream { -public: - explicit ArrayInputStream(ArrayPtr array); - KJ_DISALLOW_COPY(ArrayInputStream); - ~ArrayInputStream() noexcept(false); - - // implements BufferedInputStream ---------------------------------- - ArrayPtr tryGetReadBuffer() override; - size_t tryRead(void* buffer, size_t minBytes, size_t maxBytes) override; - void skip(size_t bytes) override; - -private: - ArrayPtr array; -}; - -class ArrayOutputStream: public BufferedOutputStream { -public: - explicit ArrayOutputStream(ArrayPtr array); - KJ_DISALLOW_COPY(ArrayOutputStream); - ~ArrayOutputStream() noexcept(false); - - ArrayPtr getArray() { - // Get the portion of the array which has been filled in. - return arrayPtr(array.begin(), fillPos); - } - - // implements BufferedInputStream ---------------------------------- - ArrayPtr getWriteBuffer() override; - void write(const void* buffer, size_t size) override; - -private: - ArrayPtr array; - byte* fillPos; -}; - -class VectorOutputStream: public BufferedOutputStream { -public: - explicit VectorOutputStream(size_t initialCapacity = 4096); - KJ_DISALLOW_COPY(VectorOutputStream); - ~VectorOutputStream() noexcept(false); - - ArrayPtr getArray() { - // Get the portion of the array which has been filled in. - return arrayPtr(vector.begin(), fillPos); - } - - // implements BufferedInputStream ---------------------------------- - ArrayPtr getWriteBuffer() override; - void write(const void* buffer, size_t size) override; - -private: - Array vector; - byte* fillPos; - - void grow(size_t minSize); -}; - -// ======================================================================================= -// File descriptor I/O - -class AutoCloseFd { - // A wrapper around a file descriptor which automatically closes the descriptor when destroyed. - // The wrapper supports move construction for transferring ownership of the descriptor. If - // close() returns an error, the destructor throws an exception, UNLESS the destructor is being - // called during unwind from another exception, in which case the close error is ignored. - // - // If your code is not exception-safe, you should not use AutoCloseFd. In this case you will - // have to call close() yourself and handle errors appropriately. - -public: - inline AutoCloseFd(): fd(-1) {} - inline AutoCloseFd(decltype(nullptr)): fd(-1) {} - inline explicit AutoCloseFd(int fd): fd(fd) {} - inline AutoCloseFd(AutoCloseFd&& other) noexcept: fd(other.fd) { other.fd = -1; } - KJ_DISALLOW_COPY(AutoCloseFd); - ~AutoCloseFd() noexcept(false); - - inline AutoCloseFd& operator=(AutoCloseFd&& other) { - AutoCloseFd old(kj::mv(*this)); - fd = other.fd; - other.fd = -1; - return *this; - } - - inline AutoCloseFd& operator=(decltype(nullptr)) { - AutoCloseFd old(kj::mv(*this)); - return *this; - } - - inline operator int() const { return fd; } - inline int get() const { return fd; } - - operator bool() const = delete; - // Deleting this operator prevents accidental use in boolean contexts, which - // the int conversion operator above would otherwise allow. - - inline bool operator==(decltype(nullptr)) { return fd < 0; } - inline bool operator!=(decltype(nullptr)) { return fd >= 0; } - -private: - int fd; - UnwindDetector unwindDetector; -}; - -inline auto KJ_STRINGIFY(const AutoCloseFd& fd) - -> decltype(kj::toCharSequence(implicitCast(fd))) { - return kj::toCharSequence(implicitCast(fd)); -} - -class FdInputStream: public InputStream { - // An InputStream wrapping a file descriptor. - -public: - explicit FdInputStream(int fd): fd(fd) {} - explicit FdInputStream(AutoCloseFd fd): fd(fd), autoclose(mv(fd)) {} - KJ_DISALLOW_COPY(FdInputStream); - ~FdInputStream() noexcept(false); - - size_t tryRead(void* buffer, size_t minBytes, size_t maxBytes) override; - - inline int getFd() const { return fd; } - -private: - int fd; - AutoCloseFd autoclose; -}; - -class FdOutputStream: public OutputStream { - // An OutputStream wrapping a file descriptor. - -public: - explicit FdOutputStream(int fd): fd(fd) {} - explicit FdOutputStream(AutoCloseFd fd): fd(fd), autoclose(mv(fd)) {} - KJ_DISALLOW_COPY(FdOutputStream); - ~FdOutputStream() noexcept(false); - - void write(const void* buffer, size_t size) override; - void write(ArrayPtr> pieces) override; - - inline int getFd() const { return fd; } - -private: - int fd; - AutoCloseFd autoclose; -}; - -// ======================================================================================= -// Win32 Handle I/O - -#ifdef _WIN32 - -class AutoCloseHandle { - // A wrapper around a Win32 HANDLE which automatically closes the handle when destroyed. - // The wrapper supports move construction for transferring ownership of the handle. If - // CloseHandle() returns an error, the destructor throws an exception, UNLESS the destructor is - // being called during unwind from another exception, in which case the close error is ignored. - // - // If your code is not exception-safe, you should not use AutoCloseHandle. In this case you will - // have to call close() yourself and handle errors appropriately. - -public: - inline AutoCloseHandle(): handle((void*)-1) {} - inline AutoCloseHandle(decltype(nullptr)): handle((void*)-1) {} - inline explicit AutoCloseHandle(void* handle): handle(handle) {} - inline AutoCloseHandle(AutoCloseHandle&& other) noexcept: handle(other.handle) { - other.handle = (void*)-1; - } - KJ_DISALLOW_COPY(AutoCloseHandle); - ~AutoCloseHandle() noexcept(false); - - inline AutoCloseHandle& operator=(AutoCloseHandle&& other) { - AutoCloseHandle old(kj::mv(*this)); - handle = other.handle; - other.handle = (void*)-1; - return *this; - } - - inline AutoCloseHandle& operator=(decltype(nullptr)) { - AutoCloseHandle old(kj::mv(*this)); - return *this; - } - - inline operator void*() const { return handle; } - inline void* get() const { return handle; } - - operator bool() const = delete; - // Deleting this operator prevents accidental use in boolean contexts, which - // the void* conversion operator above would otherwise allow. - - inline bool operator==(decltype(nullptr)) { return handle != (void*)-1; } - inline bool operator!=(decltype(nullptr)) { return handle == (void*)-1; } - -private: - void* handle; // -1 (aka INVALID_HANDLE_VALUE) if not valid. -}; - -class HandleInputStream: public InputStream { - // An InputStream wrapping a Win32 HANDLE. - -public: - explicit HandleInputStream(void* handle): handle(handle) {} - explicit HandleInputStream(AutoCloseHandle handle): handle(handle), autoclose(mv(handle)) {} - KJ_DISALLOW_COPY(HandleInputStream); - ~HandleInputStream() noexcept(false); - - size_t tryRead(void* buffer, size_t minBytes, size_t maxBytes) override; - -private: - void* handle; - AutoCloseHandle autoclose; -}; - -class HandleOutputStream: public OutputStream { - // An OutputStream wrapping a Win32 HANDLE. - -public: - explicit HandleOutputStream(void* handle): handle(handle) {} - explicit HandleOutputStream(AutoCloseHandle handle): handle(handle), autoclose(mv(handle)) {} - KJ_DISALLOW_COPY(HandleOutputStream); - ~HandleOutputStream() noexcept(false); - - void write(const void* buffer, size_t size) override; - -private: - void* handle; - AutoCloseHandle autoclose; -}; - -#endif // _WIN32 - -} // namespace kj - -#endif // KJ_IO_H_ diff --git a/phonelibs/capnp-cpp/include/kj/main.h b/phonelibs/capnp-cpp/include/kj/main.h deleted file mode 100644 index 4dcd804fd4..0000000000 --- a/phonelibs/capnp-cpp/include/kj/main.h +++ /dev/null @@ -1,407 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_MAIN_H_ -#define KJ_MAIN_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "array.h" -#include "string.h" -#include "vector.h" -#include "function.h" - -namespace kj { - -class ProcessContext { - // Context for command-line programs. - -public: - virtual StringPtr getProgramName() = 0; - // Get argv[0] as passed to main(). - - KJ_NORETURN(virtual void exit()) = 0; - // Indicates program completion. The program is considered successful unless `error()` was - // called. Typically this exits with _Exit(), meaning that the stack is not unwound, buffers - // are not flushed, etc. -- it is the responsibility of the caller to flush any buffers that - // matter. However, an alternate context implementation e.g. for unit testing purposes could - // choose to throw an exception instead. - // - // At first this approach may sound crazy. Isn't it much better to shut down cleanly? What if - // you lose data? However, it turns out that if you look at each common class of program, _Exit() - // is almost always preferable. Let's break it down: - // - // * Commands: A typical program you might run from the command line is single-threaded and - // exits quickly and deterministically. Commands often use buffered I/O and need to flush - // those buffers before exit. However, most of the work performed by destructors is not - // flushing buffers, but rather freeing up memory, placing objects into freelists, and closing - // file descriptors. All of this is irrelevant if the process is about to exit anyway, and - // for a command that runs quickly, time wasted freeing heap space may make a real difference - // in the overall runtime of a script. Meanwhile, it is usually easy to determine exactly what - // resources need to be flushed before exit, and easy to tell if they are not being flushed - // (because the command fails to produce the expected output). Therefore, it is reasonably - // easy for commands to explicitly ensure all output is flushed before exiting, and it is - // probably a good idea for them to do so anyway, because write failures should be detected - // and handled. For commands, a good strategy is to allocate any objects that require clean - // destruction on the stack, and allow them to go out of scope before the command exits. - // Meanwhile, any resources which do not need to be cleaned up should be allocated as members - // of the command's main class, whose destructor normally will not be called. - // - // * Interactive apps: Programs that interact with the user (whether they be graphical apps - // with windows or console-based apps like emacs) generally exit only when the user asks them - // to. Such applications may store large data structures in memory which need to be synced - // to disk, such as documents or user preferences. However, relying on stack unwind or global - // destructors as the mechanism for ensuring such syncing occurs is probably wrong. First of - // all, it's 2013, and applications ought to be actively syncing changes to non-volatile - // storage the moment those changes are made. Applications can crash at any time and a crash - // should never lose data that is more than half a second old. Meanwhile, if a user actually - // does try to close an application while unsaved changes exist, the application UI should - // prompt the user to decide what to do. Such a UI mechanism is obviously too high level to - // be implemented via destructors, so KJ's use of _Exit() shouldn't make a difference here. - // - // * Servers: A good server is fault-tolerant, prepared for the possibility that at any time - // it could crash, the OS could decide to kill it off, or the machine it is running on could - // just die. So, using _Exit() should be no problem. In fact, servers generally never even - // call exit anyway; they are killed externally. - // - // * Batch jobs: A long-running batch job is something between a command and a server. It - // probably knows exactly what needs to be flushed before exiting, and it probably should be - // fault-tolerant. - // - // Meanwhile, regardless of program type, if you are adhering to KJ style, then the use of - // _Exit() shouldn't be a problem anyway: - // - // * KJ style forbids global mutable state (singletons) in general and global constructors and - // destructors in particular. Therefore, everything that could possibly need cleanup either - // lives on the stack or is transitively owned by something living on the stack. - // - // * Calling exit() simply means "Don't clean up anything older than this stack frame.". If you - // have resources that require cleanup before exit, make sure they are owned by stack frames - // beyond the one that eventually calls exit(). To be as safe as possible, don't place any - // state in your program's main class, and don't call exit() yourself. Then, runMainAndExit() - // will do it, and the only thing on the stack at that time will be your main class, which - // has no state anyway. - // - // TODO(someday): Perhaps we should use the new std::quick_exit(), so that at_quick_exit() is - // available for those who really think they need it. Unfortunately, it is not yet available - // on many platforms. - - virtual void warning(StringPtr message) = 0; - // Print the given message to standard error. A newline is printed after the message if it - // doesn't already have one. - - virtual void error(StringPtr message) = 0; - // Like `warning()`, but also sets a flag indicating that the process has failed, and that when - // it eventually exits it should indicate an error status. - - KJ_NORETURN(virtual void exitError(StringPtr message)) = 0; - // Equivalent to `error(message)` followed by `exit()`. - - KJ_NORETURN(virtual void exitInfo(StringPtr message)) = 0; - // Displays the given non-error message to the user and then calls `exit()`. This is used to - // implement things like --help. - - virtual void increaseLoggingVerbosity() = 0; - // Increase the level of detail produced by the debug logging system. `MainBuilder` invokes - // this if the caller uses the -v flag. - - // TODO(someday): Add interfaces representing standard OS resources like the filesystem, so that - // these things can be mocked out. -}; - -class TopLevelProcessContext final: public ProcessContext { - // A ProcessContext implementation appropriate for use at the actual entry point of a process - // (as opposed to when you are trying to call a program's main function from within some other - // program). This implementation writes errors to stderr, and its `exit()` method actually - // calls the C `quick_exit()` function. - -public: - explicit TopLevelProcessContext(StringPtr programName); - - struct CleanShutdownException { int exitCode; }; - // If the environment variable KJ_CLEAN_SHUTDOWN is set, then exit() will actually throw this - // exception rather than exiting. `kj::runMain()` catches this exception and returns normally. - // This is useful primarily for testing purposes, to assist tools like memory leak checkers that - // are easily confused by quick_exit(). - - StringPtr getProgramName() override; - KJ_NORETURN(void exit() override); - void warning(StringPtr message) override; - void error(StringPtr message) override; - KJ_NORETURN(void exitError(StringPtr message) override); - KJ_NORETURN(void exitInfo(StringPtr message) override); - void increaseLoggingVerbosity() override; - -private: - StringPtr programName; - bool cleanShutdown; - bool hadErrors = false; -}; - -typedef Function params)> MainFunc; - -int runMainAndExit(ProcessContext& context, MainFunc&& func, int argc, char* argv[]); -// Runs the given main function and then exits using the given context. If an exception is thrown, -// this will catch it, report it via the context and exit with an error code. -// -// Normally this function does not return, because returning would probably lead to wasting time -// on cleanup when the process is just going to exit anyway. However, to facilitate memory leak -// checkers and other tools that require a clean shutdown to do their job, if the environment -// variable KJ_CLEAN_SHUTDOWN is set, the function will in fact return an exit code, which should -// then be returned from main(). -// -// Most users will use the KJ_MAIN() macro rather than call this function directly. - -#define KJ_MAIN(MainClass) \ - int main(int argc, char* argv[]) { \ - ::kj::TopLevelProcessContext context(argv[0]); \ - MainClass mainObject(context); \ - return ::kj::runMainAndExit(context, mainObject.getMain(), argc, argv); \ - } -// Convenience macro for declaring a main function based on the given class. The class must have -// a constructor that accepts a ProcessContext& and a method getMain() which returns -// kj::MainFunc (probably building it using a MainBuilder). - -class MainBuilder { - // Builds a main() function with nice argument parsing. As options and arguments are parsed, - // corresponding callbacks are called, so that you never have to write a massive switch() - // statement to interpret arguments. Additionally, this approach encourages you to write - // main classes that have a reasonable API that can be used as an alternative to their - // command-line interface. - // - // All StringPtrs passed to MainBuilder must remain valid until option parsing completes. The - // assumption is that these strings will all be literals, making this an easy requirement. If - // not, consider allocating them in an Arena. - // - // Some flags are automatically recognized by the main functions built by this class: - // --help: Prints help text and exits. The help text is constructed based on the - // information you provide to the builder as you define each flag. - // --verbose: Increase logging verbosity. - // --version: Print version information and exit. - // - // Example usage: - // - // class FooMain { - // public: - // FooMain(kj::ProcessContext& context): context(context) {} - // - // bool setAll() { all = true; return true; } - // // Enable the --all flag. - // - // kj::MainBuilder::Validity setOutput(kj::StringPtr name) { - // // Set the output file. - // - // if (name.endsWith(".foo")) { - // outputFile = name; - // return true; - // } else { - // return "Output file must have extension .foo."; - // } - // } - // - // kj::MainBuilder::Validity processInput(kj::StringPtr name) { - // // Process an input file. - // - // if (!exists(name)) { - // return kj::str(name, ": file not found"); - // } - // // ... process the input file ... - // return true; - // } - // - // kj::MainFunc getMain() { - // return MainBuilder(context, "Foo Builder v1.5", "Reads s and builds a Foo.") - // .addOption({'a', "all"}, KJ_BIND_METHOD(*this, setAll), - // "Frob all the widgets. Otherwise, only some widgets are frobbed.") - // .addOptionWithArg({'o', "output"}, KJ_BIND_METHOD(*this, setOutput), - // "", "Output to . Must be a .foo file.") - // .expectOneOrMoreArgs("", KJ_BIND_METHOD(*this, processInput)) - // .build(); - // } - // - // private: - // bool all = false; - // kj::StringPtr outputFile; - // kj::ProcessContext& context; - // }; - -public: - MainBuilder(ProcessContext& context, StringPtr version, - StringPtr briefDescription, StringPtr extendedDescription = nullptr); - ~MainBuilder() noexcept(false); - - class OptionName { - public: - OptionName() = default; - inline OptionName(char shortName): isLong(false), shortName(shortName) {} - inline OptionName(const char* longName): isLong(true), longName(longName) {} - - private: - bool isLong; - union { - char shortName; - const char* longName; - }; - friend class MainBuilder; - }; - - class Validity { - public: - inline Validity(bool valid) { - if (!valid) errorMessage = heapString("invalid argument"); - } - inline Validity(const char* errorMessage) - : errorMessage(heapString(errorMessage)) {} - inline Validity(String&& errorMessage) - : errorMessage(kj::mv(errorMessage)) {} - - inline const Maybe& getError() const { return errorMessage; } - inline Maybe releaseError() { return kj::mv(errorMessage); } - - private: - Maybe errorMessage; - friend class MainBuilder; - }; - - MainBuilder& addOption(std::initializer_list names, Function callback, - StringPtr helpText); - // Defines a new option (flag). `names` is a list of characters and strings that can be used to - // specify the option on the command line. Single-character names are used with "-" while string - // names are used with "--". `helpText` is a natural-language description of the flag. - // - // `callback` is called when the option is seen. Its return value indicates whether the option - // was accepted. If not, further option processing stops, and error is written, and the process - // exits. - // - // Example: - // - // builder.addOption({'a', "all"}, KJ_BIND_METHOD(*this, showAll), "Show all files."); - // - // This option could be specified in the following ways: - // - // -a - // --all - // - // Note that single-character option names can be combined into a single argument. For example, - // `-abcd` is equivalent to `-a -b -c -d`. - // - // The help text for this option would look like: - // - // -a, --all - // Show all files. - // - // Note that help text is automatically word-wrapped. - - MainBuilder& addOptionWithArg(std::initializer_list names, - Function callback, - StringPtr argumentTitle, StringPtr helpText); - // Like `addOption()`, but adds an option which accepts an argument. `argumentTitle` is used in - // the help text. The argument text is passed to the callback. - // - // Example: - // - // builder.addOptionWithArg({'o', "output"}, KJ_BIND_METHOD(*this, setOutput), - // "", "Output to ."); - // - // This option could be specified with an argument of "foo" in the following ways: - // - // -ofoo - // -o foo - // --output=foo - // --output foo - // - // Note that single-character option names can be combined, but only the last option can have an - // argument, since the characters after the option letter are interpreted as the argument. E.g. - // `-abofoo` would be equivalent to `-a -b -o foo`. - // - // The help text for this option would look like: - // - // -o FILENAME, --output=FILENAME - // Output to FILENAME. - - MainBuilder& addSubCommand(StringPtr name, Function getSubParser, - StringPtr briefHelpText); - // If exactly the given name is seen as an argument, invoke getSubParser() and then pass all - // remaining arguments to the parser it returns. This is useful for implementing commands which - // have lots of sub-commands, like "git" (which has sub-commands "checkout", "branch", "pull", - // etc.). - // - // `getSubParser` is only called if the command is seen. This avoids building main functions - // for commands that aren't used. - // - // `briefHelpText` should be brief enough to show immediately after the command name on a single - // line. It will not be wrapped. Users can use the built-in "help" command to get extended - // help on a particular command. - - MainBuilder& expectArg(StringPtr title, Function callback); - MainBuilder& expectOptionalArg(StringPtr title, Function callback); - MainBuilder& expectZeroOrMoreArgs(StringPtr title, Function callback); - MainBuilder& expectOneOrMoreArgs(StringPtr title, Function callback); - // Set callbacks to handle arguments. `expectArg()` and `expectOptionalArg()` specify positional - // arguments with special handling, while `expect{Zero,One}OrMoreArgs()` specifies a handler for - // an argument list (the handler is called once for each argument in the list). `title` - // specifies how the argument should be represented in the usage text. - // - // All options callbacks are called before argument callbacks, regardless of their ordering on - // the command line. This matches GNU getopt's behavior of permuting non-flag arguments to the - // end of the argument list. Also matching getopt, the special option "--" indicates that the - // rest of the command line is all arguments, not options, even if they start with '-'. - // - // The interpretation of positional arguments is fairly flexible. The non-optional arguments can - // be expected at the beginning, end, or in the middle. If more arguments are specified than - // the number of non-optional args, they are assigned to the optional argument handlers in the - // order of registration. - // - // For example, say you called: - // builder.expectArg("", ...); - // builder.expectOptionalArg("", ...); - // builder.expectArg("", ...); - // builder.expectZeroOrMoreArgs("", ...); - // builder.expectArg("", ...); - // - // This command requires at least three arguments: foo, baz, and corge. If four arguments are - // given, the second is assigned to bar. If five or more arguments are specified, then the - // arguments between the third and last are assigned to qux. Note that it never makes sense - // to call `expect*OrMoreArgs()` more than once since only the first call would ever be used. - // - // In practice, you probably shouldn't create such complicated commands as in the above example. - // But, this flexibility seems necessary to support commands where the first argument is special - // as well as commands (like `cp`) where the last argument is special. - - MainBuilder& callAfterParsing(Function callback); - // Call the given function after all arguments have been parsed. - - MainFunc build(); - // Build the "main" function, which simply parses the arguments. Once this returns, the - // `MainBuilder` is no longer valid. - -private: - struct Impl; - Own impl; - - class MainImpl; -}; - -} // namespace kj - -#endif // KJ_MAIN_H_ diff --git a/phonelibs/capnp-cpp/include/kj/memory.h b/phonelibs/capnp-cpp/include/kj/memory.h deleted file mode 100644 index 60912b0a34..0000000000 --- a/phonelibs/capnp-cpp/include/kj/memory.h +++ /dev/null @@ -1,406 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_MEMORY_H_ -#define KJ_MEMORY_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "common.h" - -namespace kj { - -// ======================================================================================= -// Disposer -- Implementation details. - -class Disposer { - // Abstract interface for a thing that "disposes" of objects, where "disposing" usually means - // calling the destructor followed by freeing the underlying memory. `Own` encapsulates an - // object pointer with corresponding Disposer. - // - // Few developers will ever touch this interface. It is primarily useful for those implementing - // custom memory allocators. - -protected: - // Do not declare a destructor, as doing so will force a global initializer for each HeapDisposer - // instance. Eww! - - virtual void disposeImpl(void* pointer) const = 0; - // Disposes of the object, given a pointer to the beginning of the object. If the object is - // polymorphic, this pointer is determined by dynamic_cast(). For non-polymorphic types, - // Own does not allow any casting, so the pointer exactly matches the original one given to - // Own. - -public: - - template - void dispose(T* object) const; - // Helper wrapper around disposeImpl(). - // - // If T is polymorphic, calls `disposeImpl(dynamic_cast(object))`, otherwise calls - // `disposeImpl(implicitCast(object))`. - // - // Callers must not call dispose() on the same pointer twice, even if the first call throws - // an exception. - -private: - template - struct Dispose_; -}; - -template -class DestructorOnlyDisposer: public Disposer { - // A disposer that merely calls the type's destructor and nothing else. - -public: - static const DestructorOnlyDisposer instance; - - void disposeImpl(void* pointer) const override { - reinterpret_cast(pointer)->~T(); - } -}; - -template -const DestructorOnlyDisposer DestructorOnlyDisposer::instance = DestructorOnlyDisposer(); - -class NullDisposer: public Disposer { - // A disposer that does nothing. - -public: - static const NullDisposer instance; - - void disposeImpl(void* pointer) const override {} -}; - -// ======================================================================================= -// Own -- An owned pointer. - -template -class Own { - // A transferrable title to a T. When an Own goes out of scope, the object's Disposer is - // called to dispose of it. An Own can be efficiently passed by move, without relocating the - // underlying object; this transfers ownership. - // - // This is much like std::unique_ptr, except: - // - You cannot release(). An owned object is not necessarily allocated with new (see next - // point), so it would be hard to use release() correctly. - // - The deleter is made polymorphic by virtual call rather than by template. This is much - // more powerful -- it allows the use of custom allocators, freelists, etc. This could - // _almost_ be accomplished with unique_ptr by forcing everyone to use something like - // std::unique_ptr, except that things get hairy in the presence of multiple - // inheritance and upcasting, and anyway if you force everyone to use a custom deleter - // then you've lost any benefit to interoperating with the "standard" unique_ptr. - -public: - KJ_DISALLOW_COPY(Own); - inline Own(): disposer(nullptr), ptr(nullptr) {} - inline Own(Own&& other) noexcept - : disposer(other.disposer), ptr(other.ptr) { other.ptr = nullptr; } - inline Own(Own>&& other) noexcept - : disposer(other.disposer), ptr(other.ptr) { other.ptr = nullptr; } - template ()>> - inline Own(Own&& other) noexcept - : disposer(other.disposer), ptr(other.ptr) { - static_assert(__is_polymorphic(T), - "Casting owned pointers requires that the target type is polymorphic."); - other.ptr = nullptr; - } - inline Own(T* ptr, const Disposer& disposer) noexcept: disposer(&disposer), ptr(ptr) {} - - ~Own() noexcept(false) { dispose(); } - - inline Own& operator=(Own&& other) { - // Move-assingnment operator. - - // Careful, this might own `other`. Therefore we have to transfer the pointers first, then - // dispose. - const Disposer* disposerCopy = disposer; - T* ptrCopy = ptr; - disposer = other.disposer; - ptr = other.ptr; - other.ptr = nullptr; - if (ptrCopy != nullptr) { - disposerCopy->dispose(const_cast*>(ptrCopy)); - } - return *this; - } - - inline Own& operator=(decltype(nullptr)) { - dispose(); - return *this; - } - - template - Own downcast() { - // Downcast the pointer to Own, destroying the original pointer. If this pointer does not - // actually point at an instance of U, the results are undefined (throws an exception in debug - // mode if RTTI is enabled, otherwise you're on your own). - - Own result; - if (ptr != nullptr) { - result.ptr = &kj::downcast(*ptr); - result.disposer = disposer; - ptr = nullptr; - } - return result; - } - -#define NULLCHECK KJ_IREQUIRE(ptr != nullptr, "null Own<> dereference") - inline T* operator->() { NULLCHECK; return ptr; } - inline const T* operator->() const { NULLCHECK; return ptr; } - inline T& operator*() { NULLCHECK; return *ptr; } - inline const T& operator*() const { NULLCHECK; return *ptr; } -#undef NULLCHECK - inline T* get() { return ptr; } - inline const T* get() const { return ptr; } - inline operator T*() { return ptr; } - inline operator const T*() const { return ptr; } - -private: - const Disposer* disposer; // Only valid if ptr != nullptr. - T* ptr; - - inline explicit Own(decltype(nullptr)): disposer(nullptr), ptr(nullptr) {} - - inline bool operator==(decltype(nullptr)) { return ptr == nullptr; } - inline bool operator!=(decltype(nullptr)) { return ptr != nullptr; } - // Only called by Maybe>. - - inline void dispose() { - // Make sure that if an exception is thrown, we are left with a null ptr, so we won't possibly - // dispose again. - T* ptrCopy = ptr; - if (ptrCopy != nullptr) { - ptr = nullptr; - disposer->dispose(const_cast*>(ptrCopy)); - } - } - - template - friend class Own; - friend class Maybe>; -}; - -namespace _ { // private - -template -class OwnOwn { -public: - inline OwnOwn(Own&& value) noexcept: value(kj::mv(value)) {} - - inline Own& operator*() & { return value; } - inline const Own& operator*() const & { return value; } - inline Own&& operator*() && { return kj::mv(value); } - inline const Own&& operator*() const && { return kj::mv(value); } - inline Own* operator->() { return &value; } - inline const Own* operator->() const { return &value; } - inline operator Own*() { return value ? &value : nullptr; } - inline operator const Own*() const { return value ? &value : nullptr; } - -private: - Own value; -}; - -template -OwnOwn readMaybe(Maybe>&& maybe) { return OwnOwn(kj::mv(maybe.ptr)); } -template -Own* readMaybe(Maybe>& maybe) { return maybe.ptr ? &maybe.ptr : nullptr; } -template -const Own* readMaybe(const Maybe>& maybe) { return maybe.ptr ? &maybe.ptr : nullptr; } - -} // namespace _ (private) - -template -class Maybe> { -public: - inline Maybe(): ptr(nullptr) {} - inline Maybe(Own&& t) noexcept: ptr(kj::mv(t)) {} - inline Maybe(Maybe&& other) noexcept: ptr(kj::mv(other.ptr)) {} - - template - inline Maybe(Maybe>&& other): ptr(mv(other.ptr)) {} - template - inline Maybe(Own&& other): ptr(mv(other)) {} - - inline Maybe(decltype(nullptr)) noexcept: ptr(nullptr) {} - - inline operator Maybe() { return ptr.get(); } - inline operator Maybe() const { return ptr.get(); } - - inline Maybe& operator=(Maybe&& other) { ptr = kj::mv(other.ptr); return *this; } - - inline bool operator==(decltype(nullptr)) const { return ptr == nullptr; } - inline bool operator!=(decltype(nullptr)) const { return ptr != nullptr; } - - Own& orDefault(Own& defaultValue) { - if (ptr == nullptr) { - return defaultValue; - } else { - return ptr; - } - } - const Own& orDefault(const Own& defaultValue) const { - if (ptr == nullptr) { - return defaultValue; - } else { - return ptr; - } - } - - template - auto map(Func&& f) & -> Maybe&>()))> { - if (ptr == nullptr) { - return nullptr; - } else { - return f(ptr); - } - } - - template - auto map(Func&& f) const & -> Maybe&>()))> { - if (ptr == nullptr) { - return nullptr; - } else { - return f(ptr); - } - } - - template - auto map(Func&& f) && -> Maybe&&>()))> { - if (ptr == nullptr) { - return nullptr; - } else { - return f(kj::mv(ptr)); - } - } - - template - auto map(Func&& f) const && -> Maybe&&>()))> { - if (ptr == nullptr) { - return nullptr; - } else { - return f(kj::mv(ptr)); - } - } - -private: - Own ptr; - - template - friend class Maybe; - template - friend _::OwnOwn _::readMaybe(Maybe>&& maybe); - template - friend Own* _::readMaybe(Maybe>& maybe); - template - friend const Own* _::readMaybe(const Maybe>& maybe); -}; - -namespace _ { // private - -template -class HeapDisposer final: public Disposer { -public: - virtual void disposeImpl(void* pointer) const override { delete reinterpret_cast(pointer); } - - static const HeapDisposer instance; -}; - -template -const HeapDisposer HeapDisposer::instance = HeapDisposer(); - -} // namespace _ (private) - -template -Own heap(Params&&... params) { - // heap(...) allocates a T on the heap, forwarding the parameters to its constructor. The - // exact heap implementation is unspecified -- for now it is operator new, but you should not - // assume this. (Since we know the object size at delete time, we could actually implement an - // allocator that is more efficient than operator new.) - - return Own(new T(kj::fwd(params)...), _::HeapDisposer::instance); -} - -template -Own> heap(T&& orig) { - // Allocate a copy (or move) of the argument on the heap. - // - // The purpose of this overload is to allow you to omit the template parameter as there is only - // one argument and the purpose is to copy it. - - typedef Decay T2; - return Own(new T2(kj::fwd(orig)), _::HeapDisposer::instance); -} - -// ======================================================================================= -// SpaceFor -- assists in manual allocation - -template -class SpaceFor { - // A class which has the same size and alignment as T but does not call its constructor or - // destructor automatically. Instead, call construct() to construct a T in the space, which - // returns an Own which will take care of calling T's destructor later. - -public: - inline SpaceFor() {} - inline ~SpaceFor() {} - - template - Own construct(Params&&... params) { - ctor(value, kj::fwd(params)...); - return Own(&value, DestructorOnlyDisposer::instance); - } - -private: - union { - T value; - }; -}; - -// ======================================================================================= -// Inline implementation details - -template -struct Disposer::Dispose_ { - static void dispose(T* object, const Disposer& disposer) { - // Note that dynamic_cast does not require RTTI to be enabled, because the offset to - // the top of the object is in the vtable -- as it obviously needs to be to correctly implement - // operator delete. - disposer.disposeImpl(dynamic_cast(object)); - } -}; -template -struct Disposer::Dispose_ { - static void dispose(T* object, const Disposer& disposer) { - disposer.disposeImpl(static_cast(object)); - } -}; - -template -void Disposer::dispose(T* object) const { - Dispose_::dispose(object, *this); -} - -} // namespace kj - -#endif // KJ_MEMORY_H_ diff --git a/phonelibs/capnp-cpp/include/kj/mutex.h b/phonelibs/capnp-cpp/include/kj/mutex.h deleted file mode 100644 index d211ebfeb1..0000000000 --- a/phonelibs/capnp-cpp/include/kj/mutex.h +++ /dev/null @@ -1,369 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_MUTEX_H_ -#define KJ_MUTEX_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "memory.h" -#include - -#if __linux__ && !defined(KJ_USE_FUTEX) -#define KJ_USE_FUTEX 1 -#endif - -#if !KJ_USE_FUTEX && !_WIN32 -// On Linux we use futex. On other platforms we wrap pthreads. -// TODO(someday): Write efficient low-level locking primitives for other platforms. -#include -#endif - -namespace kj { - -// ======================================================================================= -// Private details -- public interfaces follow below. - -namespace _ { // private - -class Mutex { - // Internal implementation details. See `MutexGuarded`. - -public: - Mutex(); - ~Mutex(); - KJ_DISALLOW_COPY(Mutex); - - enum Exclusivity { - EXCLUSIVE, - SHARED - }; - - void lock(Exclusivity exclusivity); - void unlock(Exclusivity exclusivity); - - void assertLockedByCaller(Exclusivity exclusivity); - // In debug mode, assert that the mutex is locked by the calling thread, or if that is - // non-trivial, assert that the mutex is locked (which should be good enough to catch problems - // in unit tests). In non-debug builds, do nothing. - -private: -#if KJ_USE_FUTEX - uint futex; - // bit 31 (msb) = set if exclusive lock held - // bit 30 (msb) = set if threads are waiting for exclusive lock - // bits 0-29 = count of readers; If an exclusive lock is held, this is the count of threads - // waiting for a read lock, otherwise it is the count of threads that currently hold a read - // lock. - - static constexpr uint EXCLUSIVE_HELD = 1u << 31; - static constexpr uint EXCLUSIVE_REQUESTED = 1u << 30; - static constexpr uint SHARED_COUNT_MASK = EXCLUSIVE_REQUESTED - 1; - -#elif _WIN32 - uintptr_t srwLock; // Actually an SRWLOCK, but don't want to #include in header. - -#else - mutable pthread_rwlock_t mutex; -#endif -}; - -class Once { - // Internal implementation details. See `Lazy`. - -public: -#if KJ_USE_FUTEX - inline Once(bool startInitialized = false) - : futex(startInitialized ? INITIALIZED : UNINITIALIZED) {} -#else - Once(bool startInitialized = false); - ~Once(); -#endif - KJ_DISALLOW_COPY(Once); - - class Initializer { - public: - virtual void run() = 0; - }; - - void runOnce(Initializer& init); - -#if _WIN32 // TODO(perf): Can we make this inline on win32 somehow? - bool isInitialized() noexcept; - -#else - inline bool isInitialized() noexcept { - // Fast path check to see if runOnce() would simply return immediately. -#if KJ_USE_FUTEX - return __atomic_load_n(&futex, __ATOMIC_ACQUIRE) == INITIALIZED; -#else - return __atomic_load_n(&state, __ATOMIC_ACQUIRE) == INITIALIZED; -#endif - } -#endif - - void reset(); - // Returns the state from initialized to uninitialized. It is an error to call this when - // not already initialized, or when runOnce() or isInitialized() might be called concurrently in - // another thread. - -private: -#if KJ_USE_FUTEX - uint futex; - - enum State { - UNINITIALIZED, - INITIALIZING, - INITIALIZING_WITH_WAITERS, - INITIALIZED - }; - -#elif _WIN32 - uintptr_t initOnce; // Actually an INIT_ONCE, but don't want to #include in header. - -#else - enum State { - UNINITIALIZED, - INITIALIZED - }; - State state; - pthread_mutex_t mutex; -#endif -}; - -} // namespace _ (private) - -// ======================================================================================= -// Public interface - -template -class Locked { - // Return type for `MutexGuarded::lock()`. `Locked` provides access to the bounded object - // and unlocks the mutex when it goes out of scope. - -public: - KJ_DISALLOW_COPY(Locked); - inline Locked(): mutex(nullptr), ptr(nullptr) {} - inline Locked(Locked&& other): mutex(other.mutex), ptr(other.ptr) { - other.mutex = nullptr; - other.ptr = nullptr; - } - inline ~Locked() { - if (mutex != nullptr) mutex->unlock(isConst() ? _::Mutex::SHARED : _::Mutex::EXCLUSIVE); - } - - inline Locked& operator=(Locked&& other) { - if (mutex != nullptr) mutex->unlock(isConst() ? _::Mutex::SHARED : _::Mutex::EXCLUSIVE); - mutex = other.mutex; - ptr = other.ptr; - other.mutex = nullptr; - other.ptr = nullptr; - return *this; - } - - inline void release() { - if (mutex != nullptr) mutex->unlock(isConst() ? _::Mutex::SHARED : _::Mutex::EXCLUSIVE); - mutex = nullptr; - ptr = nullptr; - } - - inline T* operator->() { return ptr; } - inline const T* operator->() const { return ptr; } - inline T& operator*() { return *ptr; } - inline const T& operator*() const { return *ptr; } - inline T* get() { return ptr; } - inline const T* get() const { return ptr; } - inline operator T*() { return ptr; } - inline operator const T*() const { return ptr; } - -private: - _::Mutex* mutex; - T* ptr; - - inline Locked(_::Mutex& mutex, T& value): mutex(&mutex), ptr(&value) {} - - template - friend class MutexGuarded; -}; - -template -class MutexGuarded { - // An object of type T, bounded by a mutex. In order to access the object, you must lock it. - // - // Write locks are not "recursive" -- trying to lock again in a thread that already holds a lock - // will deadlock. Recursive write locks are usually a sign of bad design. - // - // Unfortunately, **READ LOCKS ARE NOT RECURSIVE** either. Common sense says they should be. - // But on many operating systems (BSD, OSX), recursively read-locking a pthread_rwlock is - // actually unsafe. The problem is that writers are "prioritized" over readers, so a read lock - // request will block if any write lock requests are outstanding. So, if thread A takes a read - // lock, thread B requests a write lock (and starts waiting), and then thread A tries to take - // another read lock recursively, the result is deadlock. - -public: - template - explicit MutexGuarded(Params&&... params); - // Initialize the mutex-bounded object by passing the given parameters to its constructor. - - Locked lockExclusive() const; - // Exclusively locks the object and returns it. The returned `Locked` can be passed by - // move, similar to `Own`. - // - // This method is declared `const` in accordance with KJ style rules which say that constness - // should be used to indicate thread-safety. It is safe to share a const pointer between threads, - // but it is not safe to share a mutable pointer. Since the whole point of MutexGuarded is to - // be shared between threads, its methods should be const, even though locking it produces a - // non-const pointer to the contained object. - - Locked lockShared() const; - // Lock the value for shared access. Multiple shared locks can be taken concurrently, but cannot - // be held at the same time as a non-shared lock. - - inline const T& getWithoutLock() const { return value; } - inline T& getWithoutLock() { return value; } - // Escape hatch for cases where some external factor guarantees that it's safe to get the - // value. You should treat these like const_cast -- be highly suspicious of any use. - - inline const T& getAlreadyLockedShared() const; - inline T& getAlreadyLockedShared(); - inline T& getAlreadyLockedExclusive() const; - // Like `getWithoutLock()`, but asserts that the lock is already held by the calling thread. - -private: - mutable _::Mutex mutex; - mutable T value; -}; - -template -class MutexGuarded { - // MutexGuarded cannot guard a const type. This would be pointless anyway, and would complicate - // the implementation of Locked, which uses constness to decide what kind of lock it holds. - static_assert(sizeof(T) < 0, "MutexGuarded's type cannot be const."); -}; - -template -class Lazy { - // A lazily-initialized value. - -public: - template - T& get(Func&& init); - template - const T& get(Func&& init) const; - // The first thread to call get() will invoke the given init function to construct the value. - // Other threads will block until construction completes, then return the same value. - // - // `init` is a functor(typically a lambda) which takes `SpaceFor&` as its parameter and returns - // `Own`. If `init` throws an exception, the exception is propagated out of that thread's - // call to `get()`, and subsequent calls behave as if `get()` hadn't been called at all yet -- - // in other words, subsequent calls retry initialization until it succeeds. - -private: - mutable _::Once once; - mutable SpaceFor space; - mutable Own value; - - template - class InitImpl; -}; - -// ======================================================================================= -// Inline implementation details - -template -template -inline MutexGuarded::MutexGuarded(Params&&... params) - : value(kj::fwd(params)...) {} - -template -inline Locked MutexGuarded::lockExclusive() const { - mutex.lock(_::Mutex::EXCLUSIVE); - return Locked(mutex, value); -} - -template -inline Locked MutexGuarded::lockShared() const { - mutex.lock(_::Mutex::SHARED); - return Locked(mutex, value); -} - -template -inline const T& MutexGuarded::getAlreadyLockedShared() const { -#ifdef KJ_DEBUG - mutex.assertLockedByCaller(_::Mutex::SHARED); -#endif - return value; -} -template -inline T& MutexGuarded::getAlreadyLockedShared() { -#ifdef KJ_DEBUG - mutex.assertLockedByCaller(_::Mutex::SHARED); -#endif - return value; -} -template -inline T& MutexGuarded::getAlreadyLockedExclusive() const { -#ifdef KJ_DEBUG - mutex.assertLockedByCaller(_::Mutex::EXCLUSIVE); -#endif - return const_cast(value); -} - -template -template -class Lazy::InitImpl: public _::Once::Initializer { -public: - inline InitImpl(const Lazy& lazy, Func&& func): lazy(lazy), func(kj::fwd(func)) {} - - void run() override { - lazy.value = func(lazy.space); - } - -private: - const Lazy& lazy; - Func func; -}; - -template -template -inline T& Lazy::get(Func&& init) { - if (!once.isInitialized()) { - InitImpl initImpl(*this, kj::fwd(init)); - once.runOnce(initImpl); - } - return *value; -} - -template -template -inline const T& Lazy::get(Func&& init) const { - if (!once.isInitialized()) { - InitImpl initImpl(*this, kj::fwd(init)); - once.runOnce(initImpl); - } - return *value; -} - -} // namespace kj - -#endif // KJ_MUTEX_H_ diff --git a/phonelibs/capnp-cpp/include/kj/one-of.h b/phonelibs/capnp-cpp/include/kj/one-of.h deleted file mode 100644 index 6e143c44cf..0000000000 --- a/phonelibs/capnp-cpp/include/kj/one-of.h +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_ONE_OF_H_ -#define KJ_ONE_OF_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "common.h" - -namespace kj { - -namespace _ { // private - -template -struct TypeIndex_ { static constexpr uint value = TypeIndex_::value; }; -template -struct TypeIndex_ { static constexpr uint value = i; }; - -} // namespace _ (private) - -template -class OneOf { - template - static inline constexpr uint typeIndex() { return _::TypeIndex_<1, Key, Variants...>::value; } - // Get the 1-based index of Key within the type list Types. - -public: - inline OneOf(): tag(0) {} - OneOf(const OneOf& other) { copyFrom(other); } - OneOf(OneOf&& other) { moveFrom(other); } - ~OneOf() { destroy(); } - - OneOf& operator=(const OneOf& other) { if (tag != 0) destroy(); copyFrom(other); return *this; } - OneOf& operator=(OneOf&& other) { if (tag != 0) destroy(); moveFrom(other); return *this; } - - inline bool operator==(decltype(nullptr)) const { return tag == 0; } - inline bool operator!=(decltype(nullptr)) const { return tag != 0; } - - template - bool is() const { - return tag == typeIndex(); - } - - template - T& get() { - KJ_IREQUIRE(is(), "Must check OneOf::is() before calling get()."); - return *reinterpret_cast(space); - } - template - const T& get() const { - KJ_IREQUIRE(is(), "Must check OneOf::is() before calling get()."); - return *reinterpret_cast(space); - } - - template - T& init(Params&&... params) { - if (tag != 0) destroy(); - ctor(*reinterpret_cast(space), kj::fwd(params)...); - tag = typeIndex(); - return *reinterpret_cast(space); - } - -private: - uint tag; - - static inline constexpr size_t maxSize(size_t a) { - return a; - } - template - static inline constexpr size_t maxSize(size_t a, size_t b, Rest... rest) { - return maxSize(kj::max(a, b), rest...); - } - // Returns the maximum of all the parameters. - // TODO(someday): Generalize the above template and make it common. I tried, but C++ decided to - // be difficult so I cut my losses. - - static constexpr auto spaceSize = maxSize(sizeof(Variants)...); - // TODO(msvc): This constant could just as well go directly inside space's bracket's, where it's - // used, but MSVC suffers a parse error on `...`. - - union { - byte space[spaceSize]; - - void* forceAligned; - // TODO(someday): Use C++11 alignas() once we require GCC 4.8 / Clang 3.3. - }; - - template - inline void doAll(T... t) {} - - template - inline bool destroyVariant() { - if (tag == typeIndex()) { - tag = 0; - dtor(*reinterpret_cast(space)); - } - return false; - } - void destroy() { - doAll(destroyVariant()...); - } - - template - inline bool copyVariantFrom(const OneOf& other) { - if (other.is()) { - ctor(*reinterpret_cast(space), other.get()); - } - return false; - } - void copyFrom(const OneOf& other) { - // Initialize as a copy of `other`. Expects that `this` starts out uninitialized, so the tag - // is invalid. - tag = other.tag; - doAll(copyVariantFrom(other)...); - } - - template - inline bool moveVariantFrom(OneOf& other) { - if (other.is()) { - ctor(*reinterpret_cast(space), kj::mv(other.get())); - } - return false; - } - void moveFrom(OneOf& other) { - // Initialize as a copy of `other`. Expects that `this` starts out uninitialized, so the tag - // is invalid. - tag = other.tag; - doAll(moveVariantFrom(other)...); - } -}; - -} // namespace kj - -#endif // KJ_ONE_OF_H_ diff --git a/phonelibs/capnp-cpp/include/kj/parse/char.h b/phonelibs/capnp-cpp/include/kj/parse/char.h deleted file mode 100644 index 2e6d51921d..0000000000 --- a/phonelibs/capnp-cpp/include/kj/parse/char.h +++ /dev/null @@ -1,361 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// This file contains parsers useful for character stream inputs, including parsers to parse -// common kinds of tokens like identifiers, numbers, and quoted strings. - -#ifndef KJ_PARSE_CHAR_H_ -#define KJ_PARSE_CHAR_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "common.h" -#include "../string.h" -#include - -namespace kj { -namespace parse { - -// ======================================================================================= -// Exact char/string. - -class ExactString_ { -public: - constexpr inline ExactString_(const char* str): str(str) {} - - template - Maybe> operator()(Input& input) const { - const char* ptr = str; - - while (*ptr != '\0') { - if (input.atEnd() || input.current() != *ptr) return nullptr; - input.next(); - ++ptr; - } - - return Tuple<>(); - } - -private: - const char* str; -}; - -constexpr inline ExactString_ exactString(const char* str) { - return ExactString_(str); -} - -template -constexpr ExactlyConst_ exactChar() { - // Returns a parser that matches exactly the character given by the template argument (returning - // no result). - return ExactlyConst_(); -} - -// ======================================================================================= -// Char ranges / sets - -class CharGroup_ { -public: - constexpr inline CharGroup_(): bits{0, 0, 0, 0} {} - - constexpr inline CharGroup_ orRange(unsigned char first, unsigned char last) const { - return CharGroup_(bits[0] | (oneBits(last + 1) & ~oneBits(first )), - bits[1] | (oneBits(last - 63) & ~oneBits(first - 64)), - bits[2] | (oneBits(last - 127) & ~oneBits(first - 128)), - bits[3] | (oneBits(last - 191) & ~oneBits(first - 192))); - } - - constexpr inline CharGroup_ orAny(const char* chars) const { - return *chars == 0 ? *this : orChar(*chars).orAny(chars + 1); - } - - constexpr inline CharGroup_ orChar(unsigned char c) const { - return CharGroup_(bits[0] | bit(c), - bits[1] | bit(c - 64), - bits[2] | bit(c - 128), - bits[3] | bit(c - 256)); - } - - constexpr inline CharGroup_ orGroup(CharGroup_ other) const { - return CharGroup_(bits[0] | other.bits[0], - bits[1] | other.bits[1], - bits[2] | other.bits[2], - bits[3] | other.bits[3]); - } - - constexpr inline CharGroup_ invert() const { - return CharGroup_(~bits[0], ~bits[1], ~bits[2], ~bits[3]); - } - - constexpr inline bool contains(unsigned char c) const { - return (bits[c / 64] & (1ll << (c % 64))) != 0; - } - - template - Maybe operator()(Input& input) const { - if (input.atEnd()) return nullptr; - unsigned char c = input.current(); - if (contains(c)) { - input.next(); - return c; - } else { - return nullptr; - } - } - -private: - typedef unsigned long long Bits64; - - constexpr inline CharGroup_(Bits64 a, Bits64 b, Bits64 c, Bits64 d): bits{a, b, c, d} {} - Bits64 bits[4]; - - static constexpr inline Bits64 oneBits(int count) { - return count <= 0 ? 0ll : count >= 64 ? -1ll : ((1ll << count) - 1); - } - static constexpr inline Bits64 bit(int index) { - return index < 0 ? 0 : index >= 64 ? 0 : (1ll << index); - } -}; - -constexpr inline CharGroup_ charRange(char first, char last) { - // Create a parser which accepts any character in the range from `first` to `last`, inclusive. - // For example: `charRange('a', 'z')` matches all lower-case letters. The parser's result is the - // character matched. - // - // The returned object has methods which can be used to match more characters. The following - // produces a parser which accepts any letter as well as '_', '+', '-', and '.'. - // - // charRange('a', 'z').orRange('A', 'Z').orChar('_').orAny("+-.") - // - // You can also use `.invert()` to match the opposite set of characters. - - return CharGroup_().orRange(first, last); -} - -#if _MSC_VER -#define anyOfChars(chars) CharGroup_().orAny(chars) -// TODO(msvc): MSVC ICEs on the proper definition of `anyOfChars()`, which in turn prevents us from -// building the compiler or schema parser. We don't know why this happens, but Harris found that -// this horrible, horrible hack makes things work. This is awful, but it's better than nothing. -// Hopefully, MSVC will get fixed soon and we'll be able to remove this. -#else -constexpr inline CharGroup_ anyOfChars(const char* chars) { - // Returns a parser that accepts any of the characters in the given string (which should usually - // be a literal). The returned parser is of the same type as returned by `charRange()` -- see - // that function for more info. - - return CharGroup_().orAny(chars); -} -#endif - -// ======================================================================================= - -namespace _ { // private - -struct ArrayToString { - inline String operator()(const Array& arr) const { - return heapString(arr); - } -}; - -} // namespace _ (private) - -template -constexpr inline auto charsToString(SubParser&& subParser) - -> decltype(transform(kj::fwd(subParser), _::ArrayToString())) { - // Wraps a parser that returns Array such that it returns String instead. - return parse::transform(kj::fwd(subParser), _::ArrayToString()); -} - -// ======================================================================================= -// Basic character classes. - -constexpr auto alpha = charRange('a', 'z').orRange('A', 'Z'); -constexpr auto digit = charRange('0', '9'); -constexpr auto alphaNumeric = alpha.orGroup(digit); -constexpr auto nameStart = alpha.orChar('_'); -constexpr auto nameChar = alphaNumeric.orChar('_'); -constexpr auto hexDigit = charRange('0', '9').orRange('a', 'f').orRange('A', 'F'); -constexpr auto octDigit = charRange('0', '7'); -constexpr auto whitespaceChar = anyOfChars(" \f\n\r\t\v"); -constexpr auto controlChar = charRange(0, 0x1f).invert().orGroup(whitespaceChar).invert(); - -constexpr auto whitespace = many(anyOfChars(" \f\n\r\t\v")); - -constexpr auto discardWhitespace = discard(many(discard(anyOfChars(" \f\n\r\t\v")))); -// Like discard(whitespace) but avoids some memory allocation. - -// ======================================================================================= -// Identifiers - -namespace _ { // private - -struct IdentifierToString { - inline String operator()(char first, const Array& rest) const { - String result = heapString(rest.size() + 1); - result[0] = first; - memcpy(result.begin() + 1, rest.begin(), rest.size()); - return result; - } -}; - -} // namespace _ (private) - -constexpr auto identifier = transform(sequence(nameStart, many(nameChar)), _::IdentifierToString()); -// Parses an identifier (e.g. a C variable name). - -// ======================================================================================= -// Integers - -namespace _ { // private - -inline char parseDigit(char c) { - if (c < 'A') return c - '0'; - if (c < 'a') return c - 'A' + 10; - return c - 'a' + 10; -} - -template -struct ParseInteger { - inline uint64_t operator()(const Array& digits) const { - return operator()('0', digits); - } - uint64_t operator()(char first, const Array& digits) const { - uint64_t result = parseDigit(first); - for (char digit: digits) { - result = result * base + parseDigit(digit); - } - return result; - } -}; - - -} // namespace _ (private) - -constexpr auto integer = sequence( - oneOf( - transform(sequence(exactChar<'0'>(), exactChar<'x'>(), oneOrMore(hexDigit)), _::ParseInteger<16>()), - transform(sequence(exactChar<'0'>(), many(octDigit)), _::ParseInteger<8>()), - transform(sequence(charRange('1', '9'), many(digit)), _::ParseInteger<10>())), - notLookingAt(alpha.orAny("_."))); - -// ======================================================================================= -// Numbers (i.e. floats) - -namespace _ { // private - -struct ParseFloat { - double operator()(const Array& digits, - const Maybe>& fraction, - const Maybe, Array>>& exponent) const; -}; - -} // namespace _ (private) - -constexpr auto number = transform( - sequence( - oneOrMore(digit), - optional(sequence(exactChar<'.'>(), many(digit))), - optional(sequence(discard(anyOfChars("eE")), optional(anyOfChars("+-")), many(digit))), - notLookingAt(alpha.orAny("_."))), - _::ParseFloat()); - -// ======================================================================================= -// Quoted strings - -namespace _ { // private - -struct InterpretEscape { - char operator()(char c) const { - switch (c) { - case 'a': return '\a'; - case 'b': return '\b'; - case 'f': return '\f'; - case 'n': return '\n'; - case 'r': return '\r'; - case 't': return '\t'; - case 'v': return '\v'; - default: return c; - } - } -}; - -struct ParseHexEscape { - inline char operator()(char first, char second) const { - return (parseDigit(first) << 4) | parseDigit(second); - } -}; - -struct ParseHexByte { - inline byte operator()(char first, char second) const { - return (parseDigit(first) << 4) | parseDigit(second); - } -}; - -struct ParseOctEscape { - inline char operator()(char first, Maybe second, Maybe third) const { - char result = first - '0'; - KJ_IF_MAYBE(digit1, second) { - result = (result << 3) | (*digit1 - '0'); - KJ_IF_MAYBE(digit2, third) { - result = (result << 3) | (*digit2 - '0'); - } - } - return result; - } -}; - -} // namespace _ (private) - -constexpr auto escapeSequence = - sequence(exactChar<'\\'>(), oneOf( - transform(anyOfChars("abfnrtv'\"\\\?"), _::InterpretEscape()), - transform(sequence(exactChar<'x'>(), hexDigit, hexDigit), _::ParseHexEscape()), - transform(sequence(octDigit, optional(octDigit), optional(octDigit)), - _::ParseOctEscape()))); -// A parser that parses a C-string-style escape sequence (starting with a backslash). Returns -// a char. - -constexpr auto doubleQuotedString = charsToString(sequence( - exactChar<'\"'>(), - many(oneOf(anyOfChars("\\\n\"").invert(), escapeSequence)), - exactChar<'\"'>())); -// Parses a C-style double-quoted string. - -constexpr auto singleQuotedString = charsToString(sequence( - exactChar<'\''>(), - many(oneOf(anyOfChars("\\\n\'").invert(), escapeSequence)), - exactChar<'\''>())); -// Parses a C-style single-quoted string. - -constexpr auto doubleQuotedHexBinary = sequence( - exactChar<'0'>(), exactChar<'x'>(), exactChar<'\"'>(), - oneOrMore(transform(sequence(discardWhitespace, hexDigit, hexDigit), _::ParseHexByte())), - discardWhitespace, - exactChar<'\"'>()); -// Parses a double-quoted hex binary literal. Returns Array. - -} // namespace parse -} // namespace kj - -#endif // KJ_PARSE_CHAR_H_ diff --git a/phonelibs/capnp-cpp/include/kj/parse/common.h b/phonelibs/capnp-cpp/include/kj/parse/common.h deleted file mode 100644 index 3af3a8760d..0000000000 --- a/phonelibs/capnp-cpp/include/kj/parse/common.h +++ /dev/null @@ -1,824 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// Parser combinator framework! -// -// This file declares several functions which construct parsers, usually taking other parsers as -// input, thus making them parser combinators. -// -// A valid parser is any functor which takes a reference to an input cursor (defined below) as its -// input and returns a Maybe. The parser returns null on parse failure, or returns the parsed -// result on success. -// -// An "input cursor" is any type which implements the same interface as IteratorInput, below. Such -// a type acts as a pointer to the current input location. When a parser returns successfully, it -// will have updated the input cursor to point to the position just past the end of what was parsed. -// On failure, the cursor position is unspecified. - -#ifndef KJ_PARSE_COMMON_H_ -#define KJ_PARSE_COMMON_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "../common.h" -#include "../memory.h" -#include "../array.h" -#include "../tuple.h" -#include "../vector.h" -#if _MSC_VER -#include // result_of_t -#endif - -namespace kj { -namespace parse { - -template -class IteratorInput { - // A parser input implementation based on an iterator range. - -public: - IteratorInput(Iterator begin, Iterator end) - : parent(nullptr), pos(begin), end(end), best(begin) {} - explicit IteratorInput(IteratorInput& parent) - : parent(&parent), pos(parent.pos), end(parent.end), best(parent.pos) {} - ~IteratorInput() { - if (parent != nullptr) { - parent->best = kj::max(kj::max(pos, best), parent->best); - } - } - KJ_DISALLOW_COPY(IteratorInput); - - void advanceParent() { - parent->pos = pos; - } - void forgetParent() { - parent = nullptr; - } - - bool atEnd() { return pos == end; } - auto current() -> decltype(*instance()) { - KJ_IREQUIRE(!atEnd()); - return *pos; - } - auto consume() -> decltype(*instance()) { - KJ_IREQUIRE(!atEnd()); - return *pos++; - } - void next() { - KJ_IREQUIRE(!atEnd()); - ++pos; - } - - Iterator getBest() { return kj::max(pos, best); } - - Iterator getPosition() { return pos; } - -private: - IteratorInput* parent; - Iterator pos; - Iterator end; - Iterator best; // furthest we got with any sub-input -}; - -template struct OutputType_; -template struct OutputType_> { typedef T Type; }; -template -using OutputType = typename OutputType_< -#if _MSC_VER - std::result_of_t - // The instance() based version below results in: - // C2064: term does not evaluate to a function taking 1 arguments -#else - decltype(instance()(instance())) -#endif - >::Type; -// Synonym for the output type of a parser, given the parser type and the input type. - -// ======================================================================================= - -template -class ParserRef { - // Acts as a reference to some other parser, with simplified type. The referenced parser - // is polymorphic by virtual call rather than templates. For grammars of non-trivial size, - // it is important to inject refs into the grammar here and there to prevent the parser types - // from becoming ridiculous. Using too many of them can hurt performance, though. - -public: - ParserRef(): parser(nullptr), wrapper(nullptr) {} - ParserRef(const ParserRef&) = default; - ParserRef(ParserRef&&) = default; - ParserRef& operator=(const ParserRef& other) = default; - ParserRef& operator=(ParserRef&& other) = default; - - template - constexpr ParserRef(Other&& other) - : parser(&other), wrapper(&WrapperImplInstance>::instance) { - static_assert(kj::isReference(), "ParserRef should not be assigned to a temporary."); - } - - template - inline ParserRef& operator=(Other&& other) { - static_assert(kj::isReference(), "ParserRef should not be assigned to a temporary."); - parser = &other; - wrapper = &WrapperImplInstance>::instance; - return *this; - } - - KJ_ALWAYS_INLINE(Maybe operator()(Input& input) const) { - // Always inline in the hopes that this allows branch prediction to kick in so the virtual call - // doesn't hurt so much. - return wrapper->parse(parser, input); - } - -private: - struct Wrapper { - virtual Maybe parse(const void* parser, Input& input) const = 0; - }; - template - struct WrapperImpl: public Wrapper { - Maybe parse(const void* parser, Input& input) const override { - return (*reinterpret_cast(parser))(input); - } - }; - template - struct WrapperImplInstance { -#if _MSC_VER - // TODO(msvc): MSVC currently fails to initialize vtable pointers for constexpr values so - // we have to make this just const instead. - static const WrapperImpl instance; -#else - static constexpr WrapperImpl instance = WrapperImpl(); -#endif - }; - - const void* parser; - const Wrapper* wrapper; -}; - -template -template -#if _MSC_VER -const typename ParserRef::template WrapperImpl -ParserRef::WrapperImplInstance::instance = WrapperImpl(); -#else -constexpr typename ParserRef::template WrapperImpl -ParserRef::WrapperImplInstance::instance; -#endif - -template -constexpr ParserRef> ref(ParserImpl& impl) { - // Constructs a ParserRef. You must specify the input type explicitly, e.g. - // `ref(myParser)`. - - return ParserRef>(impl); -} - -// ------------------------------------------------------------------- -// any -// Output = one token - -class Any_ { -public: - template - Maybe().consume())>> operator()(Input& input) const { - if (input.atEnd()) { - return nullptr; - } else { - return input.consume(); - } - } -}; - -constexpr Any_ any = Any_(); -// A parser which matches any token and simply returns it. - -// ------------------------------------------------------------------- -// exactly() -// Output = Tuple<> - -template -class Exactly_ { -public: - explicit constexpr Exactly_(T&& expected): expected(expected) {} - - template - Maybe> operator()(Input& input) const { - if (input.atEnd() || input.current() != expected) { - return nullptr; - } else { - input.next(); - return Tuple<>(); - } - } - -private: - T expected; -}; - -template -constexpr Exactly_ exactly(T&& expected) { - // Constructs a parser which succeeds when the input is exactly the token specified. The - // result is always the empty tuple. - - return Exactly_(kj::fwd(expected)); -} - -// ------------------------------------------------------------------- -// exactlyConst() -// Output = Tuple<> - -template -class ExactlyConst_ { -public: - explicit constexpr ExactlyConst_() {} - - template - Maybe> operator()(Input& input) const { - if (input.atEnd() || input.current() != expected) { - return nullptr; - } else { - input.next(); - return Tuple<>(); - } - } -}; - -template -constexpr ExactlyConst_ exactlyConst() { - // Constructs a parser which succeeds when the input is exactly the token specified. The - // result is always the empty tuple. This parser is templated on the token value which may cause - // it to perform better -- or worse. Be sure to measure. - - return ExactlyConst_(); -} - -// ------------------------------------------------------------------- -// constResult() - -template -class ConstResult_ { -public: - explicit constexpr ConstResult_(SubParser&& subParser, Result&& result) - : subParser(kj::fwd(subParser)), result(kj::fwd(result)) {} - - template - Maybe operator()(Input& input) const { - if (subParser(input) == nullptr) { - return nullptr; - } else { - return result; - } - } - -private: - SubParser subParser; - Result result; -}; - -template -constexpr ConstResult_ constResult(SubParser&& subParser, Result&& result) { - // Constructs a parser which returns exactly `result` if `subParser` is successful. - return ConstResult_(kj::fwd(subParser), kj::fwd(result)); -} - -template -constexpr ConstResult_> discard(SubParser&& subParser) { - // Constructs a parser which wraps `subParser` but discards the result. - return constResult(kj::fwd(subParser), Tuple<>()); -} - -// ------------------------------------------------------------------- -// sequence() -// Output = Flattened Tuple of outputs of sub-parsers. - -template class Sequence_; - -template -class Sequence_ { -public: - template - explicit constexpr Sequence_(T&& firstSubParser, U&&... rest) - : first(kj::fwd(firstSubParser)), rest(kj::fwd(rest)...) {} - - // TODO(msvc): The trailing return types on `operator()` and `parseNext()` expose at least two - // bugs in MSVC: - // - // 1. An ICE. - // 2. 'error C2672: 'operator __surrogate_func': no matching overloaded function found)', - // which crops up in numerous places when trying to build the capnp command line tools. - // - // The only workaround I found for both bugs is to omit the trailing return types and instead - // rely on C++14's return type deduction. - - template - auto operator()(Input& input) const -#ifndef _MSC_VER - -> Maybe>(), - instance>()...))> -#endif - { - return parseNext(input); - } - - template - auto parseNext(Input& input, InitialParams&&... initialParams) const -#ifndef _MSC_VER - -> Maybe(initialParams)..., - instance>(), - instance>()...))> -#endif - { - KJ_IF_MAYBE(firstResult, first(input)) { - return rest.parseNext(input, kj::fwd(initialParams)..., - kj::mv(*firstResult)); - } else { - // TODO(msvc): MSVC depends on return type deduction to compile this function, so we need to - // help it deduce the right type on this code path. - return Maybe(initialParams)..., - instance>(), - instance>()...))>{nullptr}; - } - } - -private: - FirstSubParser first; - Sequence_ rest; -}; - -template <> -class Sequence_<> { -public: - template - Maybe> operator()(Input& input) const { - return parseNext(input); - } - - template - auto parseNext(Input& input, Params&&... params) const -> - Maybe(params)...))> { - return tuple(kj::fwd(params)...); - } -}; - -template -constexpr Sequence_ sequence(SubParsers&&... subParsers) { - // Constructs a parser that executes each of the parameter parsers in sequence and returns a - // tuple of their results. - - return Sequence_(kj::fwd(subParsers)...); -} - -// ------------------------------------------------------------------- -// many() -// Output = Array of output of sub-parser, or just a uint count if the sub-parser returns Tuple<>. - -template -class Many_ { - template > - struct Impl; -public: - explicit constexpr Many_(SubParser&& subParser) - : subParser(kj::fwd(subParser)) {} - - template - auto operator()(Input& input) const - -> decltype(Impl::apply(instance(), input)); - -private: - SubParser subParser; -}; - -template -template -struct Many_::Impl { - static Maybe> apply(const SubParser& subParser, Input& input) { - typedef Vector> Results; - Results results; - - while (!input.atEnd()) { - Input subInput(input); - - KJ_IF_MAYBE(subResult, subParser(subInput)) { - subInput.advanceParent(); - results.add(kj::mv(*subResult)); - } else { - break; - } - } - - if (atLeastOne && results.empty()) { - return nullptr; - } - - return results.releaseAsArray(); - } -}; - -template -template -struct Many_::Impl> { - // If the sub-parser output is Tuple<>, just return a count. - - static Maybe apply(const SubParser& subParser, Input& input) { - uint count = 0; - - while (!input.atEnd()) { - Input subInput(input); - - KJ_IF_MAYBE(subResult, subParser(subInput)) { - subInput.advanceParent(); - ++count; - } else { - break; - } - } - - if (atLeastOne && count == 0) { - return nullptr; - } - - return count; - } -}; - -template -template -auto Many_::operator()(Input& input) const - -> decltype(Impl::apply(instance(), input)) { - return Impl>::apply(subParser, input); -} - -template -constexpr Many_ many(SubParser&& subParser) { - // Constructs a parser that repeatedly executes the given parser until it fails, returning an - // Array of the results (or a uint count if `subParser` returns an empty tuple). - return Many_(kj::fwd(subParser)); -} - -template -constexpr Many_ oneOrMore(SubParser&& subParser) { - // Like `many()` but the parser must parse at least one item to be successful. - return Many_(kj::fwd(subParser)); -} - -// ------------------------------------------------------------------- -// times() -// Output = Array of output of sub-parser, or Tuple<> if sub-parser returns Tuple<>. - -template -class Times_ { - template > - struct Impl; -public: - explicit constexpr Times_(SubParser&& subParser, uint count) - : subParser(kj::fwd(subParser)), count(count) {} - - template - auto operator()(Input& input) const - -> decltype(Impl::apply(instance(), instance(), input)); - -private: - SubParser subParser; - uint count; -}; - -template -template -struct Times_::Impl { - static Maybe> apply(const SubParser& subParser, uint count, Input& input) { - auto results = heapArrayBuilder>(count); - - while (results.size() < count) { - if (input.atEnd()) { - return nullptr; - } else KJ_IF_MAYBE(subResult, subParser(input)) { - results.add(kj::mv(*subResult)); - } else { - return nullptr; - } - } - - return results.finish(); - } -}; - -template -template -struct Times_::Impl> { - // If the sub-parser output is Tuple<>, just return a count. - - static Maybe> apply(const SubParser& subParser, uint count, Input& input) { - uint actualCount = 0; - - while (actualCount < count) { - if (input.atEnd()) { - return nullptr; - } else KJ_IF_MAYBE(subResult, subParser(input)) { - ++actualCount; - } else { - return nullptr; - } - } - - return tuple(); - } -}; - -template -template -auto Times_::operator()(Input& input) const - -> decltype(Impl::apply(instance(), instance(), input)) { - return Impl>::apply(subParser, count, input); -} - -template -constexpr Times_ times(SubParser&& subParser, uint count) { - // Constructs a parser that repeats the subParser exactly `count` times. - return Times_(kj::fwd(subParser), count); -} - -// ------------------------------------------------------------------- -// optional() -// Output = Maybe - -template -class Optional_ { -public: - explicit constexpr Optional_(SubParser&& subParser) - : subParser(kj::fwd(subParser)) {} - - template - Maybe>> operator()(Input& input) const { - typedef Maybe> Result; - - Input subInput(input); - KJ_IF_MAYBE(subResult, subParser(subInput)) { - subInput.advanceParent(); - return Result(kj::mv(*subResult)); - } else { - return Result(nullptr); - } - } - -private: - SubParser subParser; -}; - -template -constexpr Optional_ optional(SubParser&& subParser) { - // Constructs a parser that accepts zero or one of the given sub-parser, returning a Maybe - // of the sub-parser's result. - return Optional_(kj::fwd(subParser)); -} - -// ------------------------------------------------------------------- -// oneOf() -// All SubParsers must have same output type, which becomes the output type of the -// OneOfParser. - -template -class OneOf_; - -template -class OneOf_ { -public: - explicit constexpr OneOf_(FirstSubParser&& firstSubParser, SubParsers&&... rest) - : first(kj::fwd(firstSubParser)), rest(kj::fwd(rest)...) {} - - template - Maybe> operator()(Input& input) const { - { - Input subInput(input); - Maybe> firstResult = first(subInput); - - if (firstResult != nullptr) { - subInput.advanceParent(); - return kj::mv(firstResult); - } - } - - // Hoping for some tail recursion here... - return rest(input); - } - -private: - FirstSubParser first; - OneOf_ rest; -}; - -template <> -class OneOf_<> { -public: - template - decltype(nullptr) operator()(Input& input) const { - return nullptr; - } -}; - -template -constexpr OneOf_ oneOf(SubParsers&&... parsers) { - // Constructs a parser that accepts one of a set of options. The parser behaves as the first - // sub-parser in the list which returns successfully. All of the sub-parsers must return the - // same type. - return OneOf_(kj::fwd(parsers)...); -} - -// ------------------------------------------------------------------- -// transform() -// Output = Result of applying transform functor to input value. If input is a tuple, it is -// unpacked to form the transformation parameters. - -template -struct Span { -public: - inline const Position& begin() const { return begin_; } - inline const Position& end() const { return end_; } - - Span() = default; - inline constexpr Span(Position&& begin, Position&& end): begin_(mv(begin)), end_(mv(end)) {} - -private: - Position begin_; - Position end_; -}; - -template -constexpr Span> span(Position&& start, Position&& end) { - return Span>(kj::fwd(start), kj::fwd(end)); -} - -template -class Transform_ { -public: - explicit constexpr Transform_(SubParser&& subParser, TransformFunc&& transform) - : subParser(kj::fwd(subParser)), transform(kj::fwd(transform)) {} - - template - Maybe(), - instance&&>()))> - operator()(Input& input) const { - KJ_IF_MAYBE(subResult, subParser(input)) { - return kj::apply(transform, kj::mv(*subResult)); - } else { - return nullptr; - } - } - -private: - SubParser subParser; - TransformFunc transform; -}; - -template -class TransformOrReject_ { -public: - explicit constexpr TransformOrReject_(SubParser&& subParser, TransformFunc&& transform) - : subParser(kj::fwd(subParser)), transform(kj::fwd(transform)) {} - - template - decltype(kj::apply(instance(), instance&&>())) - operator()(Input& input) const { - KJ_IF_MAYBE(subResult, subParser(input)) { - return kj::apply(transform, kj::mv(*subResult)); - } else { - return nullptr; - } - } - -private: - SubParser subParser; - TransformFunc transform; -}; - -template -class TransformWithLocation_ { -public: - explicit constexpr TransformWithLocation_(SubParser&& subParser, TransformFunc&& transform) - : subParser(kj::fwd(subParser)), transform(kj::fwd(transform)) {} - - template - Maybe(), - instance().getPosition())>>>(), - instance&&>()))> - operator()(Input& input) const { - auto start = input.getPosition(); - KJ_IF_MAYBE(subResult, subParser(input)) { - return kj::apply(transform, Span(kj::mv(start), input.getPosition()), - kj::mv(*subResult)); - } else { - return nullptr; - } - } - -private: - SubParser subParser; - TransformFunc transform; -}; - -template -constexpr Transform_ transform( - SubParser&& subParser, TransformFunc&& functor) { - // Constructs a parser which executes some other parser and then transforms the result by invoking - // `functor` on it. Typically `functor` is a lambda. It is invoked using `kj::apply`, - // meaning tuples will be unpacked as arguments. - return Transform_( - kj::fwd(subParser), kj::fwd(functor)); -} - -template -constexpr TransformOrReject_ transformOrReject( - SubParser&& subParser, TransformFunc&& functor) { - // Like `transform()` except that `functor` returns a `Maybe`. If it returns null, parsing fails, - // otherwise the parser's result is the content of the `Maybe`. - return TransformOrReject_( - kj::fwd(subParser), kj::fwd(functor)); -} - -template -constexpr TransformWithLocation_ transformWithLocation( - SubParser&& subParser, TransformFunc&& functor) { - // Like `transform` except that `functor` also takes a `Span` as its first parameter specifying - // the location of the parsed content. The span's position type is whatever the parser input's - // getPosition() returns. - return TransformWithLocation_( - kj::fwd(subParser), kj::fwd(functor)); -} - -// ------------------------------------------------------------------- -// notLookingAt() -// Fails if the given parser succeeds at the current location. - -template -class NotLookingAt_ { -public: - explicit constexpr NotLookingAt_(SubParser&& subParser) - : subParser(kj::fwd(subParser)) {} - - template - Maybe> operator()(Input& input) const { - Input subInput(input); - subInput.forgetParent(); - if (subParser(subInput) == nullptr) { - return Tuple<>(); - } else { - return nullptr; - } - } - -private: - SubParser subParser; -}; - -template -constexpr NotLookingAt_ notLookingAt(SubParser&& subParser) { - // Constructs a parser which fails at any position where the given parser succeeds. Otherwise, - // it succeeds without consuming any input and returns an empty tuple. - return NotLookingAt_(kj::fwd(subParser)); -} - -// ------------------------------------------------------------------- -// endOfInput() -// Output = Tuple<>, only succeeds if at end-of-input - -class EndOfInput_ { -public: - template - Maybe> operator()(Input& input) const { - if (input.atEnd()) { - return Tuple<>(); - } else { - return nullptr; - } - } -}; - -constexpr EndOfInput_ endOfInput = EndOfInput_(); -// A parser that succeeds only if it is called with no input. - -} // namespace parse -} // namespace kj - -#endif // KJ_PARSE_COMMON_H_ diff --git a/phonelibs/capnp-cpp/include/kj/refcount.h b/phonelibs/capnp-cpp/include/kj/refcount.h deleted file mode 100644 index a24e4bf5b9..0000000000 --- a/phonelibs/capnp-cpp/include/kj/refcount.h +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#include "memory.h" - -#ifndef KJ_REFCOUNT_H_ -#define KJ_REFCOUNT_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -namespace kj { - -class Refcounted: private Disposer { - // Subclass this to create a class that contains a reference count. Then, use - // `kj::refcounted()` to allocate a new refcounted pointer. - // - // Do NOT use this lightly. Refcounting is a crutch. Good designs should strive to make object - // ownership clear, so that refcounting is not necessary. All that said, reference counting can - // sometimes simplify code that would otherwise become convoluted with explicit ownership, even - // when ownership relationships are clear at an abstract level. - // - // NOT THREADSAFE: This refcounting implementation assumes that an object's references are - // manipulated only in one thread, because atomic (thread-safe) refcounting is surprisingly slow. - // - // In general, abstract classes should _not_ subclass this. The concrete class at the bottom - // of the hierarchy should be the one to decide how it implements refcounting. Interfaces should - // expose only an `addRef()` method that returns `Own`. There are two reasons for - // this rule: - // 1. Interfaces would need to virtually inherit Refcounted, otherwise two refcounted interfaces - // could not be inherited by the same subclass. Virtual inheritance is awkward and - // inefficient. - // 2. An implementation may decide that it would rather return a copy than a refcount, or use - // some other strategy. - // - // TODO(cleanup): Rethink above. Virtual inheritance is not necessarily that bad. OTOH, a - // virtual function call for every refcount is sad in its own way. A Ref type to replace - // Own could also be nice. - -public: - virtual ~Refcounted() noexcept(false); - - inline bool isShared() const { return refcount > 1; } - // Check if there are multiple references to this object. This is sometimes useful for deciding - // whether it's safe to modify the object vs. make a copy. - -private: - mutable uint refcount = 0; - // "mutable" because disposeImpl() is const. Bleh. - - void disposeImpl(void* pointer) const override; - template - static Own addRefInternal(T* object); - - template - friend Own addRef(T& object); - template - friend Own refcounted(Params&&... params); -}; - -template -inline Own refcounted(Params&&... params) { - // Allocate a new refcounted instance of T, passing `params` to its constructor. Returns an - // initial reference to the object. More references can be created with `kj::addRef()`. - - return Refcounted::addRefInternal(new T(kj::fwd(params)...)); -} - -template -Own addRef(T& object) { - // Return a new reference to `object`, which must subclass Refcounted and have been allocated - // using `kj::refcounted<>()`. It is suggested that subclasses implement a non-static addRef() - // method which wraps this and returns the appropriate type. - - KJ_IREQUIRE(object.Refcounted::refcount > 0, "Object not allocated with kj::refcounted()."); - return Refcounted::addRefInternal(&object); -} - -template -Own Refcounted::addRefInternal(T* object) { - Refcounted* refcounted = object; - ++refcounted->refcount; - return Own(object, *refcounted); -} - -} // namespace kj - -#endif // KJ_REFCOUNT_H_ diff --git a/phonelibs/capnp-cpp/include/kj/std/iostream.h b/phonelibs/capnp-cpp/include/kj/std/iostream.h deleted file mode 100644 index 627e0fcf86..0000000000 --- a/phonelibs/capnp-cpp/include/kj/std/iostream.h +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) 2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -/* - * Compatibility layer for stdlib iostream - */ - -#ifndef KJ_STD_IOSTREAM_H_ -#define KJ_STD_IOSTREAM_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "../io.h" -#include - -namespace kj { -namespace std { - -class StdOutputStream: public kj::OutputStream { - -public: - explicit StdOutputStream(::std::ostream& stream) : stream_(stream) {} - ~StdOutputStream() noexcept(false) {} - - virtual void write(const void* src, size_t size) override { - // Always writes the full size. - - stream_.write((char*)src, size); - } - - virtual void write(ArrayPtr> pieces) override { - // Equivalent to write()ing each byte array in sequence, which is what the - // default implementation does. Override if you can do something better, - // e.g. use writev() to do the write in a single syscall. - - for (auto piece : pieces) { - write(piece.begin(), piece.size()); - } - } - -private: - ::std::ostream& stream_; - -}; - -class StdInputStream: public kj::InputStream { - -public: - explicit StdInputStream(::std::istream& stream) : stream_(stream) {} - ~StdInputStream() noexcept(false) {} - - virtual size_t tryRead( - void* buffer, size_t minBytes, size_t maxBytes) override { - // Like read(), but may return fewer than minBytes on EOF. - - stream_.read((char*)buffer, maxBytes); - return stream_.gcount(); - } - -private: - ::std::istream& stream_; - -}; - -} // namespace std -} // namespace kj - -#endif // KJ_STD_IOSTREAM_H_ diff --git a/phonelibs/capnp-cpp/include/kj/string-tree.h b/phonelibs/capnp-cpp/include/kj/string-tree.h deleted file mode 100644 index 70a46319ef..0000000000 --- a/phonelibs/capnp-cpp/include/kj/string-tree.h +++ /dev/null @@ -1,212 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_STRING_TREE_H_ -#define KJ_STRING_TREE_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "string.h" - -namespace kj { - -class StringTree { - // A long string, represented internally as a tree of strings. This data structure is like a - // String, but optimized for concatenation and iteration at the expense of seek time. The - // structure is intended to be used for building large text blobs from many small pieces, where - // repeatedly concatenating smaller strings into larger ones would waste copies. This structure - // is NOT intended for use cases requiring random access or computing substrings. For those, - // you should use a Rope, which is a much more complicated data structure. - // - // The proper way to construct a StringTree is via kj::strTree(...), which works just like - // kj::str(...) but returns a StringTree rather than a String. - // - // KJ_STRINGIFY() functions that construct large strings from many smaller strings are encouraged - // to return StringTree rather than a flat char container. - -public: - inline StringTree(): size_(0) {} - inline StringTree(String&& text): size_(text.size()), text(kj::mv(text)) {} - - StringTree(Array&& pieces, StringPtr delim); - // Build a StringTree by concatenating the given pieces, delimited by the given delimiter - // (e.g. ", "). - - inline size_t size() const { return size_; } - - template - void visit(Func&& func) const; - - String flatten() const; - // Return the contents as a string. - - // TODO(someday): flatten() when *this is an rvalue and when branches.size() == 0 could simply - // return `kj::mv(text)`. Requires reference qualifiers (Clang 3.3 / GCC 4.8). - - void flattenTo(char* __restrict__ target) const; - // Copy the contents to the given character array. Does not add a NUL terminator. - -private: - size_t size_; - String text; - - struct Branch; - Array branches; // In order. - - inline void fill(char* pos, size_t branchIndex); - template - void fill(char* pos, size_t branchIndex, First&& first, Rest&&... rest); - template - void fill(char* pos, size_t branchIndex, StringTree&& first, Rest&&... rest); - template - void fill(char* pos, size_t branchIndex, Array&& first, Rest&&... rest); - template - void fill(char* pos, size_t branchIndex, String&& first, Rest&&... rest); - - template - static StringTree concat(Params&&... params); - static StringTree&& concat(StringTree&& param) { return kj::mv(param); } - - template - static inline size_t flatSize(const T& t) { return t.size(); } - static inline size_t flatSize(String&& s) { return 0; } - static inline size_t flatSize(StringTree&& s) { return 0; } - - template - static inline size_t branchCount(const T& t) { return 0; } - static inline size_t branchCount(String&& s) { return 1; } - static inline size_t branchCount(StringTree&& s) { return 1; } - - template - friend StringTree strTree(Params&&... params); -}; - -inline StringTree&& KJ_STRINGIFY(StringTree&& tree) { return kj::mv(tree); } -inline const StringTree& KJ_STRINGIFY(const StringTree& tree) { return tree; } - -inline StringTree KJ_STRINGIFY(Array&& trees) { return StringTree(kj::mv(trees), ""); } - -template -StringTree strTree(Params&&... params); -// Build a StringTree by stringifying the given parameters and concatenating the results. -// If any of the parameters stringify to StringTree rvalues, they will be incorporated as -// branches to avoid a copy. - -// ======================================================================================= -// Inline implementation details - -namespace _ { // private - -template -char* fill(char* __restrict__ target, const StringTree& first, Rest&&... rest) { - // Make str() work with stringifiers that return StringTree by patching fill(). - - first.flattenTo(target); - return fill(target + first.size(), kj::fwd(rest)...); -} - -template constexpr bool isStringTree() { return false; } -template <> constexpr bool isStringTree() { return true; } - -inline StringTree&& toStringTreeOrCharSequence(StringTree&& tree) { return kj::mv(tree); } -inline StringTree toStringTreeOrCharSequence(String&& str) { return StringTree(kj::mv(str)); } - -template -inline auto toStringTreeOrCharSequence(T&& value) - -> decltype(toCharSequence(kj::fwd(value))) { - static_assert(!isStringTree>(), - "When passing a StringTree into kj::strTree(), either pass it by rvalue " - "(use kj::mv(value)) or explicitly call value.flatten() to make a copy."); - - return toCharSequence(kj::fwd(value)); -} - -} // namespace _ (private) - -struct StringTree::Branch { - size_t index; - // Index in `text` where this branch should be inserted. - - StringTree content; -}; - -template -void StringTree::visit(Func&& func) const { - size_t pos = 0; - for (auto& branch: branches) { - if (branch.index > pos) { - func(text.slice(pos, branch.index)); - pos = branch.index; - } - branch.content.visit(func); - } - if (text.size() > pos) { - func(text.slice(pos, text.size())); - } -} - -inline void StringTree::fill(char* pos, size_t branchIndex) { - KJ_IREQUIRE(pos == text.end() && branchIndex == branches.size(), - kj::str(text.end() - pos, ' ', branches.size() - branchIndex).cStr()); -} - -template -void StringTree::fill(char* pos, size_t branchIndex, First&& first, Rest&&... rest) { - pos = _::fill(pos, kj::fwd(first)); - fill(pos, branchIndex, kj::fwd(rest)...); -} - -template -void StringTree::fill(char* pos, size_t branchIndex, StringTree&& first, Rest&&... rest) { - branches[branchIndex].index = pos - text.begin(); - branches[branchIndex].content = kj::mv(first); - fill(pos, branchIndex + 1, kj::fwd(rest)...); -} - -template -void StringTree::fill(char* pos, size_t branchIndex, String&& first, Rest&&... rest) { - branches[branchIndex].index = pos - text.begin(); - branches[branchIndex].content = StringTree(kj::mv(first)); - fill(pos, branchIndex + 1, kj::fwd(rest)...); -} - -template -StringTree StringTree::concat(Params&&... params) { - StringTree result; - result.size_ = _::sum({params.size()...}); - result.text = heapString( - _::sum({StringTree::flatSize(kj::fwd(params))...})); - result.branches = heapArray( - _::sum({StringTree::branchCount(kj::fwd(params))...})); - result.fill(result.text.begin(), 0, kj::fwd(params)...); - return result; -} - -template -StringTree strTree(Params&&... params) { - return StringTree::concat(_::toStringTreeOrCharSequence(kj::fwd(params))...); -} - -} // namespace kj - -#endif // KJ_STRING_TREE_H_ diff --git a/phonelibs/capnp-cpp/include/kj/string.h b/phonelibs/capnp-cpp/include/kj/string.h deleted file mode 100644 index 9048be2417..0000000000 --- a/phonelibs/capnp-cpp/include/kj/string.h +++ /dev/null @@ -1,534 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_STRING_H_ -#define KJ_STRING_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include -#include "array.h" -#include - -namespace kj { - -class StringPtr; -class String; - -class StringTree; // string-tree.h - -// Our STL string SFINAE trick does not work with GCC 4.7, but it works with Clang and GCC 4.8, so -// we'll just preprocess it out if not supported. -#if __clang__ || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) || _MSC_VER -#define KJ_COMPILER_SUPPORTS_STL_STRING_INTEROP 1 -#endif - -// ======================================================================================= -// StringPtr -- A NUL-terminated ArrayPtr containing UTF-8 text. -// -// NUL bytes are allowed to appear before the end of the string. The only requirement is that -// a NUL byte appear immediately after the last byte of the content. This terminator byte is not -// counted in the string's size. - -class StringPtr { -public: - inline StringPtr(): content("", 1) {} - inline StringPtr(decltype(nullptr)): content("", 1) {} - inline StringPtr(const char* value): content(value, strlen(value) + 1) {} - inline StringPtr(const char* value, size_t size): content(value, size + 1) { - KJ_IREQUIRE(value[size] == '\0', "StringPtr must be NUL-terminated."); - } - inline StringPtr(const char* begin, const char* end): StringPtr(begin, end - begin) {} - inline StringPtr(const String& value); - -#if KJ_COMPILER_SUPPORTS_STL_STRING_INTEROP - template ().c_str())> - inline StringPtr(const T& t): StringPtr(t.c_str()) {} - // Allow implicit conversion from any class that has a c_str() method (namely, std::string). - // We use a template trick to detect std::string in order to avoid including the header for - // those who don't want it. - - template ().c_str())> - inline operator T() const { return cStr(); } - // Allow implicit conversion to any class that has a c_str() method (namely, std::string). - // We use a template trick to detect std::string in order to avoid including the header for - // those who don't want it. -#endif - - inline operator ArrayPtr() const; - inline ArrayPtr asArray() const; - inline ArrayPtr asBytes() const { return asArray().asBytes(); } - // Result does not include NUL terminator. - - inline const char* cStr() const { return content.begin(); } - // Returns NUL-terminated string. - - inline size_t size() const { return content.size() - 1; } - // Result does not include NUL terminator. - - inline char operator[](size_t index) const { return content[index]; } - - inline const char* begin() const { return content.begin(); } - inline const char* end() const { return content.end() - 1; } - - inline bool operator==(decltype(nullptr)) const { return content.size() <= 1; } - inline bool operator!=(decltype(nullptr)) const { return content.size() > 1; } - - inline bool operator==(const StringPtr& other) const; - inline bool operator!=(const StringPtr& other) const { return !(*this == other); } - inline bool operator< (const StringPtr& other) const; - inline bool operator> (const StringPtr& other) const { return other < *this; } - inline bool operator<=(const StringPtr& other) const { return !(other < *this); } - inline bool operator>=(const StringPtr& other) const { return !(*this < other); } - - inline StringPtr slice(size_t start) const; - inline ArrayPtr slice(size_t start, size_t end) const; - // A string slice is only NUL-terminated if it is a suffix, so slice() has a one-parameter - // version that assumes end = size(). - - inline bool startsWith(const StringPtr& other) const; - inline bool endsWith(const StringPtr& other) const; - - inline Maybe findFirst(char c) const; - inline Maybe findLast(char c) const; - - template - T parseAs() const; - // Parse string as template number type. - // Integer numbers prefixed by "0x" and "0X" are parsed in base 16 (like strtoi with base 0). - // Integer numbers prefixed by "0" are parsed in base 10 (unlike strtoi with base 0). - // Overflowed integer numbers throw exception. - // Overflowed floating numbers return inf. - -private: - inline StringPtr(ArrayPtr content): content(content) {} - - ArrayPtr content; -}; - -inline bool operator==(const char* a, const StringPtr& b) { return b == a; } -inline bool operator!=(const char* a, const StringPtr& b) { return b != a; } - -template <> char StringPtr::parseAs() const; -template <> signed char StringPtr::parseAs() const; -template <> unsigned char StringPtr::parseAs() const; -template <> short StringPtr::parseAs() const; -template <> unsigned short StringPtr::parseAs() const; -template <> int StringPtr::parseAs() const; -template <> unsigned StringPtr::parseAs() const; -template <> long StringPtr::parseAs() const; -template <> unsigned long StringPtr::parseAs() const; -template <> long long StringPtr::parseAs() const; -template <> unsigned long long StringPtr::parseAs() const; -template <> float StringPtr::parseAs() const; -template <> double StringPtr::parseAs() const; - -// ======================================================================================= -// String -- A NUL-terminated Array containing UTF-8 text. -// -// NUL bytes are allowed to appear before the end of the string. The only requirement is that -// a NUL byte appear immediately after the last byte of the content. This terminator byte is not -// counted in the string's size. -// -// To allocate a String, you must call kj::heapString(). We do not implement implicit copying to -// the heap because this hides potential inefficiency from the developer. - -class String { -public: - String() = default; - inline String(decltype(nullptr)): content(nullptr) {} - inline String(char* value, size_t size, const ArrayDisposer& disposer); - // Does not copy. `size` does not include NUL terminator, but `value` must be NUL-terminated. - inline explicit String(Array buffer); - // Does not copy. Requires `buffer` ends with `\0`. - - inline operator ArrayPtr(); - inline operator ArrayPtr() const; - inline ArrayPtr asArray(); - inline ArrayPtr asArray() const; - inline ArrayPtr asBytes() { return asArray().asBytes(); } - inline ArrayPtr asBytes() const { return asArray().asBytes(); } - // Result does not include NUL terminator. - - inline Array releaseArray() { return kj::mv(content); } - // Disowns the backing array (which includes the NUL terminator) and returns it. The String value - // is clobbered (as if moved away). - - inline const char* cStr() const; - - inline size_t size() const; - // Result does not include NUL terminator. - - inline char operator[](size_t index) const; - inline char& operator[](size_t index); - - inline char* begin(); - inline char* end(); - inline const char* begin() const; - inline const char* end() const; - - inline bool operator==(decltype(nullptr)) const { return content.size() <= 1; } - inline bool operator!=(decltype(nullptr)) const { return content.size() > 1; } - - inline bool operator==(const StringPtr& other) const { return StringPtr(*this) == other; } - inline bool operator!=(const StringPtr& other) const { return StringPtr(*this) != other; } - inline bool operator< (const StringPtr& other) const { return StringPtr(*this) < other; } - inline bool operator> (const StringPtr& other) const { return StringPtr(*this) > other; } - inline bool operator<=(const StringPtr& other) const { return StringPtr(*this) <= other; } - inline bool operator>=(const StringPtr& other) const { return StringPtr(*this) >= other; } - - inline bool startsWith(const StringPtr& other) const { return StringPtr(*this).startsWith(other);} - inline bool endsWith(const StringPtr& other) const { return StringPtr(*this).endsWith(other); } - - inline StringPtr slice(size_t start) const { return StringPtr(*this).slice(start); } - inline ArrayPtr slice(size_t start, size_t end) const { - return StringPtr(*this).slice(start, end); - } - - inline Maybe findFirst(char c) const { return StringPtr(*this).findFirst(c); } - inline Maybe findLast(char c) const { return StringPtr(*this).findLast(c); } - - template - T parseAs() const { return StringPtr(*this).parseAs(); } - // Parse as number - -private: - Array content; -}; - -inline bool operator==(const char* a, const String& b) { return b == a; } -inline bool operator!=(const char* a, const String& b) { return b != a; } - -String heapString(size_t size); -// Allocate a String of the given size on the heap, not including NUL terminator. The NUL -// terminator will be initialized automatically but the rest of the content is not initialized. - -String heapString(const char* value); -String heapString(const char* value, size_t size); -String heapString(StringPtr value); -String heapString(const String& value); -String heapString(ArrayPtr value); -// Allocates a copy of the given value on the heap. - -// ======================================================================================= -// Magic str() function which transforms parameters to text and concatenates them into one big -// String. - -namespace _ { // private - -inline size_t sum(std::initializer_list nums) { - size_t result = 0; - for (auto num: nums) { - result += num; - } - return result; -} - -inline char* fill(char* ptr) { return ptr; } - -template -char* fill(char* __restrict__ target, const StringTree& first, Rest&&... rest); -// Make str() work with stringifiers that return StringTree by patching fill(). -// -// Defined in string-tree.h. - -template -char* fill(char* __restrict__ target, const First& first, Rest&&... rest) { - auto i = first.begin(); - auto end = first.end(); - while (i != end) { - *target++ = *i++; - } - return fill(target, kj::fwd(rest)...); -} - -template -String concat(Params&&... params) { - // Concatenate a bunch of containers into a single Array. The containers can be anything that - // is iterable and whose elements can be converted to `char`. - - String result = heapString(sum({params.size()...})); - fill(result.begin(), kj::fwd(params)...); - return result; -} - -inline String concat(String&& arr) { - return kj::mv(arr); -} - -struct Stringifier { - // This is a dummy type with only one instance: STR (below). To make an arbitrary type - // stringifiable, define `operator*(Stringifier, T)` to return an iterable container of `char`. - // The container type must have a `size()` method. Be sure to declare the operator in the same - // namespace as `T` **or** in the global scope. - // - // A more usual way to accomplish what we're doing here would be to require that you define - // a function like `toString(T)` and then rely on argument-dependent lookup. However, this has - // the problem that it pollutes other people's namespaces and even the global namespace. For - // example, some other project may already have functions called `toString` which do something - // different. Declaring `operator*` with `Stringifier` as the left operand cannot conflict with - // anything. - - inline ArrayPtr operator*(ArrayPtr s) const { return s; } - inline ArrayPtr operator*(ArrayPtr s) const { return s; } - inline ArrayPtr operator*(const Array& s) const { return s; } - inline ArrayPtr operator*(const Array& s) const { return s; } - template - inline ArrayPtr operator*(const CappedArray& s) const { return s; } - template - inline ArrayPtr operator*(const FixedArray& s) const { return s; } - inline ArrayPtr operator*(const char* s) const { return arrayPtr(s, strlen(s)); } - inline ArrayPtr operator*(const String& s) const { return s.asArray(); } - inline ArrayPtr operator*(const StringPtr& s) const { return s.asArray(); } - - inline Range operator*(const Range& r) const { return r; } - inline Repeat operator*(const Repeat& r) const { return r; } - - inline FixedArray operator*(char c) const { - FixedArray result; - result[0] = c; - return result; - } - - StringPtr operator*(decltype(nullptr)) const; - StringPtr operator*(bool b) const; - - CappedArray operator*(signed char i) const; - CappedArray operator*(unsigned char i) const; - CappedArray operator*(short i) const; - CappedArray operator*(unsigned short i) const; - CappedArray operator*(int i) const; - CappedArray operator*(unsigned int i) const; - CappedArray operator*(long i) const; - CappedArray operator*(unsigned long i) const; - CappedArray operator*(long long i) const; - CappedArray operator*(unsigned long long i) const; - CappedArray operator*(float f) const; - CappedArray operator*(double f) const; - CappedArray operator*(const void* s) const; - - template - String operator*(ArrayPtr arr) const; - template - String operator*(const Array& arr) const; - -#if KJ_COMPILER_SUPPORTS_STL_STRING_INTEROP // supports expression SFINAE? - template ().toString())> - inline Result operator*(T&& value) const { return kj::fwd(value).toString(); } -#endif -}; -static KJ_CONSTEXPR(const) Stringifier STR = Stringifier(); - -} // namespace _ (private) - -template -auto toCharSequence(T&& value) -> decltype(_::STR * kj::fwd(value)) { - // Returns an iterable of chars that represent a textual representation of the value, suitable - // for debugging. - // - // Most users should use str() instead, but toCharSequence() may occasionally be useful to avoid - // heap allocation overhead that str() implies. - // - // To specialize this function for your type, see KJ_STRINGIFY. - - return _::STR * kj::fwd(value); -} - -CappedArray hex(unsigned char i); -CappedArray hex(unsigned short i); -CappedArray hex(unsigned int i); -CappedArray hex(unsigned long i); -CappedArray hex(unsigned long long i); - -template -String str(Params&&... params) { - // Magic function which builds a string from a bunch of arbitrary values. Example: - // str(1, " / ", 2, " = ", 0.5) - // returns: - // "1 / 2 = 0.5" - // To teach `str` how to stringify a type, see `Stringifier`. - - return _::concat(toCharSequence(kj::fwd(params))...); -} - -inline String str(String&& s) { return mv(s); } -// Overload to prevent redundant allocation. - -template -String strArray(T&& arr, const char* delim) { - size_t delimLen = strlen(delim); - KJ_STACK_ARRAY(decltype(_::STR * arr[0]), pieces, kj::size(arr), 8, 32); - size_t size = 0; - for (size_t i = 0; i < kj::size(arr); i++) { - if (i > 0) size += delimLen; - pieces[i] = _::STR * arr[i]; - size += pieces[i].size(); - } - - String result = heapString(size); - char* pos = result.begin(); - for (size_t i = 0; i < kj::size(arr); i++) { - if (i > 0) { - memcpy(pos, delim, delimLen); - pos += delimLen; - } - pos = _::fill(pos, pieces[i]); - } - return result; -} - -namespace _ { // private - -template -inline String Stringifier::operator*(ArrayPtr arr) const { - return strArray(arr, ", "); -} - -template -inline String Stringifier::operator*(const Array& arr) const { - return strArray(arr, ", "); -} - -} // namespace _ (private) - -#define KJ_STRINGIFY(...) operator*(::kj::_::Stringifier, __VA_ARGS__) -// Defines a stringifier for a custom type. Example: -// -// class Foo {...}; -// inline StringPtr KJ_STRINGIFY(const Foo& foo) { return foo.name(); } -// -// This allows Foo to be passed to str(). -// -// The function should be declared either in the same namespace as the target type or in the global -// namespace. It can return any type which is an iterable container of chars. - -// ======================================================================================= -// Inline implementation details. - -inline StringPtr::StringPtr(const String& value): content(value.begin(), value.size() + 1) {} - -inline StringPtr::operator ArrayPtr() const { - return content.slice(0, content.size() - 1); -} - -inline ArrayPtr StringPtr::asArray() const { - return content.slice(0, content.size() - 1); -} - -inline bool StringPtr::operator==(const StringPtr& other) const { - return content.size() == other.content.size() && - memcmp(content.begin(), other.content.begin(), content.size() - 1) == 0; -} - -inline bool StringPtr::operator<(const StringPtr& other) const { - bool shorter = content.size() < other.content.size(); - int cmp = memcmp(content.begin(), other.content.begin(), - shorter ? content.size() : other.content.size()); - return cmp < 0 || (cmp == 0 && shorter); -} - -inline StringPtr StringPtr::slice(size_t start) const { - return StringPtr(content.slice(start, content.size())); -} -inline ArrayPtr StringPtr::slice(size_t start, size_t end) const { - return content.slice(start, end); -} - -inline bool StringPtr::startsWith(const StringPtr& other) const { - return other.content.size() <= content.size() && - memcmp(content.begin(), other.content.begin(), other.size()) == 0; -} -inline bool StringPtr::endsWith(const StringPtr& other) const { - return other.content.size() <= content.size() && - memcmp(end() - other.size(), other.content.begin(), other.size()) == 0; -} - -inline Maybe StringPtr::findFirst(char c) const { - const char* pos = reinterpret_cast(memchr(content.begin(), c, size())); - if (pos == nullptr) { - return nullptr; - } else { - return pos - content.begin(); - } -} - -inline Maybe StringPtr::findLast(char c) const { - for (size_t i = size(); i > 0; --i) { - if (content[i-1] == c) { - return i-1; - } - } - return nullptr; -} - -inline String::operator ArrayPtr() { - return content == nullptr ? ArrayPtr(nullptr) : content.slice(0, content.size() - 1); -} -inline String::operator ArrayPtr() const { - return content == nullptr ? ArrayPtr(nullptr) : content.slice(0, content.size() - 1); -} - -inline ArrayPtr String::asArray() { - return content == nullptr ? ArrayPtr(nullptr) : content.slice(0, content.size() - 1); -} -inline ArrayPtr String::asArray() const { - return content == nullptr ? ArrayPtr(nullptr) : content.slice(0, content.size() - 1); -} - -inline const char* String::cStr() const { return content == nullptr ? "" : content.begin(); } - -inline size_t String::size() const { return content == nullptr ? 0 : content.size() - 1; } - -inline char String::operator[](size_t index) const { return content[index]; } -inline char& String::operator[](size_t index) { return content[index]; } - -inline char* String::begin() { return content == nullptr ? nullptr : content.begin(); } -inline char* String::end() { return content == nullptr ? nullptr : content.end() - 1; } -inline const char* String::begin() const { return content == nullptr ? nullptr : content.begin(); } -inline const char* String::end() const { return content == nullptr ? nullptr : content.end() - 1; } - -inline String::String(char* value, size_t size, const ArrayDisposer& disposer) - : content(value, size + 1, disposer) { - KJ_IREQUIRE(value[size] == '\0', "String must be NUL-terminated."); -} - -inline String::String(Array buffer): content(kj::mv(buffer)) { - KJ_IREQUIRE(content.size() > 0 && content.back() == '\0', "String must be NUL-terminated."); -} - -inline String heapString(const char* value) { - return heapString(value, strlen(value)); -} -inline String heapString(StringPtr value) { - return heapString(value.begin(), value.size()); -} -inline String heapString(const String& value) { - return heapString(value.begin(), value.size()); -} -inline String heapString(ArrayPtr value) { - return heapString(value.begin(), value.size()); -} - -} // namespace kj - -#endif // KJ_STRING_H_ diff --git a/phonelibs/capnp-cpp/include/kj/test.h b/phonelibs/capnp-cpp/include/kj/test.h deleted file mode 100644 index 69e1c80840..0000000000 --- a/phonelibs/capnp-cpp/include/kj/test.h +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_TEST_H_ -#define KJ_TEST_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "debug.h" -#include "vector.h" -#include "function.h" - -namespace kj { - -class TestRunner; - -class TestCase { -public: - TestCase(const char* file, uint line, const char* description); - ~TestCase(); - - virtual void run() = 0; - -private: - const char* file; - uint line; - const char* description; - TestCase* next; - TestCase** prev; - bool matchedFilter; - - friend class TestRunner; -}; - -#define KJ_TEST(description) \ - /* Make sure the linker fails if tests are not in anonymous namespaces. */ \ - extern int KJ_CONCAT(YouMustWrapTestsInAnonymousNamespace, __COUNTER__) KJ_UNUSED; \ - class KJ_UNIQUE_NAME(TestCase): public ::kj::TestCase { \ - public: \ - KJ_UNIQUE_NAME(TestCase)(): ::kj::TestCase(__FILE__, __LINE__, description) {} \ - void run() override; \ - } KJ_UNIQUE_NAME(testCase); \ - void KJ_UNIQUE_NAME(TestCase)::run() - -#if _MSC_VER -#define KJ_INDIRECT_EXPAND(m, vargs) m vargs -#define KJ_FAIL_EXPECT(...) \ - KJ_INDIRECT_EXPAND(KJ_LOG, (ERROR , __VA_ARGS__)); -#define KJ_EXPECT(cond, ...) \ - if (cond); else KJ_INDIRECT_EXPAND(KJ_FAIL_EXPECT, ("failed: expected " #cond , __VA_ARGS__)) -#else -#define KJ_FAIL_EXPECT(...) \ - KJ_LOG(ERROR, ##__VA_ARGS__); -#define KJ_EXPECT(cond, ...) \ - if (cond); else KJ_FAIL_EXPECT("failed: expected " #cond, ##__VA_ARGS__) -#endif - -#define KJ_EXPECT_THROW_RECOVERABLE(type, code) \ - do { \ - KJ_IF_MAYBE(e, ::kj::runCatchingExceptions([&]() { code; })) { \ - KJ_EXPECT(e->getType() == ::kj::Exception::Type::type, \ - "code threw wrong exception type: " #code, e->getType()); \ - } else { \ - KJ_FAIL_EXPECT("code did not throw: " #code); \ - } \ - } while (false) - -#define KJ_EXPECT_THROW_RECOVERABLE_MESSAGE(message, code) \ - do { \ - KJ_IF_MAYBE(e, ::kj::runCatchingExceptions([&]() { code; })) { \ - KJ_EXPECT(::kj::_::hasSubstring(e->getDescription(), message), \ - "exception description didn't contain expected substring", e->getDescription()); \ - } else { \ - KJ_FAIL_EXPECT("code did not throw: " #code); \ - } \ - } while (false) - -#if KJ_NO_EXCEPTIONS -#define KJ_EXPECT_THROW(type, code) \ - do { \ - KJ_EXPECT(::kj::_::expectFatalThrow(type, nullptr, [&]() { code; })); \ - } while (false) -#define KJ_EXPECT_THROW_MESSAGE(message, code) \ - do { \ - KJ_EXPECT(::kj::_::expectFatalThrow(nullptr, kj::StringPtr(message), [&]() { code; })); \ - } while (false) -#else -#define KJ_EXPECT_THROW KJ_EXPECT_THROW_RECOVERABLE -#define KJ_EXPECT_THROW_MESSAGE KJ_EXPECT_THROW_RECOVERABLE_MESSAGE -#endif - -#define KJ_EXPECT_LOG(level, substring) \ - ::kj::_::LogExpectation KJ_UNIQUE_NAME(_kjLogExpectation)(::kj::LogSeverity::level, substring) -// Expects that a log message with the given level and substring text will be printed within -// the current scope. This message will not cause the test to fail, even if it is an error. - -// ======================================================================================= - -namespace _ { // private - -bool hasSubstring(kj::StringPtr haystack, kj::StringPtr needle); - -#if KJ_NO_EXCEPTIONS -bool expectFatalThrow(Maybe type, Maybe message, - Function code); -// Expects that the given code will throw a fatal exception matching the given type and/or message. -// Since exceptions are disabled, the test will fork() and run in a subprocess. On Windows, where -// fork() is not available, this always returns true. -#endif - -class LogExpectation: public ExceptionCallback { -public: - LogExpectation(LogSeverity severity, StringPtr substring); - ~LogExpectation(); - - void logMessage(LogSeverity severity, const char* file, int line, int contextDepth, - String&& text) override; - -private: - LogSeverity severity; - StringPtr substring; - bool seen; - UnwindDetector unwindDetector; -}; - -class GlobFilter { - // Implements glob filters for the --filter flag. - // - // Exposed in header only for testing. - -public: - explicit GlobFilter(const char* pattern); - explicit GlobFilter(ArrayPtr pattern); - - bool matches(StringPtr name); - -private: - String pattern; - Vector states; - - void applyState(char c, int state); -}; - -} // namespace _ (private) -} // namespace kj - -#endif // KJ_TEST_H_ diff --git a/phonelibs/capnp-cpp/include/kj/thread.h b/phonelibs/capnp-cpp/include/kj/thread.h deleted file mode 100644 index b17b88c520..0000000000 --- a/phonelibs/capnp-cpp/include/kj/thread.h +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_THREAD_H_ -#define KJ_THREAD_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "common.h" -#include "function.h" -#include "exception.h" - -namespace kj { - -class Thread { - // A thread! Pass a lambda to the constructor, and it runs in the thread. The destructor joins - // the thread. If the function throws an exception, it is rethrown from the thread's destructor - // (if not unwinding from another exception). - -public: - explicit Thread(Function func); - KJ_DISALLOW_COPY(Thread); - - ~Thread() noexcept(false); - -#if !_WIN32 - void sendSignal(int signo); - // Send a Unix signal to the given thread, using pthread_kill or an equivalent. -#endif - - void detach(); - // Don't join the thread in ~Thread(). - -private: - struct ThreadState { - Function func; - kj::Maybe exception; - - unsigned int refcount; - // Owned by the parent thread and the child thread. - - void unref(); - }; - ThreadState* state; - -#if _WIN32 - void* threadHandle; -#else - unsigned long long threadId; // actually pthread_t -#endif - bool detached = false; - -#if _WIN32 - static unsigned long __stdcall runThread(void* ptr); -#else - static void* runThread(void* ptr); -#endif -}; - -} // namespace kj - -#endif // KJ_THREAD_H_ diff --git a/phonelibs/capnp-cpp/include/kj/threadlocal.h b/phonelibs/capnp-cpp/include/kj/threadlocal.h deleted file mode 100644 index 67d0db60ef..0000000000 --- a/phonelibs/capnp-cpp/include/kj/threadlocal.h +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright (c) 2014, Jason Choy -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_THREADLOCAL_H_ -#define KJ_THREADLOCAL_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif -// This file declares a macro `KJ_THREADLOCAL_PTR` for declaring thread-local pointer-typed -// variables. Use like: -// KJ_THREADLOCAL_PTR(MyType) foo = nullptr; -// This is equivalent to: -// thread_local MyType* foo = nullptr; -// This can only be used at the global scope. -// -// AVOID USING THIS. Use of thread-locals is discouraged because they often have many of the same -// properties as singletons: http://www.object-oriented-security.org/lets-argue/singletons -// -// Also, thread-locals tend to be hostile to event-driven code, which can be particularly -// surprising when using fibers (all fibers in the same thread will share the same threadlocals, -// even though they do not share a stack). -// -// That said, thread-locals are sometimes needed for runtime logistics in the KJ framework. For -// example, the current exception callback and current EventLoop are stored as thread-local -// pointers. Since KJ only ever needs to store pointers, not values, we avoid the question of -// whether these values' destructors need to be run, and we avoid the need for heap allocation. - -#include "common.h" - -#if !defined(KJ_USE_PTHREAD_THREADLOCAL) && defined(__APPLE__) -#include "TargetConditionals.h" -#if TARGET_OS_IPHONE -// iOS apparently does not support __thread (nor C++11 thread_local). -#define KJ_USE_PTHREAD_TLS 1 -#endif -#endif - -#if KJ_USE_PTHREAD_TLS -#include -#endif - -namespace kj { - -#if KJ_USE_PTHREAD_TLS -// If __thread is unavailable, we'll fall back to pthreads. - -#define KJ_THREADLOCAL_PTR(type) \ - namespace { struct KJ_UNIQUE_NAME(_kj_TlpTag); } \ - static ::kj::_::ThreadLocalPtr< type, KJ_UNIQUE_NAME(_kj_TlpTag)> -// Hack: In order to ensure each thread-local results in a unique template instance, we declare -// a one-off dummy type to use as the second type parameter. - -namespace _ { // private - -template -class ThreadLocalPtr { - // Hacky type to emulate __thread T*. We need a separate instance of the ThreadLocalPtr template - // for every thread-local variable, because we don't want to require a global constructor, and in - // order to initialize the TLS on first use we need to use a local static variable (in getKey()). - // Each template instance will get a separate such local static variable, fulfilling our need. - -public: - ThreadLocalPtr() = default; - constexpr ThreadLocalPtr(decltype(nullptr)) {} - // Allow initialization to nullptr without a global constructor. - - inline ThreadLocalPtr& operator=(T* val) { - pthread_setspecific(getKey(), val); - return *this; - } - - inline operator T*() const { - return get(); - } - - inline T& operator*() const { - return *get(); - } - - inline T* operator->() const { - return get(); - } - -private: - inline T* get() const { - return reinterpret_cast(pthread_getspecific(getKey())); - } - - inline static pthread_key_t getKey() { - static pthread_key_t key = createKey(); - return key; - } - - static pthread_key_t createKey() { - pthread_key_t key; - pthread_key_create(&key, 0); - return key; - } -}; - -} // namespace _ (private) - -#elif __GNUC__ - -#define KJ_THREADLOCAL_PTR(type) static __thread type* -// GCC's __thread is lighter-weight than thread_local and is good enough for our purposes. - -#else - -#define KJ_THREADLOCAL_PTR(type) static thread_local type* - -#endif // KJ_USE_PTHREAD_TLS - -} // namespace kj - -#endif // KJ_THREADLOCAL_H_ diff --git a/phonelibs/capnp-cpp/include/kj/time.h b/phonelibs/capnp-cpp/include/kj/time.h deleted file mode 100644 index 37d7b8a90e..0000000000 --- a/phonelibs/capnp-cpp/include/kj/time.h +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright (c) 2014 Google Inc. (contributed by Remy Blank ) -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_TIME_H_ -#define KJ_TIME_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "async.h" -#include "units.h" -#include - -namespace kj { -namespace _ { // private - -class NanosecondLabel; -class TimeLabel; -class DateLabel; - -} // namespace _ (private) - -using Duration = Quantity; -// A time value, in nanoseconds. - -constexpr Duration NANOSECONDS = unit(); -constexpr Duration MICROSECONDS = 1000 * NANOSECONDS; -constexpr Duration MILLISECONDS = 1000 * MICROSECONDS; -constexpr Duration SECONDS = 1000 * MILLISECONDS; -constexpr Duration MINUTES = 60 * SECONDS; -constexpr Duration HOURS = 60 * MINUTES; -constexpr Duration DAYS = 24 * HOURS; - -using TimePoint = Absolute; -// An absolute time measured by some particular instance of `Timer`. `Time`s from two different -// `Timer`s may be measured from different origins and so are not necessarily compatible. - -using Date = Absolute; -// A point in real-world time, measured relative to the Unix epoch (Jan 1, 1970 00:00:00 UTC). - -constexpr Date UNIX_EPOCH = origin(); -// The `Date` representing Jan 1, 1970 00:00:00 UTC. - -class Clock { - // Interface to read the current date and time. -public: - virtual Date now() = 0; -}; - -Clock& nullClock(); -// A clock which always returns UNIX_EPOCH as the current time. Useful when you don't care about -// time. - -class Timer { - // Interface to time and timer functionality. - // - // Each `Timer` may have a different origin, and some `Timer`s may in fact tick at a different - // rate than real time (e.g. a `Timer` could represent CPU time consumed by a thread). However, - // all `Timer`s are monotonic: time will never appear to move backwards, even if the calendar - // date as tracked by the system is manually modified. - -public: - virtual TimePoint now() = 0; - // Returns the current value of a clock that moves steadily forward, independent of any - // changes in the wall clock. The value is updated every time the event loop waits, - // and is constant in-between waits. - - virtual Promise atTime(TimePoint time) = 0; - // Returns a promise that returns as soon as now() >= time. - - virtual Promise afterDelay(Duration delay) = 0; - // Equivalent to atTime(now() + delay). - - template - Promise timeoutAt(TimePoint time, Promise&& promise) KJ_WARN_UNUSED_RESULT; - // Return a promise equivalent to `promise` but which throws an exception (and cancels the - // original promise) if it hasn't completed by `time`. The thrown exception is of type - // "OVERLOADED". - - template - Promise timeoutAfter(Duration delay, Promise&& promise) KJ_WARN_UNUSED_RESULT; - // Return a promise equivalent to `promise` but which throws an exception (and cancels the - // original promise) if it hasn't completed after `delay` from now. The thrown exception is of - // type "OVERLOADED". - -private: - static kj::Exception makeTimeoutException(); -}; - -class TimerImpl final: public Timer { - // Implementation of Timer that expects an external caller -- usually, the EventPort - // implementation -- to tell it when time has advanced. - -public: - TimerImpl(TimePoint startTime); - ~TimerImpl() noexcept(false); - - Maybe nextEvent(); - // Returns the time at which the next scheduled timer event will occur, or null if no timer - // events are scheduled. - - Maybe timeoutToNextEvent(TimePoint start, Duration unit, uint64_t max); - // Convenience method which computes a timeout value to pass to an event-waiting system call to - // cause it to time out when the next timer event occurs. - // - // `start` is the time at which the timeout starts counting. This is typically not the same as - // now() since some time may have passed since the last time advanceTo() was called. - // - // `unit` is the time unit in which the timeout is measured. This is often MILLISECONDS. Note - // that this method will fractional values *up*, to guarantee that the returned timeout waits - // until just *after* the time the event is scheduled. - // - // The timeout will be clamped to `max`. Use this to avoid an overflow if e.g. the OS wants a - // 32-bit value or a signed value. - // - // Returns nullptr if there are no future events. - - void advanceTo(TimePoint newTime); - // Set the time to `time` and fire any at() events that have been passed. - - // implements Timer ---------------------------------------------------------- - TimePoint now() override; - Promise atTime(TimePoint time) override; - Promise afterDelay(Duration delay) override; - -private: - struct Impl; - class TimerPromiseAdapter; - TimePoint time; - Own impl; -}; - -// ======================================================================================= -// inline implementation details - -template -Promise Timer::timeoutAt(TimePoint time, Promise&& promise) { - return promise.exclusiveJoin(atTime(time).then([]() -> kj::Promise { - return makeTimeoutException(); - })); -} - -template -Promise Timer::timeoutAfter(Duration delay, Promise&& promise) { - return promise.exclusiveJoin(afterDelay(delay).then([]() -> kj::Promise { - return makeTimeoutException(); - })); -} - -inline TimePoint TimerImpl::now() { return time; } - -} // namespace kj - -#endif // KJ_TIME_H_ diff --git a/phonelibs/capnp-cpp/include/kj/tuple.h b/phonelibs/capnp-cpp/include/kj/tuple.h deleted file mode 100644 index 2ea7276ec5..0000000000 --- a/phonelibs/capnp-cpp/include/kj/tuple.h +++ /dev/null @@ -1,364 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// This file defines a notion of tuples that is simpler that `std::tuple`. It works as follows: -// - `kj::Tuple is the type of a tuple of an A, a B, and a C. -// - `kj::tuple(a, b, c)` returns a tuple containing a, b, and c. If any of these are themselves -// tuples, they are flattened, so `tuple(a, tuple(b, c), d)` is equivalent to `tuple(a, b, c, d)`. -// - `kj::get(myTuple)` returns the element of `myTuple` at index n. -// - `kj::apply(func, ...)` calls func on the following arguments after first expanding any tuples -// in the argument list. So `kj::apply(foo, a, tuple(b, c), d)` would call `foo(a, b, c, d)`. -// -// Note that: -// - The type `Tuple` is a synonym for T. This is why `get` and `apply` are not members of the -// type. -// - It is illegal for an element of `Tuple` to itself be a tuple, as tuples are meant to be -// flattened. -// - It is illegal for an element of `Tuple` to be a reference, due to problems this would cause -// with type inference and `tuple()`. - -#ifndef KJ_TUPLE_H_ -#define KJ_TUPLE_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "common.h" - -namespace kj { -namespace _ { // private - -template -struct TypeByIndex_; -template -struct TypeByIndex_<0, First, Rest...> { - typedef First Type; -}; -template -struct TypeByIndex_ - : public TypeByIndex_ {}; -template -struct TypeByIndex_ { - static_assert(index != index, "Index out-of-range."); -}; -template -using TypeByIndex = typename TypeByIndex_::Type; -// Chose a particular type out of a list of types, by index. - -template -struct Indexes {}; -// Dummy helper type that just encapsulates a sequential list of indexes, so that we can match -// templates against them and unpack them with '...'. - -template -struct MakeIndexes_: public MakeIndexes_ {}; -template -struct MakeIndexes_<0, prefix...> { - typedef Indexes Type; -}; -template -using MakeIndexes = typename MakeIndexes_::Type; -// Equivalent to Indexes<0, 1, 2, ..., end>. - -template -class Tuple; -template -inline TypeByIndex& getImpl(Tuple& tuple); -template -inline TypeByIndex&& getImpl(Tuple&& tuple); -template -inline const TypeByIndex& getImpl(const Tuple& tuple); - -template -struct TupleElement { - // Encapsulates one element of a tuple. The actual tuple implementation multiply-inherits - // from a TupleElement for each element, which is more efficient than a recursive definition. - - T value; - TupleElement() = default; - constexpr inline TupleElement(const T& value): value(value) {} - constexpr inline TupleElement(T&& value): value(kj::mv(value)) {} -}; - -template -struct TupleElement { - // If tuples contained references, one of the following would have to be true: - // - `auto x = tuple(y, z)` would cause x to be a tuple of references to y and z, which is - // probably not what you expected. - // - `Tuple x = tuple(a, b)` would not work, because `tuple()` returned - // Tuple. - static_assert(sizeof(T*) == 0, "Sorry, tuples cannot contain references."); -}; - -template -struct TupleElement> { - static_assert(sizeof(Tuple*) == 0, - "Tuples cannot contain other tuples -- they should be flattened."); -}; - -template -struct TupleImpl; - -template -struct TupleImpl, Types...> - : public TupleElement... { - // Implementation of Tuple. The only reason we need this rather than rolling this into class - // Tuple (below) is so that we can get "indexes" as an unpackable list. - - static_assert(sizeof...(indexes) == sizeof...(Types), "Incorrect use of TupleImpl."); - - template - inline TupleImpl(Params&&... params) - : TupleElement(kj::fwd(params))... { - // Work around Clang 3.2 bug 16303 where this is not detected. (Unfortunately, Clang sometimes - // segfaults instead.) - static_assert(sizeof...(params) == sizeof...(indexes), - "Wrong number of parameters to Tuple constructor."); - } - - template - constexpr inline TupleImpl(Tuple&& other) - : TupleElement(kj::mv(getImpl(other)))... {} - template - constexpr inline TupleImpl(Tuple& other) - : TupleElement(getImpl(other))... {} - template - constexpr inline TupleImpl(const Tuple& other) - : TupleElement(getImpl(other))... {} -}; - -struct MakeTupleFunc; - -template -class Tuple { - // The actual Tuple class (used for tuples of size other than 1). - -public: - template - constexpr inline Tuple(Tuple&& other): impl(kj::mv(other)) {} - template - constexpr inline Tuple(Tuple& other): impl(other) {} - template - constexpr inline Tuple(const Tuple& other): impl(other) {} - -private: - template - constexpr Tuple(Params&&... params): impl(kj::fwd(params)...) {} - - TupleImpl, T...> impl; - - template - friend inline TypeByIndex& getImpl(Tuple& tuple); - template - friend inline TypeByIndex&& getImpl(Tuple&& tuple); - template - friend inline const TypeByIndex& getImpl(const Tuple& tuple); - friend struct MakeTupleFunc; -}; - -template <> -class Tuple<> { - // Simplified zero-member version of Tuple. In particular this is important to make sure that - // Tuple<>() is constexpr. -}; - -template -class Tuple; -// Single-element tuple should never be used. The public API should ensure this. - -template -inline TypeByIndex& getImpl(Tuple& tuple) { - // Get member of a Tuple by index, e.g. `get<2>(myTuple)`. - static_assert(index < sizeof...(T), "Tuple element index out-of-bounds."); - return implicitCast>&>(tuple.impl).value; -} -template -inline TypeByIndex&& getImpl(Tuple&& tuple) { - // Get member of a Tuple by index, e.g. `get<2>(myTuple)`. - static_assert(index < sizeof...(T), "Tuple element index out-of-bounds."); - return kj::mv(implicitCast>&>(tuple.impl).value); -} -template -inline const TypeByIndex& getImpl(const Tuple& tuple) { - // Get member of a Tuple by index, e.g. `get<2>(myTuple)`. - static_assert(index < sizeof...(T), "Tuple element index out-of-bounds."); - return implicitCast>&>(tuple.impl).value; -} -template -inline T&& getImpl(T&& value) { - // Get member of a Tuple by index, e.g. `getImpl<2>(myTuple)`. - - // Non-tuples are equivalent to one-element tuples. - static_assert(index == 0, "Tuple element index out-of-bounds."); - return kj::fwd(value); -} - - -template -struct ExpandAndApplyResult_; -// Template which computes the return type of applying Func to T... after flattening tuples. -// SoFar starts as Tuple<> and accumulates the flattened parameter types -- so after this template -// is recursively expanded, T... is empty and SoFar is a Tuple containing all the parameters. - -template -struct ExpandAndApplyResult_, First, Rest...> - : public ExpandAndApplyResult_, Rest...> {}; -template -struct ExpandAndApplyResult_, Tuple, Rest...> - : public ExpandAndApplyResult_, FirstTypes&&..., Rest...> {}; -template -struct ExpandAndApplyResult_, Tuple&, Rest...> - : public ExpandAndApplyResult_, FirstTypes&..., Rest...> {}; -template -struct ExpandAndApplyResult_, const Tuple&, Rest...> - : public ExpandAndApplyResult_, const FirstTypes&..., Rest...> {}; -template -struct ExpandAndApplyResult_> { - typedef decltype(instance()(instance()...)) Type; -}; -template -using ExpandAndApplyResult = typename ExpandAndApplyResult_, T...>::Type; -// Computes the expected return type of `expandAndApply()`. - -template -inline auto expandAndApply(Func&& func) -> ExpandAndApplyResult { - return func(); -} - -template -struct ExpandAndApplyFunc { - Func&& func; - First&& first; - ExpandAndApplyFunc(Func&& func, First&& first) - : func(kj::fwd(func)), first(kj::fwd(first)) {} - template - auto operator()(T&&... params) - -> decltype(this->func(kj::fwd(first), kj::fwd(params)...)) { - return this->func(kj::fwd(first), kj::fwd(params)...); - } -}; - -template -inline auto expandAndApply(Func&& func, First&& first, Rest&&... rest) - -> ExpandAndApplyResult { - - return expandAndApply( - ExpandAndApplyFunc(kj::fwd(func), kj::fwd(first)), - kj::fwd(rest)...); -} - -template -inline auto expandAndApply(Func&& func, Tuple&& first, Rest&&... rest) - -> ExpandAndApplyResult { - return expandAndApplyWithIndexes(MakeIndexes(), - kj::fwd(func), kj::mv(first), kj::fwd(rest)...); -} - -template -inline auto expandAndApply(Func&& func, Tuple& first, Rest&&... rest) - -> ExpandAndApplyResult { - return expandAndApplyWithIndexes(MakeIndexes(), - kj::fwd(func), first, kj::fwd(rest)...); -} - -template -inline auto expandAndApply(Func&& func, const Tuple& first, Rest&&... rest) - -> ExpandAndApplyResult { - return expandAndApplyWithIndexes(MakeIndexes(), - kj::fwd(func), first, kj::fwd(rest)...); -} - -template -inline auto expandAndApplyWithIndexes( - Indexes, Func&& func, Tuple&& first, Rest&&... rest) - -> ExpandAndApplyResult { - return expandAndApply(kj::fwd(func), kj::mv(getImpl(first))..., - kj::fwd(rest)...); -} - -template -inline auto expandAndApplyWithIndexes( - Indexes, Func&& func, const Tuple& first, Rest&&... rest) - -> ExpandAndApplyResult { - return expandAndApply(kj::fwd(func), getImpl(first)..., - kj::fwd(rest)...); -} - -struct MakeTupleFunc { - template - Tuple...> operator()(Params&&... params) { - return Tuple...>(kj::fwd(params)...); - } - template - Decay operator()(Param&& param) { - return kj::fwd(param); - } -}; - -} // namespace _ (private) - -template struct Tuple_ { typedef _::Tuple Type; }; -template struct Tuple_ { typedef T Type; }; - -template using Tuple = typename Tuple_::Type; -// Tuple type. `Tuple` (i.e. a single-element tuple) is a synonym for `T`. Tuples of size -// other than 1 expand to an internal type. Either way, you can construct a Tuple using -// `kj::tuple(...)`, get an element by index `i` using `kj::get(myTuple)`, and expand the tuple -// as arguments to a function using `kj::apply(func, myTuple)`. -// -// Tuples are always flat -- that is, no element of a Tuple is ever itself a Tuple. If you -// construct a tuple from other tuples, the elements are flattened and concatenated. - -template -inline auto tuple(Params&&... params) - -> decltype(_::expandAndApply(_::MakeTupleFunc(), kj::fwd(params)...)) { - // Construct a new tuple from the given values. Any tuples in the argument list will be - // flattened into the result. - return _::expandAndApply(_::MakeTupleFunc(), kj::fwd(params)...); -} - -template -inline auto get(Tuple&& tuple) -> decltype(_::getImpl(kj::fwd(tuple))) { - // Unpack and return the tuple element at the given index. The index is specified as a template - // parameter, e.g. `kj::get<3>(myTuple)`. - return _::getImpl(kj::fwd(tuple)); -} - -template -inline auto apply(Func&& func, Params&&... params) - -> decltype(_::expandAndApply(kj::fwd(func), kj::fwd(params)...)) { - // Apply a function to some arguments, expanding tuples into separate arguments. - return _::expandAndApply(kj::fwd(func), kj::fwd(params)...); -} - -template struct TupleSize_ { static constexpr size_t size = 1; }; -template struct TupleSize_<_::Tuple> { - static constexpr size_t size = sizeof...(T); -}; - -template -constexpr size_t tupleSize() { return TupleSize_::size; } -// Returns size of the tuple T. - -} // namespace kj - -#endif // KJ_TUPLE_H_ diff --git a/phonelibs/capnp-cpp/include/kj/units.h b/phonelibs/capnp-cpp/include/kj/units.h deleted file mode 100644 index 8bba40338b..0000000000 --- a/phonelibs/capnp-cpp/include/kj/units.h +++ /dev/null @@ -1,1172 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// This file contains types which are intended to help detect incorrect usage at compile -// time, but should then be optimized down to basic primitives (usually, integers) by the -// compiler. - -#ifndef KJ_UNITS_H_ -#define KJ_UNITS_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "common.h" -#include - -namespace kj { - -// ======================================================================================= -// IDs - -template -struct Id { - // A type-safe numeric ID. `UnderlyingType` is the underlying integer representation. `Label` - // distinguishes this Id from other Id types. Sample usage: - // - // class Foo; - // typedef Id FooId; - // - // class Bar; - // typedef Id BarId; - // - // You can now use the FooId and BarId types without any possibility of accidentally using a - // FooId when you really wanted a BarId or vice-versa. - - UnderlyingType value; - - inline constexpr Id(): value(0) {} - inline constexpr explicit Id(int value): value(value) {} - - inline constexpr bool operator==(const Id& other) const { return value == other.value; } - inline constexpr bool operator!=(const Id& other) const { return value != other.value; } - inline constexpr bool operator<=(const Id& other) const { return value <= other.value; } - inline constexpr bool operator>=(const Id& other) const { return value >= other.value; } - inline constexpr bool operator< (const Id& other) const { return value < other.value; } - inline constexpr bool operator> (const Id& other) const { return value > other.value; } -}; - -// ======================================================================================= -// Quantity and UnitRatio -- implement unit analysis via the type system - -struct Unsafe_ {}; -constexpr Unsafe_ unsafe = Unsafe_(); -// Use as a parameter to constructors that are unsafe to indicate that you really do mean it. - -template -class Bounded; -template -class BoundedConst; - -template constexpr bool isIntegral() { return false; } -template <> constexpr bool isIntegral() { return true; } -template <> constexpr bool isIntegral() { return true; } -template <> constexpr bool isIntegral() { return true; } -template <> constexpr bool isIntegral() { return true; } -template <> constexpr bool isIntegral() { return true; } -template <> constexpr bool isIntegral() { return true; } -template <> constexpr bool isIntegral() { return true; } -template <> constexpr bool isIntegral() { return true; } -template <> constexpr bool isIntegral() { return true; } -template <> constexpr bool isIntegral() { return true; } -template <> constexpr bool isIntegral() { return true; } - -template -struct IsIntegralOrBounded_ { static constexpr bool value = isIntegral(); }; -template -struct IsIntegralOrBounded_> { static constexpr bool value = true; }; -template -struct IsIntegralOrBounded_> { static constexpr bool value = true; }; - -template -inline constexpr bool isIntegralOrBounded() { return IsIntegralOrBounded_::value; } - -template -class UnitRatio { - // A multiplier used to convert Quantities of one unit to Quantities of another unit. See - // Quantity, below. - // - // Construct this type by dividing one Quantity by another of a different unit. Use this type - // by multiplying it by a Quantity, or dividing a Quantity by it. - - static_assert(isIntegralOrBounded(), - "Underlying type for UnitRatio must be integer."); - -public: - inline UnitRatio() {} - - constexpr UnitRatio(Number unit1PerUnit2, decltype(unsafe)): unit1PerUnit2(unit1PerUnit2) {} - // This constructor was intended to be private, but GCC complains about it being private in a - // bunch of places that don't appear to even call it, so I made it public. Oh well. - - template - inline constexpr UnitRatio(const UnitRatio& other) - : unit1PerUnit2(other.unit1PerUnit2) {} - - template - inline constexpr UnitRatio - operator+(UnitRatio other) const { - return UnitRatio( - unit1PerUnit2 + other.unit1PerUnit2, unsafe); - } - template - inline constexpr UnitRatio - operator-(UnitRatio other) const { - return UnitRatio( - unit1PerUnit2 - other.unit1PerUnit2, unsafe); - } - - template - inline constexpr UnitRatio - operator*(UnitRatio other) const { - // U1 / U2 * U3 / U1 = U3 / U2 - return UnitRatio( - unit1PerUnit2 * other.unit1PerUnit2, unsafe); - } - template - inline constexpr UnitRatio - operator*(UnitRatio other) const { - // U1 / U2 * U2 / U3 = U1 / U3 - return UnitRatio( - unit1PerUnit2 * other.unit1PerUnit2, unsafe); - } - - template - inline constexpr UnitRatio - operator/(UnitRatio other) const { - // (U1 / U2) / (U1 / U3) = U3 / U2 - return UnitRatio( - unit1PerUnit2 / other.unit1PerUnit2, unsafe); - } - template - inline constexpr UnitRatio - operator/(UnitRatio other) const { - // (U1 / U2) / (U3 / U2) = U1 / U3 - return UnitRatio( - unit1PerUnit2 / other.unit1PerUnit2, unsafe); - } - - template - inline decltype(Number() / OtherNumber()) - operator/(UnitRatio other) const { - return unit1PerUnit2 / other.unit1PerUnit2; - } - - inline bool operator==(UnitRatio other) const { return unit1PerUnit2 == other.unit1PerUnit2; } - inline bool operator!=(UnitRatio other) const { return unit1PerUnit2 != other.unit1PerUnit2; } - -private: - Number unit1PerUnit2; - - template - friend class Quantity; - template - friend class UnitRatio; - - template - friend inline constexpr UnitRatio - operator*(N1, UnitRatio); -}; - -template () && isIntegralOrBounded()>> -inline constexpr UnitRatio - operator*(N1 n, UnitRatio r) { - return UnitRatio(n * r.unit1PerUnit2, unsafe); -} - -template -class Quantity { - // A type-safe numeric quantity, specified in terms of some unit. Two Quantities cannot be used - // in arithmetic unless they use the same unit. The `Unit` type parameter is only used to prevent - // accidental mixing of units; this type is never instantiated and can very well be incomplete. - // `Number` is the underlying primitive numeric type. - // - // Quantities support most basic arithmetic operators, intelligently handling units, and - // automatically casting the underlying type in the same way that the compiler would. - // - // To convert a primitive number to a Quantity, multiply it by unit>(). - // To convert a Quantity to a primitive number, divide it by unit>(). - // To convert a Quantity of one unit to another unit, multiply or divide by a UnitRatio. - // - // The Quantity class is not well-suited to hardcore physics as it does not allow multiplying - // one quantity by another. For example, multiplying meters by meters won't get you square - // meters; it will get you a compiler error. It would be interesting to see if template - // metaprogramming could properly deal with such things but this isn't needed for the present - // use case. - // - // Sample usage: - // - // class SecondsLabel; - // typedef Quantity Seconds; - // constexpr Seconds SECONDS = unit(); - // - // class MinutesLabel; - // typedef Quantity Minutes; - // constexpr Minutes MINUTES = unit(); - // - // constexpr UnitRatio SECONDS_PER_MINUTE = - // 60 * SECONDS / MINUTES; - // - // void waitFor(Seconds seconds) { - // sleep(seconds / SECONDS); - // } - // void waitFor(Minutes minutes) { - // waitFor(minutes * SECONDS_PER_MINUTE); - // } - // - // void waitThreeMinutes() { - // waitFor(3 * MINUTES); - // } - - static_assert(isIntegralOrBounded(), - "Underlying type for Quantity must be integer."); - -public: - inline constexpr Quantity() = default; - - inline constexpr Quantity(MaxValue_): value(maxValue) {} - inline constexpr Quantity(MinValue_): value(minValue) {} - // Allow initialization from maxValue and minValue. - // TODO(msvc): decltype(maxValue) and decltype(minValue) deduce unknown-type for these function - // parameters, causing the compiler to complain of a duplicate constructor definition, so we - // specify MaxValue_ and MinValue_ types explicitly. - - inline constexpr Quantity(Number value, decltype(unsafe)): value(value) {} - // This constructor was intended to be private, but GCC complains about it being private in a - // bunch of places that don't appear to even call it, so I made it public. Oh well. - - template - inline constexpr Quantity(const Quantity& other) - : value(other.value) {} - - template - inline Quantity& operator=(const Quantity& other) { - value = other.value; - return *this; - } - - template - inline constexpr Quantity - operator+(const Quantity& other) const { - return Quantity(value + other.value, unsafe); - } - template - inline constexpr Quantity - operator-(const Quantity& other) const { - return Quantity(value - other.value, unsafe); - } - template ()>> - inline constexpr Quantity - operator*(OtherNumber other) const { - return Quantity(value * other, unsafe); - } - template ()>> - inline constexpr Quantity - operator/(OtherNumber other) const { - return Quantity(value / other, unsafe); - } - template - inline constexpr decltype(Number() / OtherNumber()) - operator/(const Quantity& other) const { - return value / other.value; - } - template - inline constexpr Quantity - operator%(const Quantity& other) const { - return Quantity(value % other.value, unsafe); - } - - template - inline constexpr Quantity - operator*(UnitRatio ratio) const { - return Quantity( - value * ratio.unit1PerUnit2, unsafe); - } - template - inline constexpr Quantity - operator/(UnitRatio ratio) const { - return Quantity( - value / ratio.unit1PerUnit2, unsafe); - } - template - inline constexpr Quantity - operator%(UnitRatio ratio) const { - return Quantity( - value % ratio.unit1PerUnit2, unsafe); - } - template - inline constexpr UnitRatio - operator/(Quantity other) const { - return UnitRatio( - value / other.value, unsafe); - } - - template - inline constexpr bool operator==(const Quantity& other) const { - return value == other.value; - } - template - inline constexpr bool operator!=(const Quantity& other) const { - return value != other.value; - } - template - inline constexpr bool operator<=(const Quantity& other) const { - return value <= other.value; - } - template - inline constexpr bool operator>=(const Quantity& other) const { - return value >= other.value; - } - template - inline constexpr bool operator<(const Quantity& other) const { - return value < other.value; - } - template - inline constexpr bool operator>(const Quantity& other) const { - return value > other.value; - } - - template - inline Quantity& operator+=(const Quantity& other) { - value += other.value; - return *this; - } - template - inline Quantity& operator-=(const Quantity& other) { - value -= other.value; - return *this; - } - template - inline Quantity& operator*=(OtherNumber other) { - value *= other; - return *this; - } - template - inline Quantity& operator/=(OtherNumber other) { - value /= other.value; - return *this; - } - -private: - Number value; - - template - friend class Quantity; - - template - friend inline constexpr auto operator*(Number1 a, Quantity b) - -> Quantity; -}; - -template struct Unit_ { - static inline constexpr T get() { return T(1); } -}; -template -struct Unit_> { - static inline constexpr Quantity::get()), U> get() { - return Quantity::get()), U>(Unit_::get(), unsafe); - } -}; - -template -inline constexpr auto unit() -> decltype(Unit_::get()) { return Unit_::get(); } -// unit>() returns a Quantity of value 1. It also, intentionally, works on basic -// numeric types. - -template -inline constexpr auto operator*(Number1 a, Quantity b) - -> Quantity { - return Quantity(a * b.value, unsafe); -} - -template -inline constexpr auto operator*(UnitRatio ratio, - Quantity measure) - -> decltype(measure * ratio) { - return measure * ratio; -} - -// ======================================================================================= -// Absolute measures - -template -class Absolute { - // Wraps some other value -- typically a Quantity -- but represents a value measured based on - // some absolute origin. For example, if `Duration` is a type representing a time duration, - // Absolute might be a calendar date. - // - // Since Absolute represents measurements relative to some arbitrary origin, the only sensible - // arithmetic to perform on them is addition and subtraction. - - // TODO(someday): Do the same automatic expansion of integer width that Quantity does? Doesn't - // matter for our time use case, where we always use 64-bit anyway. Note that fixing this - // would implicitly allow things like multiplying an Absolute by a UnitRatio to change its - // units, which is actually totally logical and kind of neat. - -public: - inline constexpr Absolute operator+(const T& other) const { return Absolute(value + other); } - inline constexpr Absolute operator-(const T& other) const { return Absolute(value - other); } - inline constexpr T operator-(const Absolute& other) const { return value - other.value; } - - inline Absolute& operator+=(const T& other) { value += other; return *this; } - inline Absolute& operator-=(const T& other) { value -= other; return *this; } - - inline constexpr bool operator==(const Absolute& other) const { return value == other.value; } - inline constexpr bool operator!=(const Absolute& other) const { return value != other.value; } - inline constexpr bool operator<=(const Absolute& other) const { return value <= other.value; } - inline constexpr bool operator>=(const Absolute& other) const { return value >= other.value; } - inline constexpr bool operator< (const Absolute& other) const { return value < other.value; } - inline constexpr bool operator> (const Absolute& other) const { return value > other.value; } - -private: - T value; - - explicit constexpr Absolute(T value): value(value) {} - - template - friend inline constexpr U origin(); -}; - -template -inline constexpr Absolute operator+(const T& a, const Absolute& b) { - return b + a; -} - -template struct UnitOf_ { typedef T Type; }; -template struct UnitOf_> { typedef T Type; }; -template -using UnitOf = typename UnitOf_::Type; -// UnitOf> is T. UnitOf is AnythingElse. - -template -inline constexpr T origin() { return T(0 * unit>()); } -// origin>() returns an Absolute of value 0. It also, intentionally, works on basic -// numeric types. - -// ======================================================================================= -// Overflow avoidance - -template -struct BitCount_ { - static constexpr uint value = BitCount_<(n >> 1), accum + 1>::value; -}; -template -struct BitCount_<0, accum> { - static constexpr uint value = accum; -}; - -template -inline constexpr uint bitCount() { return BitCount_::value; } -// Number of bits required to represent the number `n`. - -template struct AtLeastUInt_ { - static_assert(bitCountBitCount < 7, "don't know how to represent integers over 64 bits"); -}; -template <> struct AtLeastUInt_<0> { typedef uint8_t Type; }; -template <> struct AtLeastUInt_<1> { typedef uint8_t Type; }; -template <> struct AtLeastUInt_<2> { typedef uint8_t Type; }; -template <> struct AtLeastUInt_<3> { typedef uint8_t Type; }; -template <> struct AtLeastUInt_<4> { typedef uint16_t Type; }; -template <> struct AtLeastUInt_<5> { typedef uint32_t Type; }; -template <> struct AtLeastUInt_<6> { typedef uint64_t Type; }; - -template -using AtLeastUInt = typename AtLeastUInt_()>::Type; -// AtLeastUInt is an unsigned integer of at least n bits. E.g. AtLeastUInt<12> is uint16_t. - -// ------------------------------------------------------------------- - -template -class BoundedConst { - // A constant integer value on which we can do bit size analysis. - -public: - BoundedConst() = default; - - inline constexpr uint unwrap() const { return value; } - -#define OP(op, check) \ - template \ - inline constexpr BoundedConst<(value op other)> \ - operator op(BoundedConst) const { \ - static_assert(check, "overflow in BoundedConst arithmetic"); \ - return BoundedConst<(value op other)>(); \ - } -#define COMPARE_OP(op) \ - template \ - inline constexpr bool operator op(BoundedConst) const { \ - return value op other; \ - } - - OP(+, value + other >= value) - OP(-, value - other <= value) - OP(*, value * other / other == value) - OP(/, true) // div by zero already errors out; no other division ever overflows - OP(%, true) // mod by zero already errors out; no other modulus ever overflows - OP(<<, value << other >= value) - OP(>>, true) // right shift can't overflow - OP(&, true) // bitwise ops can't overflow - OP(|, true) // bitwise ops can't overflow - - COMPARE_OP(==) - COMPARE_OP(!=) - COMPARE_OP(< ) - COMPARE_OP(> ) - COMPARE_OP(<=) - COMPARE_OP(>=) -#undef OP -#undef COMPARE_OP -}; - -template -struct Unit_> { - static inline constexpr BoundedConst<1> get() { return BoundedConst<1>(); } -}; - -template -struct Unit_> { - static inline constexpr BoundedConst<1> get() { return BoundedConst<1>(); } -}; - -template -inline constexpr BoundedConst bounded() { - return BoundedConst(); -} - -template -static constexpr uint64_t boundedAdd() { - static_assert(a + b >= a, "possible overflow detected"); - return a + b; -} -template -static constexpr uint64_t boundedSub() { - static_assert(a - b <= a, "possible underflow detected"); - return a - b; -} -template -static constexpr uint64_t boundedMul() { - static_assert(a * b / b == a, "possible overflow detected"); - return a * b; -} -template -static constexpr uint64_t boundedLShift() { - static_assert(a << b >= a, "possible overflow detected"); - return a << b; -} - -template -inline constexpr BoundedConst min(BoundedConst, BoundedConst) { - return bounded(); -} -template -inline constexpr BoundedConst max(BoundedConst, BoundedConst) { - return bounded(); -} -// We need to override min() and max() between constants because the ternary operator in the -// default implementation would complain. - -// ------------------------------------------------------------------- - -template -class Bounded { -public: - static_assert(maxN <= T(kj::maxValue), "possible overflow detected"); - - Bounded() = default; - - Bounded(const Bounded& other) = default; - template ()>> - inline constexpr Bounded(OtherInt value): value(value) { - static_assert(OtherInt(maxValue) <= maxN, "possible overflow detected"); - } - template - inline constexpr Bounded(const Bounded& other) - : value(other.value) { - static_assert(otherMax <= maxN, "possible overflow detected"); - } - template - inline constexpr Bounded(BoundedConst) - : value(otherValue) { - static_assert(otherValue <= maxN, "overflow detected"); - } - - Bounded& operator=(const Bounded& other) = default; - template ()>> - Bounded& operator=(OtherInt other) { - static_assert(OtherInt(maxValue) <= maxN, "possible overflow detected"); - value = other; - return *this; - } - template - inline Bounded& operator=(const Bounded& other) { - static_assert(otherMax <= maxN, "possible overflow detected"); - value = other.value; - return *this; - } - template - inline Bounded& operator=(BoundedConst) { - static_assert(otherValue <= maxN, "overflow detected"); - value = otherValue; - return *this; - } - - inline constexpr T unwrap() const { return value; } - -#define OP(op, newMax) \ - template \ - inline constexpr Bounded \ - operator op(const Bounded& other) const { \ - return Bounded(value op other.value, unsafe); \ - } -#define COMPARE_OP(op) \ - template \ - inline constexpr bool operator op(const Bounded& other) const { \ - return value op other.value; \ - } - - OP(+, (boundedAdd())) - OP(*, (boundedMul())) - OP(/, maxN) - OP(%, otherMax - 1) - - // operator- is intentionally omitted because we mostly use this with unsigned types, and - // subtraction requires proof that subtrahend is not greater than the minuend. - - COMPARE_OP(==) - COMPARE_OP(!=) - COMPARE_OP(< ) - COMPARE_OP(> ) - COMPARE_OP(<=) - COMPARE_OP(>=) - -#undef OP -#undef COMPARE_OP - - template - inline Bounded assertMax(ErrorFunc&& func) const { - // Assert that the number is no more than `newMax`. Otherwise, call `func`. - static_assert(newMax < maxN, "this bounded size assertion is redundant"); - if (KJ_UNLIKELY(value > newMax)) func(); - return Bounded(value, unsafe); - } - - template - inline Bounded subtractChecked( - const Bounded& other, ErrorFunc&& func) const { - // Subtract a number, calling func() if the result would underflow. - if (KJ_UNLIKELY(value < other.value)) func(); - return Bounded(value - other.value, unsafe); - } - - template - inline Bounded subtractChecked( - BoundedConst, ErrorFunc&& func) const { - // Subtract a number, calling func() if the result would underflow. - static_assert(otherValue <= maxN, "underflow detected"); - if (KJ_UNLIKELY(value < otherValue)) func(); - return Bounded(value - otherValue, unsafe); - } - - template - inline Maybe> trySubtract( - const Bounded& other) const { - // Subtract a number, calling func() if the result would underflow. - if (value < other.value) { - return nullptr; - } else { - return Bounded(value - other.value, unsafe); - } - } - - template - inline Maybe> trySubtract(BoundedConst) const { - // Subtract a number, calling func() if the result would underflow. - if (value < otherValue) { - return nullptr; - } else { - return Bounded(value - otherValue, unsafe); - } - } - - inline constexpr Bounded(T value, decltype(unsafe)): value(value) {} - template - inline constexpr Bounded(Bounded value, decltype(unsafe)) - : value(value.value) {} - // Mainly for internal use. - // - // Only use these as a last resort, with ample commentary on why you think it's safe. - -private: - T value; - - template - friend class Bounded; -}; - -template -inline constexpr Bounded bounded(Number value) { - return Bounded(value, unsafe); -} - -inline constexpr Bounded<1, uint8_t> bounded(bool value) { - return Bounded<1, uint8_t>(value, unsafe); -} - -template -inline constexpr Bounded(), Number> assumeBits(Number value) { - return Bounded(), Number>(value, unsafe); -} - -template -inline constexpr Bounded(), T> assumeBits(Bounded value) { - return Bounded(), T>(value, unsafe); -} - -template -inline constexpr auto assumeBits(Quantity value) - -> Quantity(value / unit>())), Unit> { - return Quantity(value / unit>())), Unit>( - assumeBits(value / unit>()), unsafe); -} - -template -inline constexpr Bounded assumeMax(Number value) { - return Bounded(value, unsafe); -} - -template -inline constexpr Bounded assumeMax(Bounded value) { - return Bounded(value, unsafe); -} - -template -inline constexpr auto assumeMax(Quantity value) - -> Quantity(value / unit>())), Unit> { - return Quantity(value / unit>())), Unit>( - assumeMax(value / unit>()), unsafe); -} - -template -inline constexpr Bounded assumeMax(BoundedConst, Number value) { - return assumeMax(value); -} - -template -inline constexpr Bounded assumeMax(BoundedConst, Bounded value) { - return assumeMax(value); -} - -template -inline constexpr auto assumeMax(Quantity, Unit>, Quantity value) - -> decltype(assumeMax(value)) { - return assumeMax(value); -} - -template -inline Bounded assertMax(Bounded value, ErrorFunc&& errorFunc) { - // Assert that the bounded value is less than or equal to the given maximum, calling errorFunc() - // if not. - static_assert(newMax < maxN, "this bounded size assertion is redundant"); - return value.template assertMax(kj::fwd(errorFunc)); -} - -template -inline Quantity, Unit> assertMax( - Quantity, Unit> value, ErrorFunc&& errorFunc) { - // Assert that the bounded value is less than or equal to the given maximum, calling errorFunc() - // if not. - static_assert(newMax < maxN, "this bounded size assertion is redundant"); - return (value / unit()).template assertMax( - kj::fwd(errorFunc)) * unit(); -} - -template -inline Bounded assertMax( - BoundedConst, Bounded value, ErrorFunc&& errorFunc) { - return assertMax(value, kj::mv(errorFunc)); -} - -template -inline Quantity, Unit> assertMax( - Quantity, Unit>, - Quantity, Unit> value, ErrorFunc&& errorFunc) { - return assertMax(value, kj::mv(errorFunc)); -} - -template -inline Bounded(), T> assertMaxBits( - Bounded value, ErrorFunc&& errorFunc = ErrorFunc()) { - // Assert that the bounded value requires no more than the given number of bits, calling - // errorFunc() if not. - return assertMax()>(value, kj::fwd(errorFunc)); -} - -template -inline Quantity(), T>, Unit> assertMaxBits( - Quantity, Unit> value, ErrorFunc&& errorFunc = ErrorFunc()) { - // Assert that the bounded value requires no more than the given number of bits, calling - // errorFunc() if not. - return assertMax()>(value, kj::fwd(errorFunc)); -} - -template -inline constexpr Bounded upgradeBound(Bounded value) { - return value; -} - -template -inline constexpr Quantity, Unit> upgradeBound( - Quantity, Unit> value) { - return value; -} - -template -inline auto subtractChecked(Bounded value, Other other, ErrorFunc&& errorFunc) - -> decltype(value.subtractChecked(other, kj::fwd(errorFunc))) { - return value.subtractChecked(other, kj::fwd(errorFunc)); -} - -template -inline auto subtractChecked(Quantity value, Quantity other, ErrorFunc&& errorFunc) - -> Quantity(errorFunc))), Unit> { - return subtractChecked(value / unit>(), - other / unit>(), - kj::fwd(errorFunc)) - * unit>(); -} - -template -inline auto trySubtract(Bounded value, Other other) - -> decltype(value.trySubtract(other)) { - return value.trySubtract(other); -} - -template -inline auto trySubtract(Quantity value, Quantity other) - -> Maybe> { - return trySubtract(value / unit>(), - other / unit>()) - .map([](decltype(subtractChecked(T(), U(), int())) x) { - return x * unit>(); - }); -} - -template -inline constexpr Bounded> -min(Bounded a, Bounded b) { - return Bounded>(kj::min(a.unwrap(), b.unwrap()), unsafe); -} -template -inline constexpr Bounded> -max(Bounded a, Bounded b) { - return Bounded>(kj::max(a.unwrap(), b.unwrap()), unsafe); -} -// We need to override min() and max() because: -// 1) WiderType<> might not choose the correct bounds. -// 2) One of the two sides of the ternary operator in the default implementation would fail to -// typecheck even though it is OK in practice. - -// ------------------------------------------------------------------- -// Operators between Bounded and BoundedConst - -#define OP(op, newMax) \ -template \ -inline constexpr Bounded<(newMax), decltype(T() op uint())> operator op( \ - Bounded value, BoundedConst) { \ - return Bounded<(newMax), decltype(T() op uint())>(value.unwrap() op cvalue, unsafe); \ -} - -#define REVERSE_OP(op, newMax) \ -template \ -inline constexpr Bounded<(newMax), decltype(uint() op T())> operator op( \ - BoundedConst, Bounded value) { \ - return Bounded<(newMax), decltype(uint() op T())>(cvalue op value.unwrap(), unsafe); \ -} - -#define COMPARE_OP(op) \ -template \ -inline constexpr bool operator op(Bounded value, BoundedConst) { \ - return value.unwrap() op cvalue; \ -} \ -template \ -inline constexpr bool operator op(BoundedConst, Bounded value) { \ - return cvalue op value.unwrap(); \ -} - -OP(+, (boundedAdd())) -REVERSE_OP(+, (boundedAdd())) - -OP(*, (boundedMul())) -REVERSE_OP(*, (boundedAdd())) - -OP(/, maxN / cvalue) -REVERSE_OP(/, cvalue) // denominator could be 1 - -OP(%, cvalue - 1) -REVERSE_OP(%, maxN - 1) - -OP(<<, (boundedLShift())) -REVERSE_OP(<<, (boundedLShift())) - -OP(>>, maxN >> cvalue) -REVERSE_OP(>>, cvalue >> maxN) - -OP(&, maxValueForBits()>() & cvalue) -REVERSE_OP(&, maxValueForBits()>() & cvalue) - -OP(|, maxN | cvalue) -REVERSE_OP(|, maxN | cvalue) - -COMPARE_OP(==) -COMPARE_OP(!=) -COMPARE_OP(< ) -COMPARE_OP(> ) -COMPARE_OP(<=) -COMPARE_OP(>=) - -#undef OP -#undef REVERSE_OP -#undef COMPARE_OP - -template -inline constexpr Bounded - operator-(BoundedConst, Bounded value) { - // We allow subtraction of a variable from a constant only if the constant is greater than or - // equal to the maximum possible value of the variable. Since the variable could be zero, the - // result can be as large as the constant. - // - // We do not allow subtraction of a constant from a variable because there's never a guarantee it - // won't underflow (unless the constant is zero, which is silly). - static_assert(cvalue >= maxN, "possible underflow detected"); - return Bounded(cvalue - value.unwrap(), unsafe); -} - -template -inline constexpr Bounded min(Bounded a, BoundedConst) { - return Bounded(kj::min(b, a.unwrap()), unsafe); -} -template -inline constexpr Bounded min(BoundedConst, Bounded a) { - return Bounded(kj::min(a.unwrap(), b), unsafe); -} -template -inline constexpr Bounded max(Bounded a, BoundedConst) { - return Bounded(kj::max(b, a.unwrap()), unsafe); -} -template -inline constexpr Bounded max(BoundedConst, Bounded a) { - return Bounded(kj::max(a.unwrap(), b), unsafe); -} -// We need to override min() between a Bounded and a constant since: -// 1) WiderType<> might choose BoundedConst over a 1-byte Bounded, which is wrong. -// 2) To clamp the bounds of the output type. -// 3) Same ternary operator typechecking issues. - -// ------------------------------------------------------------------- - -template -class SafeUnwrapper { -public: - inline explicit constexpr SafeUnwrapper(Bounded value): value(value.unwrap()) {} - - template ()>> - inline constexpr operator U() const { - static_assert(maxN <= U(maxValue), "possible truncation detected"); - return value; - } - - inline constexpr operator bool() const { - static_assert(maxN <= 1, "possible truncation detected"); - return value; - } - -private: - T value; -}; - -template -inline constexpr SafeUnwrapper unbound(Bounded bounded) { - // Unwraps the bounded value, returning a value that can be implicitly cast to any integer type. - // If this implicit cast could truncate, a compile-time error will be raised. - return SafeUnwrapper(bounded); -} - -template -class SafeConstUnwrapper { -public: - template ()>> - inline constexpr operator T() const { - static_assert(value <= T(maxValue), "this operation will truncate"); - return value; - } - - inline constexpr operator bool() const { - static_assert(value <= 1, "this operation will truncate"); - return value; - } -}; - -template -inline constexpr SafeConstUnwrapper unbound(BoundedConst) { - return SafeConstUnwrapper(); -} - -template -inline constexpr T unboundAs(U value) { - return unbound(value); -} - -template -inline constexpr T unboundMax(Bounded value) { - // Explicitly ungaurd expecting a value that is at most `maxN`. - static_assert(maxN <= requestedMax, "possible overflow detected"); - return value.unwrap(); -} - -template -inline constexpr uint unboundMax(BoundedConst) { - // Explicitly ungaurd expecting a value that is at most `maxN`. - static_assert(value <= requestedMax, "overflow detected"); - return value; -} - -template -inline constexpr auto unboundMaxBits(T value) -> - decltype(unboundMax()>(value)) { - // Explicitly ungaurd expecting a value that fits into `bits` bits. - return unboundMax()>(value); -} - -#define OP(op) \ -template \ -inline constexpr auto operator op(T a, SafeUnwrapper b) -> decltype(a op (T)b) { \ - return a op (AtLeastUInt)b; \ -} \ -template \ -inline constexpr auto operator op(SafeUnwrapper b, T a) -> decltype((T)b op a) { \ - return (AtLeastUInt)b op a; \ -} \ -template \ -inline constexpr auto operator op(T a, SafeConstUnwrapper b) -> decltype(a op (T)b) { \ - return a op (AtLeastUInt)b; \ -} \ -template \ -inline constexpr auto operator op(SafeConstUnwrapper b, T a) -> decltype((T)b op a) { \ - return (AtLeastUInt)b op a; \ -} - -OP(+) -OP(-) -OP(*) -OP(/) -OP(%) -OP(<<) -OP(>>) -OP(&) -OP(|) -OP(==) -OP(!=) -OP(<=) -OP(>=) -OP(<) -OP(>) - -#undef OP - -// ------------------------------------------------------------------- - -template -class Range> { -public: - inline constexpr Range(Bounded begin, Bounded end) - : inner(unbound(begin), unbound(end)) {} - inline explicit constexpr Range(Bounded end) - : inner(unbound(end)) {} - - class Iterator { - public: - Iterator() = default; - inline explicit Iterator(typename Range::Iterator inner): inner(inner) {} - - inline Bounded operator* () const { return Bounded(*inner, unsafe); } - inline Iterator& operator++() { ++inner; return *this; } - - inline bool operator==(const Iterator& other) const { return inner == other.inner; } - inline bool operator!=(const Iterator& other) const { return inner != other.inner; } - - private: - typename Range::Iterator inner; - }; - - inline Iterator begin() const { return Iterator(inner.begin()); } - inline Iterator end() const { return Iterator(inner.end()); } - -private: - Range inner; -}; - -template -class Range> { -public: - inline constexpr Range(Quantity begin, Quantity end) - : inner(begin / unit>(), end / unit>()) {} - inline explicit constexpr Range(Quantity end) - : inner(end / unit>()) {} - - class Iterator { - public: - Iterator() = default; - inline explicit Iterator(typename Range::Iterator inner): inner(inner) {} - - inline Quantity operator* () const { return *inner * unit>(); } - inline Iterator& operator++() { ++inner; return *this; } - - inline bool operator==(const Iterator& other) const { return inner == other.inner; } - inline bool operator!=(const Iterator& other) const { return inner != other.inner; } - - private: - typename Range::Iterator inner; - }; - - inline Iterator begin() const { return Iterator(inner.begin()); } - inline Iterator end() const { return Iterator(inner.end()); } - -private: - Range inner; -}; - -template -inline constexpr Range> zeroTo(BoundedConst end) { - return Range>(end); -} - -template -inline constexpr Range, Unit>> - zeroTo(Quantity, Unit> end) { - return Range, Unit>>(end); -} - -} // namespace kj - -#endif // KJ_UNITS_H_ diff --git a/phonelibs/capnp-cpp/include/kj/vector.h b/phonelibs/capnp-cpp/include/kj/vector.h deleted file mode 100644 index 44613f3331..0000000000 --- a/phonelibs/capnp-cpp/include/kj/vector.h +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_VECTOR_H_ -#define KJ_VECTOR_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#include "array.h" - -namespace kj { - -template -class Vector { - // Similar to std::vector, but based on KJ framework. - // - // This implementation always uses move constructors when growing the backing array. If the - // move constructor throws, the Vector is left in an inconsistent state. This is acceptable - // under KJ exception theory which assumes that exceptions leave things in inconsistent states. - - // TODO(someday): Allow specifying a custom allocator. - -public: - inline Vector() = default; - inline explicit Vector(size_t capacity): builder(heapArrayBuilder(capacity)) {} - - inline operator ArrayPtr() { return builder; } - inline operator ArrayPtr() const { return builder; } - inline ArrayPtr asPtr() { return builder.asPtr(); } - inline ArrayPtr asPtr() const { return builder.asPtr(); } - - inline size_t size() const { return builder.size(); } - inline bool empty() const { return size() == 0; } - inline size_t capacity() const { return builder.capacity(); } - inline T& operator[](size_t index) const { return builder[index]; } - - inline const T* begin() const { return builder.begin(); } - inline const T* end() const { return builder.end(); } - inline const T& front() const { return builder.front(); } - inline const T& back() const { return builder.back(); } - inline T* begin() { return builder.begin(); } - inline T* end() { return builder.end(); } - inline T& front() { return builder.front(); } - inline T& back() { return builder.back(); } - - inline Array releaseAsArray() { - // TODO(perf): Avoid a copy/move by allowing Array to point to incomplete space? - if (!builder.isFull()) { - setCapacity(size()); - } - return builder.finish(); - } - - template - inline T& add(Params&&... params) { - if (builder.isFull()) grow(); - return builder.add(kj::fwd(params)...); - } - - template - inline void addAll(Iterator begin, Iterator end) { - size_t needed = builder.size() + (end - begin); - if (needed > builder.capacity()) grow(needed); - builder.addAll(begin, end); - } - - template - inline void addAll(Container&& container) { - addAll(container.begin(), container.end()); - } - - inline void removeLast() { - builder.removeLast(); - } - - inline void resize(size_t size) { - if (size > builder.capacity()) grow(size); - builder.resize(size); - } - - inline void operator=(decltype(nullptr)) { - builder = nullptr; - } - - inline void clear() { - while (builder.size() > 0) { - builder.removeLast(); - } - } - - inline void truncate(size_t size) { - builder.truncate(size); - } - - inline void reserve(size_t size) { - if (size > builder.capacity()) { - setCapacity(size); - } - } - -private: - ArrayBuilder builder; - - void grow(size_t minCapacity = 0) { - setCapacity(kj::max(minCapacity, capacity() == 0 ? 4 : capacity() * 2)); - } - void setCapacity(size_t newSize) { - if (builder.size() > newSize) { - builder.truncate(newSize); - } - ArrayBuilder newBuilder = heapArrayBuilder(newSize); - newBuilder.addAll(kj::mv(builder)); - builder = kj::mv(newBuilder); - } -}; - -template -inline auto KJ_STRINGIFY(const Vector& v) -> decltype(toCharSequence(v.asPtr())) { - return toCharSequence(v.asPtr()); -} - -} // namespace kj - -#endif // KJ_VECTOR_H_ diff --git a/phonelibs/capnp-cpp/include/kj/windows-sanity.h b/phonelibs/capnp-cpp/include/kj/windows-sanity.h deleted file mode 100644 index 766ba2cbd6..0000000000 --- a/phonelibs/capnp-cpp/include/kj/windows-sanity.h +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors -// Licensed under the MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef KJ_WINDOWS_SANITY_H_ -#define KJ_WINDOWS_SANITY_H_ - -#if defined(__GNUC__) && !KJ_HEADER_WARNINGS -#pragma GCC system_header -#endif - -#ifndef _INC_WINDOWS -#error "windows.h needs to be included before kj/windows-sanity.h (or perhaps you don't need either?)" -#endif - -namespace win32 { - const auto ERROR_ = ERROR; -#undef ERROR - const auto ERROR = ERROR_; -} - -using win32::ERROR; - -#endif // KJ_WINDOWS_SANITY_H_ diff --git a/phonelibs/install_capnp.sh b/phonelibs/install_capnp.sh index b83e1ffda1..b1ea7602f1 100755 --- a/phonelibs/install_capnp.sh +++ b/phonelibs/install_capnp.sh @@ -9,6 +9,7 @@ cd capnproto-c++-${VERSION} CXXFLAGS="-fPIC" ./configure make -j4 +make install # manually build binaries statically g++ -std=gnu++11 -I./src -I./src -DKJ_HEADER_WARNINGS -DCAPNP_HEADER_WARNINGS -DCAPNP_INCLUDE_DIR=\"/usr/local/include\" -pthread -O2 -DNDEBUG -pthread -pthread -o .libs/capnp src/capnp/compiler/module-loader.o src/capnp/compiler/capnp.o ./.libs/libcapnpc.a ./.libs/libcapnp.a ./.libs/libkj.a -lpthread -pthread @@ -18,6 +19,7 @@ g++ -std=gnu++11 -I./src -I./src -DKJ_HEADER_WARNINGS -DCAPNP_HEADER_WARNINGS -D g++ -std=gnu++11 -I./src -I./src -DKJ_HEADER_WARNINGS -DCAPNP_HEADER_WARNINGS -DCAPNP_INCLUDE_DIR=\"/usr/local/include\" -pthread -O2 -DNDEBUG -pthread -pthread -o .libs/capnpc-capnp src/capnp/compiler/capnpc-capnp.o ./.libs/libcapnp.a ./.libs/libkj.a -lpthread -pthread cp .libs/capnp /usr/local/bin/ +rm /usr/local/bin/capnpc ln -s /usr/local/bin/capnp /usr/local/bin/capnpc cp .libs/capnpc-c++ /usr/local/bin/ cp .libs/capnpc-capnp /usr/local/bin/ @@ -31,6 +33,7 @@ git submodule update --init --recursive autoreconf -f -i -s CXXFLAGS="-fPIC" ./configure make -j4 +make install # manually build binaries statically gcc -fPIC -o .libs/capnpc-c compiler/capnpc-c.o compiler/schema.capnp.o compiler/str.o ./.libs/libcapnp_c.a diff --git a/phonelibs/json11/json11.o b/phonelibs/json11/json11.o index 1e32cca71f..516adf3734 100644 Binary files a/phonelibs/json11/json11.o and b/phonelibs/json11/json11.o differ diff --git a/phonelibs/linux/include/linux/ion.h b/phonelibs/linux/include/linux/ion.h new file mode 100644 index 0000000000..7b5b031f57 --- /dev/null +++ b/phonelibs/linux/include/linux/ion.h @@ -0,0 +1,78 @@ +/**************************************************************************** + **************************************************************************** + *** + *** This header was automatically generated from a Linux kernel header + *** of the same name, to make information necessary for userspace to + *** call into the kernel available to libc. It contains only constants, + *** structures, and macros generated from the original header, and thus, + *** contains no copyrightable information. + *** + *** To edit the content of this header, modify the corresponding + *** source file (e.g. under external/kernel-headers/original/) then + *** run bionic/libc/kernel/tools/update_all.py + *** + *** Any manual change here will be lost the next time this script will + *** be run. You've been warned! + *** + **************************************************************************** + ****************************************************************************/ +#ifndef _UAPI_LINUX_ION_H +#define _UAPI_LINUX_ION_H +#include +#include +typedef int ion_user_handle_t; +enum ion_heap_type { + ION_HEAP_TYPE_SYSTEM, + ION_HEAP_TYPE_SYSTEM_CONTIG, + ION_HEAP_TYPE_CARVEOUT, + ION_HEAP_TYPE_CHUNK, + ION_HEAP_TYPE_DMA, + ION_HEAP_TYPE_CUSTOM, +}; +#define ION_NUM_HEAP_IDS (sizeof(unsigned int) * 8) +#define ION_FLAG_CACHED 1 +#define ION_FLAG_CACHED_NEEDS_SYNC 2 +struct ion_allocation_data { + size_t len; + size_t align; + unsigned int heap_id_mask; + unsigned int flags; + ion_user_handle_t handle; +}; +struct ion_fd_data { + ion_user_handle_t handle; + int fd; +}; +struct ion_handle_data { + ion_user_handle_t handle; +}; +struct ion_custom_data { + unsigned int cmd; + unsigned long arg; +}; +#define MAX_HEAP_NAME 32 +struct ion_heap_data { + char name[MAX_HEAP_NAME]; + __u32 type; + __u32 heap_id; + __u32 reserved0; + __u32 reserved1; + __u32 reserved2; +}; +struct ion_heap_query { + __u32 cnt; + __u32 reserved0; + __u64 heaps; + __u32 reserved1; + __u32 reserved2; +}; +#define ION_IOC_MAGIC 'I' +#define ION_IOC_ALLOC _IOWR(ION_IOC_MAGIC, 0, struct ion_allocation_data) +#define ION_IOC_FREE _IOWR(ION_IOC_MAGIC, 1, struct ion_handle_data) +#define ION_IOC_MAP _IOWR(ION_IOC_MAGIC, 2, struct ion_fd_data) +#define ION_IOC_SHARE _IOWR(ION_IOC_MAGIC, 4, struct ion_fd_data) +#define ION_IOC_IMPORT _IOWR(ION_IOC_MAGIC, 5, struct ion_fd_data) +#define ION_IOC_SYNC _IOWR(ION_IOC_MAGIC, 7, struct ion_fd_data) +#define ION_IOC_CUSTOM _IOWR(ION_IOC_MAGIC, 6, struct ion_custom_data) +#define ION_IOC_HEAP_QUERY _IOWR(ION_IOC_MAGIC, 8, struct ion_heap_query) +#endif diff --git a/phonelibs/openmax/include/OMX_Audio.h b/phonelibs/openmax/include/OMX_Audio.h new file mode 100644 index 0000000000..0d455766c5 --- /dev/null +++ b/phonelibs/openmax/include/OMX_Audio.h @@ -0,0 +1,1312 @@ +/* + * Copyright (c) 2008 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** @file OMX_Audio.h - OpenMax IL version 1.1.2 + * The structures needed by Audio components to exchange + * parameters and configuration data with the componenmilts. + */ + +#ifndef OMX_Audio_h +#define OMX_Audio_h + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +/* Each OMX header must include all required header files to allow the + * header to compile without errors. The includes below are required + * for this header file to compile successfully + */ + +#include + +/** @defgroup midi MIDI + * @ingroup audio + */ + +/** @defgroup effects Audio effects + * @ingroup audio + */ + +/** @defgroup audio OpenMAX IL Audio Domain + * Structures for OpenMAX IL Audio domain + * @{ + */ + +/** Enumeration used to define the possible audio codings. + * If "OMX_AUDIO_CodingUnused" is selected, the coding selection must + * be done in a vendor specific way. Since this is for an audio + * processing element this enum is relevant. However, for another + * type of component other enums would be in this area. + */ +typedef enum OMX_AUDIO_CODINGTYPE { + OMX_AUDIO_CodingUnused = 0, /**< Placeholder value when coding is N/A */ + OMX_AUDIO_CodingAutoDetect, /**< auto detection of audio format */ + OMX_AUDIO_CodingPCM, /**< Any variant of PCM coding */ + OMX_AUDIO_CodingADPCM, /**< Any variant of ADPCM encoded data */ + OMX_AUDIO_CodingAMR, /**< Any variant of AMR encoded data */ + OMX_AUDIO_CodingGSMFR, /**< Any variant of GSM fullrate (i.e. GSM610) */ + OMX_AUDIO_CodingGSMEFR, /**< Any variant of GSM Enhanced Fullrate encoded data*/ + OMX_AUDIO_CodingGSMHR, /**< Any variant of GSM Halfrate encoded data */ + OMX_AUDIO_CodingPDCFR, /**< Any variant of PDC Fullrate encoded data */ + OMX_AUDIO_CodingPDCEFR, /**< Any variant of PDC Enhanced Fullrate encoded data */ + OMX_AUDIO_CodingPDCHR, /**< Any variant of PDC Halfrate encoded data */ + OMX_AUDIO_CodingTDMAFR, /**< Any variant of TDMA Fullrate encoded data (TIA/EIA-136-420) */ + OMX_AUDIO_CodingTDMAEFR, /**< Any variant of TDMA Enhanced Fullrate encoded data (TIA/EIA-136-410) */ + OMX_AUDIO_CodingQCELP8, /**< Any variant of QCELP 8kbps encoded data */ + OMX_AUDIO_CodingQCELP13, /**< Any variant of QCELP 13kbps encoded data */ + OMX_AUDIO_CodingEVRC, /**< Any variant of EVRC encoded data */ + OMX_AUDIO_CodingSMV, /**< Any variant of SMV encoded data */ + OMX_AUDIO_CodingG711, /**< Any variant of G.711 encoded data */ + OMX_AUDIO_CodingG723, /**< Any variant of G.723 dot 1 encoded data */ + OMX_AUDIO_CodingG726, /**< Any variant of G.726 encoded data */ + OMX_AUDIO_CodingG729, /**< Any variant of G.729 encoded data */ + OMX_AUDIO_CodingAAC, /**< Any variant of AAC encoded data */ + OMX_AUDIO_CodingMP3, /**< Any variant of MP3 encoded data */ + OMX_AUDIO_CodingSBC, /**< Any variant of SBC encoded data */ + OMX_AUDIO_CodingVORBIS, /**< Any variant of VORBIS encoded data */ + OMX_AUDIO_CodingWMA, /**< Any variant of WMA encoded data */ + OMX_AUDIO_CodingRA, /**< Any variant of RA encoded data */ + OMX_AUDIO_CodingMIDI, /**< Any variant of MIDI encoded data */ + OMX_AUDIO_CodingAC3, /**< Any variant of AC3 encoded data */ + OMX_AUDIO_CodingKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_CodingVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_CodingMax = 0x7FFFFFFF +} OMX_AUDIO_CODINGTYPE; + + +/** The PortDefinition structure is used to define all of the parameters + * necessary for the compliant component to setup an input or an output audio + * path. If additional information is needed to define the parameters of the + * port (such as frequency), additional structures must be sent such as the + * OMX_AUDIO_PARAM_PCMMODETYPE structure to supply the extra parameters for the port. + */ +typedef struct OMX_AUDIO_PORTDEFINITIONTYPE { + OMX_STRING cMIMEType; /**< MIME type of data for the port */ + OMX_NATIVE_DEVICETYPE pNativeRender; /** < platform specific reference + for an output device, + otherwise this field is 0 */ + OMX_BOOL bFlagErrorConcealment; /**< Turns on error concealment if it is + supported by the OMX component */ + OMX_AUDIO_CODINGTYPE eEncoding; /**< Type of data expected for this + port (e.g. PCM, AMR, MP3, etc) */ +} OMX_AUDIO_PORTDEFINITIONTYPE; + + +/** Port format parameter. This structure is used to enumerate + * the various data input/output format supported by the port. + */ +typedef struct OMX_AUDIO_PARAM_PORTFORMATTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Indicates which port to set */ + OMX_U32 nIndex; /**< Indicates the enumeration index for the format from 0x0 to N-1 */ + OMX_AUDIO_CODINGTYPE eEncoding; /**< Type of data expected for this port (e.g. PCM, AMR, MP3, etc) */ +} OMX_AUDIO_PARAM_PORTFORMATTYPE; + + +/** PCM mode type */ +typedef enum OMX_AUDIO_PCMMODETYPE { + OMX_AUDIO_PCMModeLinear = 0, /**< Linear PCM encoded data */ + OMX_AUDIO_PCMModeALaw, /**< A law PCM encoded data (G.711) */ + OMX_AUDIO_PCMModeMULaw, /**< Mu law PCM encoded data (G.711) */ + OMX_AUDIO_PCMModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_PCMModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_PCMModeMax = 0x7FFFFFFF +} OMX_AUDIO_PCMMODETYPE; + + +typedef enum OMX_AUDIO_CHANNELTYPE { + OMX_AUDIO_ChannelNone = 0x0, /**< Unused or empty */ + OMX_AUDIO_ChannelLF = 0x1, /**< Left front */ + OMX_AUDIO_ChannelRF = 0x2, /**< Right front */ + OMX_AUDIO_ChannelCF = 0x3, /**< Center front */ + OMX_AUDIO_ChannelLS = 0x4, /**< Left surround */ + OMX_AUDIO_ChannelRS = 0x5, /**< Right surround */ + OMX_AUDIO_ChannelLFE = 0x6, /**< Low frequency effects */ + OMX_AUDIO_ChannelCS = 0x7, /**< Back surround */ + OMX_AUDIO_ChannelLR = 0x8, /**< Left rear. */ + OMX_AUDIO_ChannelRR = 0x9, /**< Right rear. */ + OMX_AUDIO_ChannelKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_ChannelVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_ChannelMax = 0x7FFFFFFF +} OMX_AUDIO_CHANNELTYPE; + +#define OMX_AUDIO_MAXCHANNELS 16 /**< maximum number distinct audio channels that a buffer may contain */ +#define OMX_MIN_PCMPAYLOAD_MSEC 5 /**< Minimum audio buffer payload size for uncompressed (PCM) audio */ + +/** PCM format description */ +typedef struct OMX_AUDIO_PARAM_PCMMODETYPE { + OMX_U32 nSize; /**< Size of this structure, in Bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels (e.g. 2 for stereo) */ + OMX_NUMERICALDATATYPE eNumData; /**< indicates PCM data as signed or unsigned */ + OMX_ENDIANTYPE eEndian; /**< indicates PCM data as little or big endian */ + OMX_BOOL bInterleaved; /**< True for normal interleaved data; false for + non-interleaved data (e.g. block data) */ + OMX_U32 nBitPerSample; /**< Bit per sample */ + OMX_U32 nSamplingRate; /**< Sampling rate of the source data. Use 0 for + variable or unknown sampling rate. */ + OMX_AUDIO_PCMMODETYPE ePCMMode; /**< PCM mode enumeration */ + OMX_AUDIO_CHANNELTYPE eChannelMapping[OMX_AUDIO_MAXCHANNELS]; /**< Slot i contains channel defined by eChannelMap[i] */ + +} OMX_AUDIO_PARAM_PCMMODETYPE; + + +/** Audio channel mode. This is used by both AAC and MP3, although the names are more appropriate + * for the MP3. For example, JointStereo for MP3 is CouplingChannels for AAC. + */ +typedef enum OMX_AUDIO_CHANNELMODETYPE { + OMX_AUDIO_ChannelModeStereo = 0, /**< 2 channels, the bitrate allocation between those + two channels changes accordingly to each channel information */ + OMX_AUDIO_ChannelModeJointStereo, /**< mode that takes advantage of what is common between + 2 channels for higher compression gain */ + OMX_AUDIO_ChannelModeDual, /**< 2 mono-channels, each channel is encoded with half + the bitrate of the overall bitrate */ + OMX_AUDIO_ChannelModeMono, /**< Mono channel mode */ + OMX_AUDIO_ChannelModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_ChannelModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_ChannelModeMax = 0x7FFFFFFF +} OMX_AUDIO_CHANNELMODETYPE; + + +typedef enum OMX_AUDIO_MP3STREAMFORMATTYPE { + OMX_AUDIO_MP3StreamFormatMP1Layer3 = 0, /**< MP3 Audio MPEG 1 Layer 3 Stream format */ + OMX_AUDIO_MP3StreamFormatMP2Layer3, /**< MP3 Audio MPEG 2 Layer 3 Stream format */ + OMX_AUDIO_MP3StreamFormatMP2_5Layer3, /**< MP3 Audio MPEG2.5 Layer 3 Stream format */ + OMX_AUDIO_MP3StreamFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_MP3StreamFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_MP3StreamFormatMax = 0x7FFFFFFF +} OMX_AUDIO_MP3STREAMFORMATTYPE; + +/** MP3 params */ +typedef struct OMX_AUDIO_PARAM_MP3TYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels */ + OMX_U32 nBitRate; /**< Bit rate of the input data. Use 0 for variable + rate or unknown bit rates */ + OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for + variable or unknown sampling rate. */ + OMX_U32 nAudioBandWidth; /**< Audio band width (in Hz) to which an encoder should + limit the audio signal. Use 0 to let encoder decide */ + OMX_AUDIO_CHANNELMODETYPE eChannelMode; /**< Channel mode enumeration */ + OMX_AUDIO_MP3STREAMFORMATTYPE eFormat; /**< MP3 stream format */ +} OMX_AUDIO_PARAM_MP3TYPE; + + +typedef enum OMX_AUDIO_AACSTREAMFORMATTYPE { + OMX_AUDIO_AACStreamFormatMP2ADTS = 0, /**< AAC Audio Data Transport Stream 2 format */ + OMX_AUDIO_AACStreamFormatMP4ADTS, /**< AAC Audio Data Transport Stream 4 format */ + OMX_AUDIO_AACStreamFormatMP4LOAS, /**< AAC Low Overhead Audio Stream format */ + OMX_AUDIO_AACStreamFormatMP4LATM, /**< AAC Low overhead Audio Transport Multiplex */ + OMX_AUDIO_AACStreamFormatADIF, /**< AAC Audio Data Interchange Format */ + OMX_AUDIO_AACStreamFormatMP4FF, /**< AAC inside MPEG-4/ISO File Format */ + OMX_AUDIO_AACStreamFormatRAW, /**< AAC Raw Format */ + OMX_AUDIO_AACStreamFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_AACStreamFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_AACStreamFormatMax = 0x7FFFFFFF +} OMX_AUDIO_AACSTREAMFORMATTYPE; + + +/** AAC mode type. Note that the term profile is used with the MPEG-2 + * standard and the term object type and profile is used with MPEG-4 */ +typedef enum OMX_AUDIO_AACPROFILETYPE{ + OMX_AUDIO_AACObjectNull = 0, /**< Null, not used */ + OMX_AUDIO_AACObjectMain = 1, /**< AAC Main object */ + OMX_AUDIO_AACObjectLC, /**< AAC Low Complexity object (AAC profile) */ + OMX_AUDIO_AACObjectSSR, /**< AAC Scalable Sample Rate object */ + OMX_AUDIO_AACObjectLTP, /**< AAC Long Term Prediction object */ + OMX_AUDIO_AACObjectHE, /**< AAC High Efficiency (object type SBR, HE-AAC profile) */ + OMX_AUDIO_AACObjectScalable, /**< AAC Scalable object */ + OMX_AUDIO_AACObjectERLC = 17, /**< ER AAC Low Complexity object (Error Resilient AAC-LC) */ + OMX_AUDIO_AACObjectLD = 23, /**< AAC Low Delay object (Error Resilient) */ + OMX_AUDIO_AACObjectHE_PS = 29, /**< AAC High Efficiency with Parametric Stereo coding (HE-AAC v2, object type PS) */ + OMX_AUDIO_AACObjectKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_AACObjectVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_AACObjectMax = 0x7FFFFFFF +} OMX_AUDIO_AACPROFILETYPE; + + +/** AAC tool usage (for nAACtools in OMX_AUDIO_PARAM_AACPROFILETYPE). + * Required for encoder configuration and optional as decoder info output. + * For MP3, OMX_AUDIO_CHANNELMODETYPE is sufficient. */ +#define OMX_AUDIO_AACToolNone 0x00000000 /**< no AAC tools allowed (encoder config) or active (decoder info output) */ +#define OMX_AUDIO_AACToolMS 0x00000001 /**< MS: Mid/side joint coding tool allowed or active */ +#define OMX_AUDIO_AACToolIS 0x00000002 /**< IS: Intensity stereo tool allowed or active */ +#define OMX_AUDIO_AACToolTNS 0x00000004 /**< TNS: Temporal Noise Shaping tool allowed or active */ +#define OMX_AUDIO_AACToolPNS 0x00000008 /**< PNS: MPEG-4 Perceptual Noise substitution tool allowed or active */ +#define OMX_AUDIO_AACToolLTP 0x00000010 /**< LTP: MPEG-4 Long Term Prediction tool allowed or active */ +#define OMX_AUDIO_AACToolAll 0x7FFFFFFF /**< all AAC tools allowed or active (*/ + +/** MPEG-4 AAC error resilience (ER) tool usage (for nAACERtools in OMX_AUDIO_PARAM_AACPROFILETYPE). + * Required for ER encoder configuration and optional as decoder info output */ +#define OMX_AUDIO_AACERNone 0x00000000 /**< no AAC ER tools allowed/used */ +#define OMX_AUDIO_AACERVCB11 0x00000001 /**< VCB11: Virtual Code Books for AAC section data */ +#define OMX_AUDIO_AACERRVLC 0x00000002 /**< RVLC: Reversible Variable Length Coding */ +#define OMX_AUDIO_AACERHCR 0x00000004 /**< HCR: Huffman Codeword Reordering */ +#define OMX_AUDIO_AACERAll 0x7FFFFFFF /**< all AAC ER tools allowed/used */ + + +/** AAC params */ +typedef struct OMX_AUDIO_PARAM_AACPROFILETYPE { + OMX_U32 nSize; /**< Size of this structure, in Bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels */ + OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for + variable or unknown sampling rate. */ + OMX_U32 nBitRate; /**< Bit rate of the input data. Use 0 for variable + rate or unknown bit rates */ + OMX_U32 nAudioBandWidth; /**< Audio band width (in Hz) to which an encoder should + limit the audio signal. Use 0 to let encoder decide */ + OMX_U32 nFrameLength; /**< Frame length (in audio samples per channel) of the codec. + Can be 1024 or 960 (AAC-LC), 2048 (HE-AAC), 480 or 512 (AAC-LD). + Use 0 to let encoder decide */ + OMX_U32 nAACtools; /**< AAC tool usage */ + OMX_U32 nAACERtools; /**< MPEG-4 AAC error resilience tool usage */ + OMX_AUDIO_AACPROFILETYPE eAACProfile; /**< AAC profile enumeration */ + OMX_AUDIO_AACSTREAMFORMATTYPE eAACStreamFormat; /**< AAC stream format enumeration */ + OMX_AUDIO_CHANNELMODETYPE eChannelMode; /**< Channel mode enumeration */ +} OMX_AUDIO_PARAM_AACPROFILETYPE; + + +/** VORBIS params */ +typedef struct OMX_AUDIO_PARAM_VORBISTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels */ + OMX_U32 nBitRate; /**< Bit rate of the encoded data data. Use 0 for variable + rate or unknown bit rates. Encoding is set to the + bitrate closest to specified value (in bps) */ + OMX_U32 nMinBitRate; /**< Sets minimum bitrate (in bps). */ + OMX_U32 nMaxBitRate; /**< Sets maximum bitrate (in bps). */ + + OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for + variable or unknown sampling rate. */ + OMX_U32 nAudioBandWidth; /**< Audio band width (in Hz) to which an encoder should + limit the audio signal. Use 0 to let encoder decide */ + OMX_S32 nQuality; /**< Sets encoding quality to n, between -1 (low) and 10 (high). + In the default mode of operation, teh quality level is 3. + Normal quality range is 0 - 10. */ + OMX_BOOL bManaged; /**< Set bitrate management mode. This turns off the + normal VBR encoding, but allows hard or soft bitrate + constraints to be enforced by the encoder. This mode can + be slower, and may also be lower quality. It is + primarily useful for streaming. */ + OMX_BOOL bDownmix; /**< Downmix input from stereo to mono (has no effect on + non-stereo streams). Useful for lower-bitrate encoding. */ +} OMX_AUDIO_PARAM_VORBISTYPE; + + +/** WMA Version */ +typedef enum OMX_AUDIO_WMAFORMATTYPE { + OMX_AUDIO_WMAFormatUnused = 0, /**< format unused or unknown */ + OMX_AUDIO_WMAFormat7, /**< Windows Media Audio format 7 */ + OMX_AUDIO_WMAFormat8, /**< Windows Media Audio format 8 */ + OMX_AUDIO_WMAFormat9, /**< Windows Media Audio format 9 */ + OMX_AUDIO_WMAFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_WMAFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_WMAFormatMax = 0x7FFFFFFF +} OMX_AUDIO_WMAFORMATTYPE; + + +/** WMA Profile */ +typedef enum OMX_AUDIO_WMAPROFILETYPE { + OMX_AUDIO_WMAProfileUnused = 0, /**< profile unused or unknown */ + OMX_AUDIO_WMAProfileL1, /**< Windows Media audio version 9 profile L1 */ + OMX_AUDIO_WMAProfileL2, /**< Windows Media audio version 9 profile L2 */ + OMX_AUDIO_WMAProfileL3, /**< Windows Media audio version 9 profile L3 */ + OMX_AUDIO_WMAProfileKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_WMAProfileVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_WMAProfileMax = 0x7FFFFFFF +} OMX_AUDIO_WMAPROFILETYPE; + + +/** WMA params */ +typedef struct OMX_AUDIO_PARAM_WMATYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U16 nChannels; /**< Number of channels */ + OMX_U32 nBitRate; /**< Bit rate of the input data. Use 0 for variable + rate or unknown bit rates */ + OMX_AUDIO_WMAFORMATTYPE eFormat; /**< Version of WMA stream / data */ + OMX_AUDIO_WMAPROFILETYPE eProfile; /**< Profile of WMA stream / data */ + OMX_U32 nSamplingRate; /**< Sampling rate of the source data */ + OMX_U16 nBlockAlign; /**< is the block alignment, or block size, in bytes of the audio codec */ + OMX_U16 nEncodeOptions; /**< WMA Type-specific data */ + OMX_U32 nSuperBlockAlign; /**< WMA Type-specific data */ +} OMX_AUDIO_PARAM_WMATYPE; + +/** + * RealAudio format + */ +typedef enum OMX_AUDIO_RAFORMATTYPE { + OMX_AUDIO_RAFormatUnused = 0, /**< Format unused or unknown */ + OMX_AUDIO_RA8, /**< RealAudio 8 codec */ + OMX_AUDIO_RA9, /**< RealAudio 9 codec */ + OMX_AUDIO_RA10_AAC, /**< MPEG-4 AAC codec for bitrates of more than 128kbps */ + OMX_AUDIO_RA10_CODEC, /**< RealAudio codec for bitrates less than 128 kbps */ + OMX_AUDIO_RA10_LOSSLESS, /**< RealAudio Lossless */ + OMX_AUDIO_RA10_MULTICHANNEL, /**< RealAudio Multichannel */ + OMX_AUDIO_RA10_VOICE, /**< RealAudio Voice for bitrates below 15 kbps */ + OMX_AUDIO_RAFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_RAFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_RAFormatMax = 0x7FFFFFFF +} OMX_AUDIO_RAFORMATTYPE; + +/** RA (Real Audio) params */ +typedef struct OMX_AUDIO_PARAM_RATYPE { + OMX_U32 nSize; /**< Size of this structure, in Bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels */ + OMX_U32 nSamplingRate; /**< is the sampling rate of the source data */ + OMX_U32 nBitsPerFrame; /**< is the value for bits per frame */ + OMX_U32 nSamplePerFrame; /**< is the value for samples per frame */ + OMX_U32 nCouplingQuantBits; /**< is the number of coupling quantization bits in the stream */ + OMX_U32 nCouplingStartRegion; /**< is the coupling start region in the stream */ + OMX_U32 nNumRegions; /**< is the number of regions value */ + OMX_AUDIO_RAFORMATTYPE eFormat; /**< is the RealAudio audio format */ +} OMX_AUDIO_PARAM_RATYPE; + + +/** SBC Allocation Method Type */ +typedef enum OMX_AUDIO_SBCALLOCMETHODTYPE { + OMX_AUDIO_SBCAllocMethodLoudness, /**< Loudness allocation method */ + OMX_AUDIO_SBCAllocMethodSNR, /**< SNR allocation method */ + OMX_AUDIO_SBCAllocMethodKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_SBCAllocMethodVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_SBCAllocMethodMax = 0x7FFFFFFF +} OMX_AUDIO_SBCALLOCMETHODTYPE; + + +/** SBC params */ +typedef struct OMX_AUDIO_PARAM_SBCTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels */ + OMX_U32 nBitRate; /**< Bit rate of the input data. Use 0 for variable + rate or unknown bit rates */ + OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for + variable or unknown sampling rate. */ + OMX_U32 nBlocks; /**< Number of blocks */ + OMX_U32 nSubbands; /**< Number of subbands */ + OMX_U32 nBitPool; /**< Bitpool value */ + OMX_BOOL bEnableBitrate; /**< Use bitrate value instead of bitpool */ + OMX_AUDIO_CHANNELMODETYPE eChannelMode; /**< Channel mode enumeration */ + OMX_AUDIO_SBCALLOCMETHODTYPE eSBCAllocType; /**< SBC Allocation method type */ +} OMX_AUDIO_PARAM_SBCTYPE; + + +/** ADPCM stream format parameters */ +typedef struct OMX_AUDIO_PARAM_ADPCMTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_U32 nBitsPerSample; /**< Number of bits in each sample */ + OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for + variable or unknown sampling rate. */ +} OMX_AUDIO_PARAM_ADPCMTYPE; + + +/** G723 rate */ +typedef enum OMX_AUDIO_G723RATE { + OMX_AUDIO_G723ModeUnused = 0, /**< AMRNB Mode unused / unknown */ + OMX_AUDIO_G723ModeLow, /**< 5300 bps */ + OMX_AUDIO_G723ModeHigh, /**< 6300 bps */ + OMX_AUDIO_G723ModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_G723ModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_G723ModeMax = 0x7FFFFFFF +} OMX_AUDIO_G723RATE; + + +/** G723 - Sample rate must be 8 KHz */ +typedef struct OMX_AUDIO_PARAM_G723TYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_AUDIO_G723RATE eBitRate; /**< todo: Should this be moved to a config? */ + OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ + OMX_BOOL bPostFilter; /**< Enable Post Filter */ +} OMX_AUDIO_PARAM_G723TYPE; + + +/** ITU G726 (ADPCM) rate */ +typedef enum OMX_AUDIO_G726MODE { + OMX_AUDIO_G726ModeUnused = 0, /**< G726 Mode unused / unknown */ + OMX_AUDIO_G726Mode16, /**< 16 kbps */ + OMX_AUDIO_G726Mode24, /**< 24 kbps */ + OMX_AUDIO_G726Mode32, /**< 32 kbps, most common rate, also G721 */ + OMX_AUDIO_G726Mode40, /**< 40 kbps */ + OMX_AUDIO_G726ModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_G726ModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_G726ModeMax = 0x7FFFFFFF +} OMX_AUDIO_G726MODE; + + +/** G.726 stream format parameters - must be at 8KHz */ +typedef struct OMX_AUDIO_PARAM_G726TYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_AUDIO_G726MODE eG726Mode; +} OMX_AUDIO_PARAM_G726TYPE; + + +/** G729 coder type */ +typedef enum OMX_AUDIO_G729TYPE { + OMX_AUDIO_G729 = 0, /**< ITU G.729 encoded data */ + OMX_AUDIO_G729A, /**< ITU G.729 annex A encoded data */ + OMX_AUDIO_G729B, /**< ITU G.729 with annex B encoded data */ + OMX_AUDIO_G729AB, /**< ITU G.729 annexes A and B encoded data */ + OMX_AUDIO_G729KhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_G729VendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_G729Max = 0x7FFFFFFF +} OMX_AUDIO_G729TYPE; + + +/** G729 stream format parameters - fixed 6KHz sample rate */ +typedef struct OMX_AUDIO_PARAM_G729TYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_AUDIO_G729TYPE eBitType; +} OMX_AUDIO_PARAM_G729TYPE; + + +/** AMR Frame format */ +typedef enum OMX_AUDIO_AMRFRAMEFORMATTYPE { + OMX_AUDIO_AMRFrameFormatConformance = 0, /**< Frame Format is AMR Conformance + (Standard) Format */ + OMX_AUDIO_AMRFrameFormatIF1, /**< Frame Format is AMR Interface + Format 1 */ + OMX_AUDIO_AMRFrameFormatIF2, /**< Frame Format is AMR Interface + Format 2*/ + OMX_AUDIO_AMRFrameFormatFSF, /**< Frame Format is AMR File Storage + Format */ + OMX_AUDIO_AMRFrameFormatRTPPayload, /**< Frame Format is AMR Real-Time + Transport Protocol Payload Format */ + OMX_AUDIO_AMRFrameFormatITU, /**< Frame Format is ITU Format (added at Motorola request) */ + OMX_AUDIO_AMRFrameFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_AMRFrameFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_AMRFrameFormatMax = 0x7FFFFFFF +} OMX_AUDIO_AMRFRAMEFORMATTYPE; + + +/** AMR band mode */ +typedef enum OMX_AUDIO_AMRBANDMODETYPE { + OMX_AUDIO_AMRBandModeUnused = 0, /**< AMRNB Mode unused / unknown */ + OMX_AUDIO_AMRBandModeNB0, /**< AMRNB Mode 0 = 4750 bps */ + OMX_AUDIO_AMRBandModeNB1, /**< AMRNB Mode 1 = 5150 bps */ + OMX_AUDIO_AMRBandModeNB2, /**< AMRNB Mode 2 = 5900 bps */ + OMX_AUDIO_AMRBandModeNB3, /**< AMRNB Mode 3 = 6700 bps */ + OMX_AUDIO_AMRBandModeNB4, /**< AMRNB Mode 4 = 7400 bps */ + OMX_AUDIO_AMRBandModeNB5, /**< AMRNB Mode 5 = 7950 bps */ + OMX_AUDIO_AMRBandModeNB6, /**< AMRNB Mode 6 = 10200 bps */ + OMX_AUDIO_AMRBandModeNB7, /**< AMRNB Mode 7 = 12200 bps */ + OMX_AUDIO_AMRBandModeWB0, /**< AMRWB Mode 0 = 6600 bps */ + OMX_AUDIO_AMRBandModeWB1, /**< AMRWB Mode 1 = 8850 bps */ + OMX_AUDIO_AMRBandModeWB2, /**< AMRWB Mode 2 = 12650 bps */ + OMX_AUDIO_AMRBandModeWB3, /**< AMRWB Mode 3 = 14250 bps */ + OMX_AUDIO_AMRBandModeWB4, /**< AMRWB Mode 4 = 15850 bps */ + OMX_AUDIO_AMRBandModeWB5, /**< AMRWB Mode 5 = 18250 bps */ + OMX_AUDIO_AMRBandModeWB6, /**< AMRWB Mode 6 = 19850 bps */ + OMX_AUDIO_AMRBandModeWB7, /**< AMRWB Mode 7 = 23050 bps */ + OMX_AUDIO_AMRBandModeWB8, /**< AMRWB Mode 8 = 23850 bps */ + OMX_AUDIO_AMRBandModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_AMRBandModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_AMRBandModeMax = 0x7FFFFFFF +} OMX_AUDIO_AMRBANDMODETYPE; + + +/** AMR Discontinuous Transmission mode */ +typedef enum OMX_AUDIO_AMRDTXMODETYPE { + OMX_AUDIO_AMRDTXModeOff = 0, /**< AMR Discontinuous Transmission Mode is disabled */ + OMX_AUDIO_AMRDTXModeOnVAD1, /**< AMR Discontinuous Transmission Mode using + Voice Activity Detector 1 (VAD1) is enabled */ + OMX_AUDIO_AMRDTXModeOnVAD2, /**< AMR Discontinuous Transmission Mode using + Voice Activity Detector 2 (VAD2) is enabled */ + OMX_AUDIO_AMRDTXModeOnAuto, /**< The codec will automatically select between + Off, VAD1 or VAD2 modes */ + + OMX_AUDIO_AMRDTXasEFR, /**< DTX as EFR instead of AMR standard (3GPP 26.101, frame type =8,9,10) */ + + OMX_AUDIO_AMRDTXModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_AMRDTXModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_AMRDTXModeMax = 0x7FFFFFFF +} OMX_AUDIO_AMRDTXMODETYPE; + + +/** AMR params */ +typedef struct OMX_AUDIO_PARAM_AMRTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels */ + OMX_U32 nBitRate; /**< Bit rate read only field */ + OMX_AUDIO_AMRBANDMODETYPE eAMRBandMode; /**< AMR Band Mode enumeration */ + OMX_AUDIO_AMRDTXMODETYPE eAMRDTXMode; /**< AMR DTX Mode enumeration */ + OMX_AUDIO_AMRFRAMEFORMATTYPE eAMRFrameFormat; /**< AMR frame format enumeration */ +} OMX_AUDIO_PARAM_AMRTYPE; + + +/** GSM_FR (ETSI 06.10, 3GPP 46.010) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_GSMFRTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ +} OMX_AUDIO_PARAM_GSMFRTYPE; + + +/** GSM-HR (ETSI 06.20, 3GPP 46.020) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_GSMHRTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ +} OMX_AUDIO_PARAM_GSMHRTYPE; + + +/** GSM-EFR (ETSI 06.60, 3GPP 46.060) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_GSMEFRTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ +} OMX_AUDIO_PARAM_GSMEFRTYPE; + + +/** TDMA FR (TIA/EIA-136-420, VSELP 7.95kbps coder) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_TDMAFRTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ +} OMX_AUDIO_PARAM_TDMAFRTYPE; + + +/** TDMA EFR (TIA/EIA-136-410, ACELP 7.4kbps coder) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_TDMAEFRTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ +} OMX_AUDIO_PARAM_TDMAEFRTYPE; + + +/** PDC FR ( RCR-27, VSELP 6.7kbps coder) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_PDCFRTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ +} OMX_AUDIO_PARAM_PDCFRTYPE; + + +/** PDC EFR ( RCR-27, ACELP 6.7kbps coder) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_PDCEFRTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ +} OMX_AUDIO_PARAM_PDCEFRTYPE; + +/** PDC HR ( RCR-27, PSI-CELP 3.45kbps coder) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_PDCHRTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ + OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ +} OMX_AUDIO_PARAM_PDCHRTYPE; + + +/** CDMA Rate types */ +typedef enum OMX_AUDIO_CDMARATETYPE { + OMX_AUDIO_CDMARateBlank = 0, /**< CDMA encoded frame is blank */ + OMX_AUDIO_CDMARateFull, /**< CDMA encoded frame in full rate */ + OMX_AUDIO_CDMARateHalf, /**< CDMA encoded frame in half rate */ + OMX_AUDIO_CDMARateQuarter, /**< CDMA encoded frame in quarter rate */ + OMX_AUDIO_CDMARateEighth, /**< CDMA encoded frame in eighth rate (DTX)*/ + OMX_AUDIO_CDMARateErasure, /**< CDMA erasure frame */ + OMX_AUDIO_CDMARateKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_CDMARateVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_CDMARateMax = 0x7FFFFFFF +} OMX_AUDIO_CDMARATETYPE; + + +/** QCELP8 (TIA/EIA-96, up to 8kbps coder) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_QCELP8TYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_U32 nBitRate; /**< Bit rate of the input data. Use 0 for variable + rate or unknown bit rates */ + OMX_AUDIO_CDMARATETYPE eCDMARate; /**< Frame rate */ + OMX_U32 nMinBitRate; /**< minmal rate for the encoder = 1,2,3,4, default = 1 */ + OMX_U32 nMaxBitRate; /**< maximal rate for the encoder = 1,2,3,4, default = 4 */ +} OMX_AUDIO_PARAM_QCELP8TYPE; + + +/** QCELP13 ( CDMA, EIA/TIA-733, 13.3kbps coder) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_QCELP13TYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_AUDIO_CDMARATETYPE eCDMARate; /**< Frame rate */ + OMX_U32 nMinBitRate; /**< minmal rate for the encoder = 1,2,3,4, default = 1 */ + OMX_U32 nMaxBitRate; /**< maximal rate for the encoder = 1,2,3,4, default = 4 */ +} OMX_AUDIO_PARAM_QCELP13TYPE; + + +/** EVRC ( CDMA, EIA/TIA-127, RCELP up to 8.55kbps coder) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_EVRCTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_AUDIO_CDMARATETYPE eCDMARate; /**< actual Frame rate */ + OMX_BOOL bRATE_REDUCon; /**< RATE_REDUCtion is requested for this frame */ + OMX_U32 nMinBitRate; /**< minmal rate for the encoder = 1,2,3,4, default = 1 */ + OMX_U32 nMaxBitRate; /**< maximal rate for the encoder = 1,2,3,4, default = 4 */ + OMX_BOOL bHiPassFilter; /**< Enable encoder's High Pass Filter */ + OMX_BOOL bNoiseSuppressor; /**< Enable encoder's noise suppressor pre-processing */ + OMX_BOOL bPostFilter; /**< Enable decoder's post Filter */ +} OMX_AUDIO_PARAM_EVRCTYPE; + + +/** SMV ( up to 8.55kbps coder) stream format parameters */ +typedef struct OMX_AUDIO_PARAM_SMVTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannels; /**< Number of channels in the data stream (not + necessarily the same as the number of channels + to be rendered. */ + OMX_AUDIO_CDMARATETYPE eCDMARate; /**< Frame rate */ + OMX_BOOL bRATE_REDUCon; /**< RATE_REDUCtion is requested for this frame */ + OMX_U32 nMinBitRate; /**< minmal rate for the encoder = 1,2,3,4, default = 1 ??*/ + OMX_U32 nMaxBitRate; /**< maximal rate for the encoder = 1,2,3,4, default = 4 ??*/ + OMX_BOOL bHiPassFilter; /**< Enable encoder's High Pass Filter ??*/ + OMX_BOOL bNoiseSuppressor; /**< Enable encoder's noise suppressor pre-processing */ + OMX_BOOL bPostFilter; /**< Enable decoder's post Filter ??*/ +} OMX_AUDIO_PARAM_SMVTYPE; + + +/** MIDI Format + * @ingroup midi + */ +typedef enum OMX_AUDIO_MIDIFORMATTYPE +{ + OMX_AUDIO_MIDIFormatUnknown = 0, /**< MIDI Format unknown or don't care */ + OMX_AUDIO_MIDIFormatSMF0, /**< Standard MIDI File Type 0 */ + OMX_AUDIO_MIDIFormatSMF1, /**< Standard MIDI File Type 1 */ + OMX_AUDIO_MIDIFormatSMF2, /**< Standard MIDI File Type 2 */ + OMX_AUDIO_MIDIFormatSPMIDI, /**< SP-MIDI */ + OMX_AUDIO_MIDIFormatXMF0, /**< eXtensible Music Format type 0 */ + OMX_AUDIO_MIDIFormatXMF1, /**< eXtensible Music Format type 1 */ + OMX_AUDIO_MIDIFormatMobileXMF, /**< Mobile XMF (eXtensible Music Format type 2) */ + OMX_AUDIO_MIDIFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_MIDIFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_MIDIFormatMax = 0x7FFFFFFF +} OMX_AUDIO_MIDIFORMATTYPE; + + +/** MIDI params + * @ingroup midi + */ +typedef struct OMX_AUDIO_PARAM_MIDITYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nFileSize; /**< size of the MIDI file in bytes, where the entire + MIDI file passed in, otherwise if 0x0, the MIDI data + is merged and streamed (instead of passed as an + entire MIDI file) */ + OMX_BU32 sMaxPolyphony; /**< Specifies the maximum simultaneous polyphonic + voices. A value of zero indicates that the default + polyphony of the device is used */ + OMX_BOOL bLoadDefaultSound; /**< Whether to load default sound + bank at initialization */ + OMX_AUDIO_MIDIFORMATTYPE eMidiFormat; /**< Version of the MIDI file */ +} OMX_AUDIO_PARAM_MIDITYPE; + + +/** Type of the MIDI sound bank + * @ingroup midi + */ +typedef enum OMX_AUDIO_MIDISOUNDBANKTYPE { + OMX_AUDIO_MIDISoundBankUnused = 0, /**< unused/unknown soundbank type */ + OMX_AUDIO_MIDISoundBankDLS1, /**< DLS version 1 */ + OMX_AUDIO_MIDISoundBankDLS2, /**< DLS version 2 */ + OMX_AUDIO_MIDISoundBankMobileDLSBase, /**< Mobile DLS, using the base functionality */ + OMX_AUDIO_MIDISoundBankMobileDLSPlusOptions, /**< Mobile DLS, using the specification-defined optional feature set */ + OMX_AUDIO_MIDISoundBankKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_MIDISoundBankVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_MIDISoundBankMax = 0x7FFFFFFF +} OMX_AUDIO_MIDISOUNDBANKTYPE; + + +/** Bank Layout describes how bank MSB & LSB are used in the DLS instrument definitions sound bank + * @ingroup midi + */ +typedef enum OMX_AUDIO_MIDISOUNDBANKLAYOUTTYPE { + OMX_AUDIO_MIDISoundBankLayoutUnused = 0, /**< unused/unknown soundbank type */ + OMX_AUDIO_MIDISoundBankLayoutGM, /**< GS layout (based on bank MSB 0x00) */ + OMX_AUDIO_MIDISoundBankLayoutGM2, /**< General MIDI 2 layout (using MSB 0x78/0x79, LSB 0x00) */ + OMX_AUDIO_MIDISoundBankLayoutUser, /**< Does not conform to any bank numbering standards */ + OMX_AUDIO_MIDISoundBankLayoutKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_MIDISoundBankLayoutVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_MIDISoundBankLayoutMax = 0x7FFFFFFF +} OMX_AUDIO_MIDISOUNDBANKLAYOUTTYPE; + + +/** MIDI params to load/unload user soundbank + * @ingroup midi + */ +typedef struct OMX_AUDIO_PARAM_MIDILOADUSERSOUNDTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nDLSIndex; /**< DLS file index to be loaded */ + OMX_U32 nDLSSize; /**< Size in bytes */ + OMX_PTR pDLSData; /**< Pointer to DLS file data */ + OMX_AUDIO_MIDISOUNDBANKTYPE eMidiSoundBank; /**< Midi sound bank type enumeration */ + OMX_AUDIO_MIDISOUNDBANKLAYOUTTYPE eMidiSoundBankLayout; /**< Midi sound bank layout enumeration */ +} OMX_AUDIO_PARAM_MIDILOADUSERSOUNDTYPE; + + +/** Structure for Live MIDI events and MIP messages. + * (MIP = Maximum Instantaneous Polyphony; part of the SP-MIDI standard.) + * @ingroup midi + */ +typedef struct OMX_AUDIO_CONFIG_MIDIIMMEDIATEEVENTTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Port that this structure applies to */ + OMX_U32 nMidiEventSize; /**< Size of immediate MIDI events or MIP message in bytes */ + OMX_U8 nMidiEvents[1]; /**< MIDI event array to be rendered immediately, or an + array for the MIP message buffer, where the size is + indicated by nMidiEventSize */ +} OMX_AUDIO_CONFIG_MIDIIMMEDIATEEVENTTYPE; + + +/** MIDI sound bank/ program pair in a given channel + * @ingroup midi + */ +typedef struct OMX_AUDIO_CONFIG_MIDISOUNDBANKPROGRAMTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Port that this structure applies to */ + OMX_U32 nChannel; /**< Valid channel values range from 1 to 16 */ + OMX_U16 nIDProgram; /**< Valid program ID range is 1 to 128 */ + OMX_U16 nIDSoundBank; /**< Sound bank ID */ + OMX_U32 nUserSoundBankIndex;/**< User soundbank index, easier to access soundbanks + by index if multiple banks are present */ +} OMX_AUDIO_CONFIG_MIDISOUNDBANKPROGRAMTYPE; + + +/** MIDI control + * @ingroup midi + */ +typedef struct OMX_AUDIO_CONFIG_MIDICONTROLTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BS32 sPitchTransposition; /**< Pitch transposition in semitones, stored as Q22.10 + format based on JAVA MMAPI (JSR-135) requirement */ + OMX_BU32 sPlayBackRate; /**< Relative playback rate, stored as Q14.17 fixed-point + number based on JSR-135 requirement */ + OMX_BU32 sTempo ; /**< Tempo in beats per minute (BPM), stored as Q22.10 + fixed-point number based on JSR-135 requirement */ + OMX_U32 nMaxPolyphony; /**< Specifies the maximum simultaneous polyphonic + voices. A value of zero indicates that the default + polyphony of the device is used */ + OMX_U32 nNumRepeat; /**< Number of times to repeat playback */ + OMX_U32 nStopTime; /**< Time in milliseconds to indicate when playback + will stop automatically. Set to zero if not used */ + OMX_U16 nChannelMuteMask; /**< 16 bit mask for channel mute status */ + OMX_U16 nChannelSoloMask; /**< 16 bit mask for channel solo status */ + OMX_U32 nTrack0031MuteMask; /**< 32 bit mask for track mute status. Note: This is for tracks 0-31 */ + OMX_U32 nTrack3263MuteMask; /**< 32 bit mask for track mute status. Note: This is for tracks 32-63 */ + OMX_U32 nTrack0031SoloMask; /**< 32 bit mask for track solo status. Note: This is for tracks 0-31 */ + OMX_U32 nTrack3263SoloMask; /**< 32 bit mask for track solo status. Note: This is for tracks 32-63 */ + +} OMX_AUDIO_CONFIG_MIDICONTROLTYPE; + + +/** MIDI Playback States + * @ingroup midi + */ +typedef enum OMX_AUDIO_MIDIPLAYBACKSTATETYPE { + OMX_AUDIO_MIDIPlayBackStateUnknown = 0, /**< Unknown state or state does not map to + other defined states */ + OMX_AUDIO_MIDIPlayBackStateClosedEngaged, /**< No MIDI resource is currently open. + The MIDI engine is currently processing + MIDI events. */ + OMX_AUDIO_MIDIPlayBackStateParsing, /**< A MIDI resource is open and is being + primed. The MIDI engine is currently + processing MIDI events. */ + OMX_AUDIO_MIDIPlayBackStateOpenEngaged, /**< A MIDI resource is open and primed but + not playing. The MIDI engine is currently + processing MIDI events. The transition to + this state is only possible from the + OMX_AUDIO_MIDIPlayBackStatePlaying state, + when the 'playback head' reaches the end + of media data or the playback stops due + to stop time set.*/ + OMX_AUDIO_MIDIPlayBackStatePlaying, /**< A MIDI resource is open and currently + playing. The MIDI engine is currently + processing MIDI events.*/ + OMX_AUDIO_MIDIPlayBackStatePlayingPartially, /**< Best-effort playback due to SP-MIDI/DLS + resource constraints */ + OMX_AUDIO_MIDIPlayBackStatePlayingSilently, /**< Due to system resource constraints and + SP-MIDI content constraints, there is + no audible MIDI content during playback + currently. The situation may change if + resources are freed later.*/ + OMX_AUDIO_MIDIPlayBackStateKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_MIDIPlayBackStateVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_MIDIPlayBackStateMax = 0x7FFFFFFF +} OMX_AUDIO_MIDIPLAYBACKSTATETYPE; + + +/** MIDI status + * @ingroup midi + */ +typedef struct OMX_AUDIO_CONFIG_MIDISTATUSTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U16 nNumTracks; /**< Number of MIDI tracks in the file, read only field. + NOTE: May not return a meaningful value until the entire + file is parsed and buffered. */ + OMX_U32 nDuration; /**< The length of the currently open MIDI resource + in milliseconds. NOTE: May not return a meaningful value + until the entire file is parsed and buffered. */ + OMX_U32 nPosition; /**< Current Position of the MIDI resource being played + in milliseconds */ + OMX_BOOL bVibra; /**< Does Vibra track exist? NOTE: May not return a meaningful + value until the entire file is parsed and buffered. */ + OMX_U32 nNumMetaEvents; /**< Total number of MIDI Meta Events in the currently + open MIDI resource. NOTE: May not return a meaningful value + until the entire file is parsed and buffered. */ + OMX_U32 nNumActiveVoices; /**< Number of active voices in the currently playing + MIDI resource. NOTE: May not return a meaningful value until + the entire file is parsed and buffered. */ + OMX_AUDIO_MIDIPLAYBACKSTATETYPE eMIDIPlayBackState; /**< MIDI playback state enumeration, read only field */ +} OMX_AUDIO_CONFIG_MIDISTATUSTYPE; + + +/** MIDI Meta Event structure one per Meta Event. + * MIDI Meta Events are like audio metadata, except that they are interspersed + * with the MIDI content throughout the file and are not localized in the header. + * As such, it is necessary to retrieve information about these Meta Events from + * the engine, as it encounters these Meta Events within the MIDI content. + * For example, SMF files can have up to 14 types of MIDI Meta Events (copyright, + * author, default tempo, etc.) scattered throughout the file. + * @ingroup midi + */ +typedef struct OMX_AUDIO_CONFIG_MIDIMETAEVENTTYPE{ + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nIndex; /**< Index of Meta Event */ + OMX_U8 nMetaEventType; /**< Meta Event Type, 7bits (i.e. 0 - 127) */ + OMX_U32 nMetaEventSize; /**< size of the Meta Event in bytes */ + OMX_U32 nTrack; /**< track number for the meta event */ + OMX_U32 nPosition; /**< Position of the meta-event in milliseconds */ +} OMX_AUDIO_CONFIG_MIDIMETAEVENTTYPE; + + +/** MIDI Meta Event Data structure - one per Meta Event. + * @ingroup midi + */ +typedef struct OMX_AUDIO_CONFIG_MIDIMETAEVENTDATATYPE{ + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nIndex; /**< Index of Meta Event */ + OMX_U32 nMetaEventSize; /**< size of the Meta Event in bytes */ + OMX_U8 nData[1]; /**< array of one or more bytes of meta data + as indicated by the nMetaEventSize field */ +} OMX_AUDIO_CONFIG__MIDIMETAEVENTDATATYPE; + + +/** Audio Volume adjustment for a port */ +typedef struct OMX_AUDIO_CONFIG_VOLUMETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Port index indicating which port to + set. Select the input port to set + just that port's volume. Select the + output port to adjust the master + volume. */ + OMX_BOOL bLinear; /**< Is the volume to be set in linear (0.100) + or logarithmic scale (mB) */ + OMX_BS32 sVolume; /**< Volume linear setting in the 0..100 range, OR + Volume logarithmic setting for this port. The values + for volume are in mB (millibels = 1/100 dB) relative + to a gain of 1 (e.g. the output is the same as the + input level). Values are in mB from nMax + (maximum volume) to nMin mB (typically negative). + Since the volume is "voltage" + and not a "power", it takes a setting of + -600 mB to decrease the volume by 1/2. If + a component cannot accurately set the + volume to the requested value, it must + set the volume to the closest value BELOW + the requested value. When getting the + volume setting, the current actual volume + must be returned. */ +} OMX_AUDIO_CONFIG_VOLUMETYPE; + + +/** Audio Volume adjustment for a channel */ +typedef struct OMX_AUDIO_CONFIG_CHANNELVOLUMETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Port index indicating which port to + set. Select the input port to set + just that port's volume. Select the + output port to adjust the master + volume. */ + OMX_U32 nChannel; /**< channel to select from 0 to N-1, + using OMX_ALL to apply volume settings + to all channels */ + OMX_BOOL bLinear; /**< Is the volume to be set in linear (0.100) or + logarithmic scale (mB) */ + OMX_BS32 sVolume; /**< Volume linear setting in the 0..100 range, OR + Volume logarithmic setting for this port. + The values for volume are in mB + (millibels = 1/100 dB) relative to a gain + of 1 (e.g. the output is the same as the + input level). Values are in mB from nMax + (maximum volume) to nMin mB (typically negative). + Since the volume is "voltage" + and not a "power", it takes a setting of + -600 mB to decrease the volume by 1/2. If + a component cannot accurately set the + volume to the requested value, it must + set the volume to the closest value BELOW + the requested value. When getting the + volume setting, the current actual volume + must be returned. */ + OMX_BOOL bIsMIDI; /**< TRUE if nChannel refers to a MIDI channel, + FALSE otherwise */ +} OMX_AUDIO_CONFIG_CHANNELVOLUMETYPE; + + +/** Audio balance setting */ +typedef struct OMX_AUDIO_CONFIG_BALANCETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Port index indicating which port to + set. Select the input port to set + just that port's balance. Select the + output port to adjust the master + balance. */ + OMX_S32 nBalance; /**< balance setting for this port + (-100 to 100, where -100 indicates + all left, and no right */ +} OMX_AUDIO_CONFIG_BALANCETYPE; + + +/** Audio Port mute */ +typedef struct OMX_AUDIO_CONFIG_MUTETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Port index indicating which port to + set. Select the input port to set + just that port's mute. Select the + output port to adjust the master + mute. */ + OMX_BOOL bMute; /**< Mute setting for this port */ +} OMX_AUDIO_CONFIG_MUTETYPE; + + +/** Audio Channel mute */ +typedef struct OMX_AUDIO_CONFIG_CHANNELMUTETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nChannel; /**< channel to select from 0 to N-1, + using OMX_ALL to apply mute settings + to all channels */ + OMX_BOOL bMute; /**< Mute setting for this channel */ + OMX_BOOL bIsMIDI; /**< TRUE if nChannel refers to a MIDI channel, + FALSE otherwise */ +} OMX_AUDIO_CONFIG_CHANNELMUTETYPE; + + + +/** Enable / Disable for loudness control, which boosts bass and to a + * smaller extent high end frequencies to compensate for hearing + * ability at the extreme ends of the audio spectrum + */ +typedef struct OMX_AUDIO_CONFIG_LOUDNESSTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bLoudness; /**< Enable/disable for loudness */ +} OMX_AUDIO_CONFIG_LOUDNESSTYPE; + + +/** Enable / Disable for bass, which controls low frequencies + */ +typedef struct OMX_AUDIO_CONFIG_BASSTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bEnable; /**< Enable/disable for bass control */ + OMX_S32 nBass; /**< bass setting for the port, as a + continuous value from -100 to 100 + (0 means no change in bass level)*/ +} OMX_AUDIO_CONFIG_BASSTYPE; + + +/** Enable / Disable for treble, which controls high frequencies tones + */ +typedef struct OMX_AUDIO_CONFIG_TREBLETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bEnable; /**< Enable/disable for treble control */ + OMX_S32 nTreble; /**< treble setting for the port, as a + continuous value from -100 to 100 + (0 means no change in treble level) */ +} OMX_AUDIO_CONFIG_TREBLETYPE; + + +/** An equalizer is typically used for two reasons: to compensate for an + * sub-optimal frequency response of a system to make it sound more natural + * or to create intentionally some unnatural coloring to the sound to create + * an effect. + * @ingroup effects + */ +typedef struct OMX_AUDIO_CONFIG_EQUALIZERTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bEnable; /**< Enable/disable for equalizer */ + OMX_BU32 sBandIndex; /**< Band number to be set. Upper Limit is + N-1, where N is the number of bands, lower limit is 0 */ + OMX_BU32 sCenterFreq; /**< Center frequecies in Hz. This is a + read only element and is used to determine + the lower, center and upper frequency of + this band. */ + OMX_BS32 sBandLevel; /**< band level in millibels */ +} OMX_AUDIO_CONFIG_EQUALIZERTYPE; + + +/** Stereo widening mode type + * @ingroup effects + */ +typedef enum OMX_AUDIO_STEREOWIDENINGTYPE { + OMX_AUDIO_StereoWideningHeadphones, /**< Stereo widening for loudspeakers */ + OMX_AUDIO_StereoWideningLoudspeakers, /**< Stereo widening for closely spaced loudspeakers */ + OMX_AUDIO_StereoWideningKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_StereoWideningVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_StereoWideningMax = 0x7FFFFFFF +} OMX_AUDIO_STEREOWIDENINGTYPE; + + +/** Control for stereo widening, which is a special 2-channel + * case of the audio virtualizer effect. For example, for 5.1-channel + * output, it translates to virtual surround sound. + * @ingroup effects + */ +typedef struct OMX_AUDIO_CONFIG_STEREOWIDENINGTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bEnable; /**< Enable/disable for stereo widening control */ + OMX_AUDIO_STEREOWIDENINGTYPE eWideningType; /**< Stereo widening algorithm type */ + OMX_U32 nStereoWidening; /**< stereo widening setting for the port, + as a continuous value from 0 to 100 */ +} OMX_AUDIO_CONFIG_STEREOWIDENINGTYPE; + + +/** The chorus effect (or ``choralizer'') is any signal processor which makes + * one sound source (such as a voice) sound like many such sources singing + * (or playing) in unison. Since performance in unison is never exact, chorus + * effects simulate this by making independently modified copies of the input + * signal. Modifications may include (1) delay, (2) frequency shift, and + * (3) amplitude modulation. + * @ingroup effects + */ +typedef struct OMX_AUDIO_CONFIG_CHORUSTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bEnable; /**< Enable/disable for chorus */ + OMX_BU32 sDelay; /**< average delay in milliseconds */ + OMX_BU32 sModulationRate; /**< rate of modulation in millihertz */ + OMX_U32 nModulationDepth; /**< depth of modulation as a percentage of + delay (i.e. 0 to 100) */ + OMX_BU32 nFeedback; /**< Feedback from chorus output to input in percentage */ +} OMX_AUDIO_CONFIG_CHORUSTYPE; + + +/** Reverberation is part of the reflected sound that follows the early + * reflections. In a typical room, this consists of a dense succession of + * echoes whose energy decays exponentially. The reverberation effect structure + * as defined here includes both (early) reflections as well as (late) reverberations. + * @ingroup effects + */ +typedef struct OMX_AUDIO_CONFIG_REVERBERATIONTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bEnable; /**< Enable/disable for reverberation control */ + OMX_BS32 sRoomLevel; /**< Intensity level for the whole room effect + (i.e. both early reflections and late + reverberation) in millibels */ + OMX_BS32 sRoomHighFreqLevel; /**< Attenuation at high frequencies + relative to the intensity at low + frequencies in millibels */ + OMX_BS32 sReflectionsLevel; /**< Intensity level of early reflections + (relative to room value), in millibels */ + OMX_BU32 sReflectionsDelay; /**< Delay time of the first reflection relative + to the direct path, in milliseconds */ + OMX_BS32 sReverbLevel; /**< Intensity level of late reverberation + relative to room level, in millibels */ + OMX_BU32 sReverbDelay; /**< Time delay from the first early reflection + to the beginning of the late reverberation + section, in milliseconds */ + OMX_BU32 sDecayTime; /**< Late reverberation decay time at low + frequencies, in milliseconds */ + OMX_BU32 nDecayHighFreqRatio; /**< Ratio of high frequency decay time relative + to low frequency decay time in percent */ + OMX_U32 nDensity; /**< Modal density in the late reverberation decay, + in percent (i.e. 0 - 100) */ + OMX_U32 nDiffusion; /**< Echo density in the late reverberation decay, + in percent (i.e. 0 - 100) */ + OMX_BU32 sReferenceHighFreq; /**< Reference high frequency in Hertz. This is + the frequency used as the reference for all + the high-frequency settings above */ + +} OMX_AUDIO_CONFIG_REVERBERATIONTYPE; + + +/** Possible settings for the Echo Cancelation structure to use + * @ingroup effects + */ +typedef enum OMX_AUDIO_ECHOCANTYPE { + OMX_AUDIO_EchoCanOff = 0, /**< Echo Cancellation is disabled */ + OMX_AUDIO_EchoCanNormal, /**< Echo Cancellation normal operation - + echo from plastics and face */ + OMX_AUDIO_EchoCanHFree, /**< Echo Cancellation optimized for + Hands Free operation */ + OMX_AUDIO_EchoCanCarKit, /**< Echo Cancellation optimized for + Car Kit (longer echo) */ + OMX_AUDIO_EchoCanKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_AUDIO_EchoCanVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_AUDIO_EchoCanMax = 0x7FFFFFFF +} OMX_AUDIO_ECHOCANTYPE; + + +/** Enable / Disable for echo cancelation, which removes undesired echo's + * from the audio + * @ingroup effects + */ +typedef struct OMX_AUDIO_CONFIG_ECHOCANCELATIONTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_AUDIO_ECHOCANTYPE eEchoCancelation; /**< Echo cancelation settings */ +} OMX_AUDIO_CONFIG_ECHOCANCELATIONTYPE; + + +/** Enable / Disable for noise reduction, which undesired noise from + * the audio + * @ingroup effects + */ +typedef struct OMX_AUDIO_CONFIG_NOISEREDUCTIONTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BOOL bNoiseReduction; /**< Enable/disable for noise reduction */ +} OMX_AUDIO_CONFIG_NOISEREDUCTIONTYPE; + +/** @} */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif +/* File EOF */ + diff --git a/phonelibs/openmax/include/OMX_Component.h b/phonelibs/openmax/include/OMX_Component.h new file mode 100644 index 0000000000..d5956405e2 --- /dev/null +++ b/phonelibs/openmax/include/OMX_Component.h @@ -0,0 +1,579 @@ +/* + * Copyright (c) 2008 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** OMX_Component.h - OpenMax IL version 1.1.2 + * The OMX_Component header file contains the definitions used to define + * the public interface of a component. This header file is intended to + * be used by both the application and the component. + */ + +#ifndef OMX_Component_h +#define OMX_Component_h + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + + +/* Each OMX header must include all required header files to allow the + * header to compile without errors. The includes below are required + * for this header file to compile successfully + */ + +#include +#include +#include +#include + +/** @ingroup comp */ +typedef enum OMX_PORTDOMAINTYPE { + OMX_PortDomainAudio, + OMX_PortDomainVideo, + OMX_PortDomainImage, + OMX_PortDomainOther, + OMX_PortDomainKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_PortDomainVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_PortDomainMax = 0x7ffffff +} OMX_PORTDOMAINTYPE; + +/** @ingroup comp */ +typedef struct OMX_PARAM_PORTDEFINITIONTYPE { + OMX_U32 nSize; /**< Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Port number the structure applies to */ + OMX_DIRTYPE eDir; /**< Direction (input or output) of this port */ + OMX_U32 nBufferCountActual; /**< The actual number of buffers allocated on this port */ + OMX_U32 nBufferCountMin; /**< The minimum number of buffers this port requires */ + OMX_U32 nBufferSize; /**< Size, in bytes, for buffers to be used for this channel */ + OMX_BOOL bEnabled; /**< Ports default to enabled and are enabled/disabled by + OMX_CommandPortEnable/OMX_CommandPortDisable. + When disabled a port is unpopulated. A disabled port + is not populated with buffers on a transition to IDLE. */ + OMX_BOOL bPopulated; /**< Port is populated with all of its buffers as indicated by + nBufferCountActual. A disabled port is always unpopulated. + An enabled port is populated on a transition to OMX_StateIdle + and unpopulated on a transition to loaded. */ + OMX_PORTDOMAINTYPE eDomain; /**< Domain of the port. Determines the contents of metadata below. */ + union { + OMX_AUDIO_PORTDEFINITIONTYPE audio; + OMX_VIDEO_PORTDEFINITIONTYPE video; + OMX_IMAGE_PORTDEFINITIONTYPE image; + OMX_OTHER_PORTDEFINITIONTYPE other; + } format; + OMX_BOOL bBuffersContiguous; + OMX_U32 nBufferAlignment; +} OMX_PARAM_PORTDEFINITIONTYPE; + +/** @ingroup comp */ +typedef struct OMX_PARAM_U32TYPE { + OMX_U32 nSize; /**< Size of this structure, in Bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_U32 nU32; /**< U32 value */ +} OMX_PARAM_U32TYPE; + +/** @ingroup rpm */ +typedef enum OMX_SUSPENSIONPOLICYTYPE { + OMX_SuspensionDisabled, /**< No suspension; v1.0 behavior */ + OMX_SuspensionEnabled, /**< Suspension allowed */ + OMX_SuspensionPolicyKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_SuspensionPolicyStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_SuspensionPolicyMax = 0x7fffffff +} OMX_SUSPENSIONPOLICYTYPE; + +/** @ingroup rpm */ +typedef struct OMX_PARAM_SUSPENSIONPOLICYTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_SUSPENSIONPOLICYTYPE ePolicy; +} OMX_PARAM_SUSPENSIONPOLICYTYPE; + +/** @ingroup rpm */ +typedef enum OMX_SUSPENSIONTYPE { + OMX_NotSuspended, /**< component is not suspended */ + OMX_Suspended, /**< component is suspended */ + OMX_SuspensionKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_SuspensionVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_SuspendMax = 0x7FFFFFFF +} OMX_SUSPENSIONTYPE; + +/** @ingroup rpm */ +typedef struct OMX_PARAM_SUSPENSIONTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_SUSPENSIONTYPE eType; +} OMX_PARAM_SUSPENSIONTYPE ; + +typedef struct OMX_CONFIG_BOOLEANTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_BOOL bEnabled; +} OMX_CONFIG_BOOLEANTYPE; + +/* Parameter specifying the content uri to use. */ +/** @ingroup cp */ +typedef struct OMX_PARAM_CONTENTURITYPE +{ + OMX_U32 nSize; /**< size of the structure in bytes, including + actual URI name */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U8 contentURI[1]; /**< The URI name */ +} OMX_PARAM_CONTENTURITYPE; + +/* Parameter specifying the pipe to use. */ +/** @ingroup cp */ +typedef struct OMX_PARAM_CONTENTPIPETYPE +{ + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_HANDLETYPE hPipe; /**< The pipe handle*/ +} OMX_PARAM_CONTENTPIPETYPE; + +/** @ingroup rpm */ +typedef struct OMX_RESOURCECONCEALMENTTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_BOOL bResourceConcealmentForbidden; /**< disallow the use of resource concealment + methods (like degrading algorithm quality to + lower resource consumption or functional bypass) + on a component as a resolution to resource conflicts. */ +} OMX_RESOURCECONCEALMENTTYPE; + + +/** @ingroup metadata */ +typedef enum OMX_METADATACHARSETTYPE { + OMX_MetadataCharsetUnknown = 0, + OMX_MetadataCharsetASCII, + OMX_MetadataCharsetBinary, + OMX_MetadataCharsetCodePage1252, + OMX_MetadataCharsetUTF8, + OMX_MetadataCharsetJavaConformantUTF8, + OMX_MetadataCharsetUTF7, + OMX_MetadataCharsetImapUTF7, + OMX_MetadataCharsetUTF16LE, + OMX_MetadataCharsetUTF16BE, + OMX_MetadataCharsetGB12345, + OMX_MetadataCharsetHZGB2312, + OMX_MetadataCharsetGB2312, + OMX_MetadataCharsetGB18030, + OMX_MetadataCharsetGBK, + OMX_MetadataCharsetBig5, + OMX_MetadataCharsetISO88591, + OMX_MetadataCharsetISO88592, + OMX_MetadataCharsetISO88593, + OMX_MetadataCharsetISO88594, + OMX_MetadataCharsetISO88595, + OMX_MetadataCharsetISO88596, + OMX_MetadataCharsetISO88597, + OMX_MetadataCharsetISO88598, + OMX_MetadataCharsetISO88599, + OMX_MetadataCharsetISO885910, + OMX_MetadataCharsetISO885913, + OMX_MetadataCharsetISO885914, + OMX_MetadataCharsetISO885915, + OMX_MetadataCharsetShiftJIS, + OMX_MetadataCharsetISO2022JP, + OMX_MetadataCharsetISO2022JP1, + OMX_MetadataCharsetISOEUCJP, + OMX_MetadataCharsetSMS7Bit, + OMX_MetadataCharsetKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_MetadataCharsetVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_MetadataCharsetTypeMax= 0x7FFFFFFF +} OMX_METADATACHARSETTYPE; + +/** @ingroup metadata */ +typedef enum OMX_METADATASCOPETYPE +{ + OMX_MetadataScopeAllLevels, + OMX_MetadataScopeTopLevel, + OMX_MetadataScopePortLevel, + OMX_MetadataScopeNodeLevel, + OMX_MetadataScopeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_MetadataScopeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_MetadataScopeTypeMax = 0x7fffffff +} OMX_METADATASCOPETYPE; + +/** @ingroup metadata */ +typedef enum OMX_METADATASEARCHMODETYPE +{ + OMX_MetadataSearchValueSizeByIndex, + OMX_MetadataSearchItemByIndex, + OMX_MetadataSearchNextItemByKey, + OMX_MetadataSearchKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_MetadataSearchVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_MetadataSearchTypeMax = 0x7fffffff +} OMX_METADATASEARCHMODETYPE; +/** @ingroup metadata */ +typedef struct OMX_CONFIG_METADATAITEMCOUNTTYPE +{ + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_METADATASCOPETYPE eScopeMode; + OMX_U32 nScopeSpecifier; + OMX_U32 nMetadataItemCount; +} OMX_CONFIG_METADATAITEMCOUNTTYPE; + +/** @ingroup metadata */ +typedef struct OMX_CONFIG_METADATAITEMTYPE +{ + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_METADATASCOPETYPE eScopeMode; + OMX_U32 nScopeSpecifier; + OMX_U32 nMetadataItemIndex; + OMX_METADATASEARCHMODETYPE eSearchMode; + OMX_METADATACHARSETTYPE eKeyCharset; + OMX_U8 nKeySizeUsed; + OMX_U8 nKey[128]; + OMX_METADATACHARSETTYPE eValueCharset; + OMX_STRING sLanguageCountry; + OMX_U32 nValueMaxSize; + OMX_U32 nValueSizeUsed; + OMX_U8 nValue[1]; +} OMX_CONFIG_METADATAITEMTYPE; + +/* @ingroup metadata */ +typedef struct OMX_CONFIG_CONTAINERNODECOUNTTYPE +{ + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_BOOL bAllKeys; + OMX_U32 nParentNodeID; + OMX_U32 nNumNodes; +} OMX_CONFIG_CONTAINERNODECOUNTTYPE; + +/** @ingroup metadata */ +typedef struct OMX_CONFIG_CONTAINERNODEIDTYPE +{ + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_BOOL bAllKeys; + OMX_U32 nParentNodeID; + OMX_U32 nNodeIndex; + OMX_U32 nNodeID; + OMX_STRING cNodeName; + OMX_BOOL bIsLeafType; +} OMX_CONFIG_CONTAINERNODEIDTYPE; + +/** @ingroup metadata */ +typedef struct OMX_PARAM_METADATAFILTERTYPE +{ + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_BOOL bAllKeys; /* if true then this structure refers to all keys and + * the three key fields below are ignored */ + OMX_METADATACHARSETTYPE eKeyCharset; + OMX_U32 nKeySizeUsed; + OMX_U8 nKey [128]; + OMX_U32 nLanguageCountrySizeUsed; + OMX_U8 nLanguageCountry[128]; + OMX_BOOL bEnabled; /* if true then key is part of filter (e.g. + * retained for query later). If false then + * key is not part of filter */ +} OMX_PARAM_METADATAFILTERTYPE; + +/** The OMX_HANDLETYPE structure defines the component handle. The component + * handle is used to access all of the component's public methods and also + * contains pointers to the component's private data area. The component + * handle is initialized by the OMX core (with help from the component) + * during the process of loading the component. After the component is + * successfully loaded, the application can safely access any of the + * component's public functions (although some may return an error because + * the state is inappropriate for the access). + * + * @ingroup comp + */ +typedef struct OMX_COMPONENTTYPE +{ + /** The size of this structure, in bytes. It is the responsibility + of the allocator of this structure to fill in this value. Since + this structure is allocated by the GetHandle function, this + function will fill in this value. */ + OMX_U32 nSize; + + /** nVersion is the version of the OMX specification that the structure + is built against. It is the responsibility of the creator of this + structure to initialize this value and every user of this structure + should verify that it knows how to use the exact version of + this structure found herein. */ + OMX_VERSIONTYPE nVersion; + + /** pComponentPrivate is a pointer to the component private data area. + This member is allocated and initialized by the component when the + component is first loaded. The application should not access this + data area. */ + OMX_PTR pComponentPrivate; + + /** pApplicationPrivate is a pointer that is a parameter to the + OMX_GetHandle method, and contains an application private value + provided by the IL client. This application private data is + returned to the IL Client by OMX in all callbacks */ + OMX_PTR pApplicationPrivate; + + /** refer to OMX_GetComponentVersion in OMX_core.h or the OMX IL + specification for details on the GetComponentVersion method. + */ + OMX_ERRORTYPE (*GetComponentVersion)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_OUT OMX_STRING pComponentName, + OMX_OUT OMX_VERSIONTYPE* pComponentVersion, + OMX_OUT OMX_VERSIONTYPE* pSpecVersion, + OMX_OUT OMX_UUIDTYPE* pComponentUUID); + + /** refer to OMX_SendCommand in OMX_core.h or the OMX IL + specification for details on the SendCommand method. + */ + OMX_ERRORTYPE (*SendCommand)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_COMMANDTYPE Cmd, + OMX_IN OMX_U32 nParam1, + OMX_IN OMX_PTR pCmdData); + + /** refer to OMX_GetParameter in OMX_core.h or the OMX IL + specification for details on the GetParameter method. + */ + OMX_ERRORTYPE (*GetParameter)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_INDEXTYPE nParamIndex, + OMX_INOUT OMX_PTR pComponentParameterStructure); + + + /** refer to OMX_SetParameter in OMX_core.h or the OMX IL + specification for details on the SetParameter method. + */ + OMX_ERRORTYPE (*SetParameter)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_INDEXTYPE nIndex, + OMX_IN OMX_PTR pComponentParameterStructure); + + + /** refer to OMX_GetConfig in OMX_core.h or the OMX IL + specification for details on the GetConfig method. + */ + OMX_ERRORTYPE (*GetConfig)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_INDEXTYPE nIndex, + OMX_INOUT OMX_PTR pComponentConfigStructure); + + + /** refer to OMX_SetConfig in OMX_core.h or the OMX IL + specification for details on the SetConfig method. + */ + OMX_ERRORTYPE (*SetConfig)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_INDEXTYPE nIndex, + OMX_IN OMX_PTR pComponentConfigStructure); + + + /** refer to OMX_GetExtensionIndex in OMX_core.h or the OMX IL + specification for details on the GetExtensionIndex method. + */ + OMX_ERRORTYPE (*GetExtensionIndex)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_STRING cParameterName, + OMX_OUT OMX_INDEXTYPE* pIndexType); + + + /** refer to OMX_GetState in OMX_core.h or the OMX IL + specification for details on the GetState method. + */ + OMX_ERRORTYPE (*GetState)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_OUT OMX_STATETYPE* pState); + + + /** The ComponentTunnelRequest method will interact with another OMX + component to determine if tunneling is possible and to setup the + tunneling. The return codes for this method can be used to + determine if tunneling is not possible, or if tunneling is not + supported. + + Base profile components (i.e. non-interop) do not support this + method and should return OMX_ErrorNotImplemented + + The interop profile component MUST support tunneling to another + interop profile component with a compatible port parameters. + A component may also support proprietary communication. + + If proprietary communication is supported the negotiation of + proprietary communication is done outside of OMX in a vendor + specific way. It is only required that the proper result be + returned and the details of how the setup is done is left + to the component implementation. + + When this method is invoked when nPort in an output port, the + component will: + 1. Populate the pTunnelSetup structure with the output port's + requirements and constraints for the tunnel. + + When this method is invoked when nPort in an input port, the + component will: + 1. Query the necessary parameters from the output port to + determine if the ports are compatible for tunneling + 2. If the ports are compatible, the component should store + the tunnel step provided by the output port + 3. Determine which port (either input or output) is the buffer + supplier, and call OMX_SetParameter on the output port to + indicate this selection. + + The component will return from this call within 5 msec. + + @param [in] hComp + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle method. + @param [in] nPort + nPort is used to select the port on the component to be used + for tunneling. + @param [in] hTunneledComp + Handle of the component to tunnel with. This is the component + handle returned by the call to the OMX_GetHandle method. When + this parameter is 0x0 the component should setup the port for + communication with the application / IL Client. + @param [in] nPortOutput + nPortOutput is used indicate the port the component should + tunnel with. + @param [in] pTunnelSetup + Pointer to the tunnel setup structure. When nPort is an output port + the component should populate the fields of this structure. When + When nPort is an input port the component should review the setup + provided by the component with the output port. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup tun + */ + + OMX_ERRORTYPE (*ComponentTunnelRequest)( + OMX_IN OMX_HANDLETYPE hComp, + OMX_IN OMX_U32 nPort, + OMX_IN OMX_HANDLETYPE hTunneledComp, + OMX_IN OMX_U32 nTunneledPort, + OMX_INOUT OMX_TUNNELSETUPTYPE* pTunnelSetup); + + /** refer to OMX_UseBuffer in OMX_core.h or the OMX IL + specification for details on the UseBuffer method. + @ingroup buf + */ + OMX_ERRORTYPE (*UseBuffer)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_INOUT OMX_BUFFERHEADERTYPE** ppBufferHdr, + OMX_IN OMX_U32 nPortIndex, + OMX_IN OMX_PTR pAppPrivate, + OMX_IN OMX_U32 nSizeBytes, + OMX_IN OMX_U8* pBuffer); + + /** refer to OMX_AllocateBuffer in OMX_core.h or the OMX IL + specification for details on the AllocateBuffer method. + @ingroup buf + */ + OMX_ERRORTYPE (*AllocateBuffer)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_INOUT OMX_BUFFERHEADERTYPE** ppBuffer, + OMX_IN OMX_U32 nPortIndex, + OMX_IN OMX_PTR pAppPrivate, + OMX_IN OMX_U32 nSizeBytes); + + /** refer to OMX_FreeBuffer in OMX_core.h or the OMX IL + specification for details on the FreeBuffer method. + @ingroup buf + */ + OMX_ERRORTYPE (*FreeBuffer)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_U32 nPortIndex, + OMX_IN OMX_BUFFERHEADERTYPE* pBuffer); + + /** refer to OMX_EmptyThisBuffer in OMX_core.h or the OMX IL + specification for details on the EmptyThisBuffer method. + @ingroup buf + */ + OMX_ERRORTYPE (*EmptyThisBuffer)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_BUFFERHEADERTYPE* pBuffer); + + /** refer to OMX_FillThisBuffer in OMX_core.h or the OMX IL + specification for details on the FillThisBuffer method. + @ingroup buf + */ + OMX_ERRORTYPE (*FillThisBuffer)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_BUFFERHEADERTYPE* pBuffer); + + /** The SetCallbacks method is used by the core to specify the callback + structure from the application to the component. This is a blocking + call. The component will return from this call within 5 msec. + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the GetHandle function. + @param [in] pCallbacks + pointer to an OMX_CALLBACKTYPE structure used to provide the + callback information to the component + @param [in] pAppData + pointer to an application defined value. It is anticipated that + the application will pass a pointer to a data structure or a "this + pointer" in this area to allow the callback (in the application) + to determine the context of the call + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + */ + OMX_ERRORTYPE (*SetCallbacks)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_CALLBACKTYPE* pCallbacks, + OMX_IN OMX_PTR pAppData); + + /** ComponentDeInit method is used to deinitialize the component + providing a means to free any resources allocated at component + initialization. NOTE: After this call the component handle is + not valid for further use. + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the GetHandle function. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + */ + OMX_ERRORTYPE (*ComponentDeInit)( + OMX_IN OMX_HANDLETYPE hComponent); + + /** @ingroup buf */ + OMX_ERRORTYPE (*UseEGLImage)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_INOUT OMX_BUFFERHEADERTYPE** ppBufferHdr, + OMX_IN OMX_U32 nPortIndex, + OMX_IN OMX_PTR pAppPrivate, + OMX_IN void* eglImage); + + OMX_ERRORTYPE (*ComponentRoleEnum)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_OUT OMX_U8 *cRole, + OMX_IN OMX_U32 nIndex); + +} OMX_COMPONENTTYPE; + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif +/* File EOF */ diff --git a/phonelibs/openmax/include/OMX_ContentPipe.h b/phonelibs/openmax/include/OMX_ContentPipe.h new file mode 100644 index 0000000000..5f6310c28a --- /dev/null +++ b/phonelibs/openmax/include/OMX_ContentPipe.h @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2008 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** OMX_ContentPipe.h - OpenMax IL version 1.1.2 + * The OMX_ContentPipe header file contains the definitions used to define + * the public interface for content piples. This header file is intended to + * be used by the component. + */ + +#ifndef OMX_CONTENTPIPE_H +#define OMX_CONTENTPIPE_H + +#ifndef KD_EACCES +/* OpenKODE error codes. CPResult values may be zero (indicating success + or one of the following values) */ +#define KD_EACCES (1) +#define KD_EADDRINUSE (2) +#define KD_EAGAIN (5) +#define KD_EBADF (7) +#define KD_EBUSY (8) +#define KD_ECONNREFUSED (9) +#define KD_ECONNRESET (10) +#define KD_EDEADLK (11) +#define KD_EDESTADDRREQ (12) +#define KD_ERANGE (35) +#define KD_EEXIST (13) +#define KD_EFBIG (14) +#define KD_EHOSTUNREACH (15) +#define KD_EINVAL (17) +#define KD_EIO (18) +#define KD_EISCONN (20) +#define KD_EISDIR (21) +#define KD_EMFILE (22) +#define KD_ENAMETOOLONG (23) +#define KD_ENOENT (24) +#define KD_ENOMEM (25) +#define KD_ENOSPC (26) +#define KD_ENOSYS (27) +#define KD_ENOTCONN (28) +#define KD_EPERM (33) +#define KD_ETIMEDOUT (36) +#define KD_EILSEQ (19) +#endif + +/** Map types from OMX standard types only here so interface is as generic as possible. */ +typedef OMX_U32 CPresult; +typedef char * CPstring; +typedef void * CPhandle; +typedef OMX_U32 CPuint; +typedef OMX_S32 CPint; +typedef char CPbyte; +typedef OMX_BOOL CPbool; + +/** enumeration of origin types used in the CP_PIPETYPE's Seek function + * @ingroup cp + */ +typedef enum CP_ORIGINTYPE { + CP_OriginBegin, + CP_OriginCur, + CP_OriginEnd, + CP_OriginKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + CP_OriginVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + CP_OriginMax = 0X7FFFFFFF +} CP_ORIGINTYPE; + +/** enumeration of contact access types used in the CP_PIPETYPE's Open function + * @ingroup cp + */ +typedef enum CP_ACCESSTYPE { + CP_AccessRead, + CP_AccessWrite, + CP_AccessReadWrite , + CP_AccessKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + CP_AccessVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + CP_AccessMax = 0X7FFFFFFF +} CP_ACCESSTYPE; + +/** enumeration of results returned by the CP_PIPETYPE's CheckAvailableBytes function + * @ingroup cp + */ +typedef enum CP_CHECKBYTESRESULTTYPE +{ + CP_CheckBytesOk, /**< There are at least the request number + of bytes available */ + CP_CheckBytesNotReady, /**< The pipe is still retrieving bytes + and presently lacks sufficient bytes. + Client will be called when they are + sufficient bytes are available. */ + CP_CheckBytesInsufficientBytes , /**< The pipe has retrieved all bytes + but those available are less than those + requested */ + CP_CheckBytesAtEndOfStream, /**< The pipe has reached the end of stream + and no more bytes are available. */ + CP_CheckBytesOutOfBuffers, /**< All read/write buffers are currently in use. */ + CP_CheckBytesKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + CP_CheckBytesVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + CP_CheckBytesMax = 0X7FFFFFFF +} CP_CHECKBYTESRESULTTYPE; + +/** enumeration of content pipe events sent to the client callback. + * @ingroup cp + */ +typedef enum CP_EVENTTYPE{ + CP_BytesAvailable, /** bytes requested in a CheckAvailableBytes call are now available*/ + CP_Overflow, /** enumeration of content pipe events sent to the client callback*/ + CP_PipeDisconnected , /** enumeration of content pipe events sent to the client callback*/ + CP_EventKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + CP_EventVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + CP_EventMax = 0X7FFFFFFF +} CP_EVENTTYPE; + +/** content pipe definition + * @ingroup cp + */ +typedef struct CP_PIPETYPE +{ + /** Open a content stream for reading or writing. */ + CPresult (*Open)( CPhandle* hContent, CPstring szURI, CP_ACCESSTYPE eAccess ); + + /** Close a content stream. */ + CPresult (*Close)( CPhandle hContent ); + + /** Create a content source and open it for writing. */ + CPresult (*Create)( CPhandle *hContent, CPstring szURI ); + + /** Check the that specified number of bytes are available for reading or writing (depending on access type).*/ + CPresult (*CheckAvailableBytes)( CPhandle hContent, CPuint nBytesRequested, CP_CHECKBYTESRESULTTYPE *eResult ); + + /** Seek to certain position in the content relative to the specified origin. */ + CPresult (*SetPosition)( CPhandle hContent, CPint nOffset, CP_ORIGINTYPE eOrigin); + + /** Retrieve the current position relative to the start of the content. */ + CPresult (*GetPosition)( CPhandle hContent, CPuint *pPosition); + + /** Retrieve data of the specified size from the content stream (advance content pointer by size of data). + Note: pipe client provides pointer. This function is appropriate for small high frequency reads. */ + CPresult (*Read)( CPhandle hContent, CPbyte *pData, CPuint nSize); + + /** Retrieve a buffer allocated by the pipe that contains the requested number of bytes. + Buffer contains the next block of bytes, as specified by nSize, of the content. nSize also + returns the size of the block actually read. Content pointer advances the by the returned size. + Note: pipe provides pointer. This function is appropriate for large reads. The client must call + ReleaseReadBuffer when done with buffer. + + In some cases the requested block may not reside in contiguous memory within the + pipe implementation. For instance if the pipe leverages a circular buffer then the requested + block may straddle the boundary of the circular buffer. By default a pipe implementation + performs a copy in this case to provide the block to the pipe client in one contiguous buffer. + If, however, the client sets bForbidCopy, then the pipe returns only those bytes preceding the memory + boundary. Here the client may retrieve the data in segments over successive calls. */ + CPresult (*ReadBuffer)( CPhandle hContent, CPbyte **ppBuffer, CPuint *nSize, CPbool bForbidCopy); + + /** Release a buffer obtained by ReadBuffer back to the pipe. */ + CPresult (*ReleaseReadBuffer)(CPhandle hContent, CPbyte *pBuffer); + + /** Write data of the specified size to the content (advance content pointer by size of data). + Note: pipe client provides pointer. This function is appropriate for small high frequency writes. */ + CPresult (*Write)( CPhandle hContent, CPbyte *data, CPuint nSize); + + /** Retrieve a buffer allocated by the pipe used to write data to the content. + Client will fill buffer with output data. Note: pipe provides pointer. This function is appropriate + for large writes. The client must call WriteBuffer when done it has filled the buffer with data.*/ + CPresult (*GetWriteBuffer)( CPhandle hContent, CPbyte **ppBuffer, CPuint nSize); + + /** Deliver a buffer obtained via GetWriteBuffer to the pipe. Pipe will write the + the contents of the buffer to content and advance content pointer by the size of the buffer */ + CPresult (*WriteBuffer)( CPhandle hContent, CPbyte *pBuffer, CPuint nFilledSize); + + /** Register a per-handle client callback with the content pipe. */ + CPresult (*RegisterCallback)( CPhandle hContent, CPresult (*ClientCallback)(CP_EVENTTYPE eEvent, CPuint iParam)); + +} CP_PIPETYPE; + +#endif + diff --git a/phonelibs/openmax/include/OMX_Core.h b/phonelibs/openmax/include/OMX_Core.h new file mode 100644 index 0000000000..52d211f0dc --- /dev/null +++ b/phonelibs/openmax/include/OMX_Core.h @@ -0,0 +1,1440 @@ +/* + * Copyright (c) 2008 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** OMX_Core.h - OpenMax IL version 1.1.2 + * The OMX_Core header file contains the definitions used by both the + * application and the component to access common items. + */ + +#ifndef OMX_Core_h +#define OMX_Core_h + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +/* Each OMX header shall include all required header files to allow the + * header to compile without errors. The includes below are required + * for this header file to compile successfully + */ + +#include + + +/** The OMX_COMMANDTYPE enumeration is used to specify the action in the + * OMX_SendCommand macro. + * @ingroup core + */ +typedef enum OMX_COMMANDTYPE +{ + OMX_CommandStateSet, /**< Change the component state */ + OMX_CommandFlush, /**< Flush the data queue(s) of a component */ + OMX_CommandPortDisable, /**< Disable a port on a component. */ + OMX_CommandPortEnable, /**< Enable a port on a component. */ + OMX_CommandMarkBuffer, /**< Mark a component/buffer for observation */ + OMX_CommandKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_CommandVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_CommandMax = 0X7FFFFFFF +} OMX_COMMANDTYPE; + + + +/** The OMX_STATETYPE enumeration is used to indicate or change the component + * state. This enumeration reflects the current state of the component when + * used with the OMX_GetState macro or becomes the parameter in a state change + * command when used with the OMX_SendCommand macro. + * + * The component will be in the Loaded state after the component is initially + * loaded into memory. In the Loaded state, the component is not allowed to + * allocate or hold resources other than to build it's internal parameter + * and configuration tables. The application will send one or more + * SetParameters/GetParameters and SetConfig/GetConfig commands to the + * component and the component will record each of these parameter and + * configuration changes for use later. When the application sends the + * Idle command, the component will acquire the resources needed for the + * specified configuration and will transition to the idle state if the + * allocation is successful. If the component cannot successfully + * transition to the idle state for any reason, the state of the component + * shall be fully rolled back to the Loaded state (e.g. all allocated + * resources shall be released). When the component receives the command + * to go to the Executing state, it shall begin processing buffers by + * sending all input buffers it holds to the application. While + * the component is in the Idle state, the application may also send the + * Pause command. If the component receives the pause command while in the + * Idle state, the component shall send all input buffers it holds to the + * application, but shall not begin processing buffers. This will allow the + * application to prefill buffers. + * + * @ingroup comp + */ + +typedef enum OMX_STATETYPE +{ + OMX_StateInvalid, /**< component has detected that it's internal data + structures are corrupted to the point that + it cannot determine it's state properly */ + OMX_StateLoaded, /**< component has been loaded but has not completed + initialization. The OMX_SetParameter macro + and the OMX_GetParameter macro are the only + valid macros allowed to be sent to the + component in this state. */ + OMX_StateIdle, /**< component initialization has been completed + successfully and the component is ready to + to start. */ + OMX_StateExecuting, /**< component has accepted the start command and + is processing data (if data is available) */ + OMX_StatePause, /**< component has received pause command */ + OMX_StateWaitForResources, /**< component is waiting for resources, either after + preemption or before it gets the resources requested. + See specification for complete details. */ + OMX_StateKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_StateVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_StateMax = 0X7FFFFFFF +} OMX_STATETYPE; + +/** The OMX_ERRORTYPE enumeration defines the standard OMX Errors. These + * errors should cover most of the common failure cases. However, + * vendors are free to add additional error messages of their own as + * long as they follow these rules: + * 1. Vendor error messages shall be in the range of 0x90000000 to + * 0x9000FFFF. + * 2. Vendor error messages shall be defined in a header file provided + * with the component. No error messages are allowed that are + * not defined. + */ +typedef enum OMX_ERRORTYPE +{ + OMX_ErrorNone = 0, + + /** There were insufficient resources to perform the requested operation */ + OMX_ErrorInsufficientResources = (OMX_S32) 0x80001000, + + /** There was an error, but the cause of the error could not be determined */ + OMX_ErrorUndefined = (OMX_S32) 0x80001001, + + /** The component name string was not valid */ + OMX_ErrorInvalidComponentName = (OMX_S32) 0x80001002, + + /** No component with the specified name string was found */ + OMX_ErrorComponentNotFound = (OMX_S32) 0x80001003, + + /** The component specified did not have a "OMX_ComponentInit" or + "OMX_ComponentDeInit entry point */ + OMX_ErrorInvalidComponent = (OMX_S32) 0x80001004, + + /** One or more parameters were not valid */ + OMX_ErrorBadParameter = (OMX_S32) 0x80001005, + + /** The requested function is not implemented */ + OMX_ErrorNotImplemented = (OMX_S32) 0x80001006, + + /** The buffer was emptied before the next buffer was ready */ + OMX_ErrorUnderflow = (OMX_S32) 0x80001007, + + /** The buffer was not available when it was needed */ + OMX_ErrorOverflow = (OMX_S32) 0x80001008, + + /** The hardware failed to respond as expected */ + OMX_ErrorHardware = (OMX_S32) 0x80001009, + + /** The component is in the state OMX_StateInvalid */ + OMX_ErrorInvalidState = (OMX_S32) 0x8000100A, + + /** Stream is found to be corrupt */ + OMX_ErrorStreamCorrupt = (OMX_S32) 0x8000100B, + + /** Ports being connected are not compatible */ + OMX_ErrorPortsNotCompatible = (OMX_S32) 0x8000100C, + + /** Resources allocated to an idle component have been + lost resulting in the component returning to the loaded state */ + OMX_ErrorResourcesLost = (OMX_S32) 0x8000100D, + + /** No more indicies can be enumerated */ + OMX_ErrorNoMore = (OMX_S32) 0x8000100E, + + /** The component detected a version mismatch */ + OMX_ErrorVersionMismatch = (OMX_S32) 0x8000100F, + + /** The component is not ready to return data at this time */ + OMX_ErrorNotReady = (OMX_S32) 0x80001010, + + /** There was a timeout that occurred */ + OMX_ErrorTimeout = (OMX_S32) 0x80001011, + + /** This error occurs when trying to transition into the state you are already in */ + OMX_ErrorSameState = (OMX_S32) 0x80001012, + + /** Resources allocated to an executing or paused component have been + preempted, causing the component to return to the idle state */ + OMX_ErrorResourcesPreempted = (OMX_S32) 0x80001013, + + /** A non-supplier port sends this error to the IL client (via the EventHandler callback) + during the allocation of buffers (on a transition from the LOADED to the IDLE state or + on a port restart) when it deems that it has waited an unusually long time for the supplier + to send it an allocated buffer via a UseBuffer call. */ + OMX_ErrorPortUnresponsiveDuringAllocation = (OMX_S32) 0x80001014, + + /** A non-supplier port sends this error to the IL client (via the EventHandler callback) + during the deallocation of buffers (on a transition from the IDLE to LOADED state or + on a port stop) when it deems that it has waited an unusually long time for the supplier + to request the deallocation of a buffer header via a FreeBuffer call. */ + OMX_ErrorPortUnresponsiveDuringDeallocation = (OMX_S32) 0x80001015, + + /** A supplier port sends this error to the IL client (via the EventHandler callback) + during the stopping of a port (either on a transition from the IDLE to LOADED + state or a port stop) when it deems that it has waited an unusually long time for + the non-supplier to return a buffer via an EmptyThisBuffer or FillThisBuffer call. */ + OMX_ErrorPortUnresponsiveDuringStop = (OMX_S32) 0x80001016, + + /** Attempting a state transtion that is not allowed */ + OMX_ErrorIncorrectStateTransition = (OMX_S32) 0x80001017, + + /* Attempting a command that is not allowed during the present state. */ + OMX_ErrorIncorrectStateOperation = (OMX_S32) 0x80001018, + + /** The values encapsulated in the parameter or config structure are not supported. */ + OMX_ErrorUnsupportedSetting = (OMX_S32) 0x80001019, + + /** The parameter or config indicated by the given index is not supported. */ + OMX_ErrorUnsupportedIndex = (OMX_S32) 0x8000101A, + + /** The port index supplied is incorrect. */ + OMX_ErrorBadPortIndex = (OMX_S32) 0x8000101B, + + /** The port has lost one or more of its buffers and it thus unpopulated. */ + OMX_ErrorPortUnpopulated = (OMX_S32) 0x8000101C, + + /** Component suspended due to temporary loss of resources */ + OMX_ErrorComponentSuspended = (OMX_S32) 0x8000101D, + + /** Component suspended due to an inability to acquire dynamic resources */ + OMX_ErrorDynamicResourcesUnavailable = (OMX_S32) 0x8000101E, + + /** When the macroblock error reporting is enabled the component returns new error + for every frame that has errors */ + OMX_ErrorMbErrorsInFrame = (OMX_S32) 0x8000101F, + + /** A component reports this error when it cannot parse or determine the format of an input stream. */ + OMX_ErrorFormatNotDetected = (OMX_S32) 0x80001020, + + /** The content open operation failed. */ + OMX_ErrorContentPipeOpenFailed = (OMX_S32) 0x80001021, + + /** The content creation operation failed. */ + OMX_ErrorContentPipeCreationFailed = (OMX_S32) 0x80001022, + + /** Separate table information is being used */ + OMX_ErrorSeperateTablesUsed = (OMX_S32) 0x80001023, + + /** Tunneling is unsupported by the component*/ + OMX_ErrorTunnelingUnsupported = (OMX_S32) 0x80001024, + + OMX_ErrorKhronosExtensions = (OMX_S32)0x8F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_ErrorVendorStartUnused = (OMX_S32)0x90000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_ErrorMax = 0x7FFFFFFF +} OMX_ERRORTYPE; + +/** @ingroup core */ +typedef OMX_ERRORTYPE (* OMX_COMPONENTINITTYPE)(OMX_IN OMX_HANDLETYPE hComponent); + +/** @ingroup core */ +typedef struct OMX_COMPONENTREGISTERTYPE +{ + const char * pName; /* Component name, 128 byte limit (including '\0') applies */ + OMX_COMPONENTINITTYPE pInitialize; /* Component instance initialization function */ +} OMX_COMPONENTREGISTERTYPE; + +/** @ingroup core */ +extern OMX_COMPONENTREGISTERTYPE OMX_ComponentRegistered[]; + +/** @ingroup rpm */ +typedef struct OMX_PRIORITYMGMTTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nGroupPriority; /**< Priority of the component group */ + OMX_U32 nGroupID; /**< ID of the component group */ +} OMX_PRIORITYMGMTTYPE; + +/* Component name and Role names are limited to 128 characters including the terminating '\0'. */ +#define OMX_MAX_STRINGNAME_SIZE 128 + +/** @ingroup comp */ +typedef struct OMX_PARAM_COMPONENTROLETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U8 cRole[OMX_MAX_STRINGNAME_SIZE]; /**< name of standard component which defines component role */ +} OMX_PARAM_COMPONENTROLETYPE; + +/** End of Stream Buffer Flag: + * + * A component sets EOS when it has no more data to emit on a particular + * output port. Thus an output port shall set EOS on the last buffer it + * emits. A component's determination of when an output port should + * cease sending data is implemenation specific. + * @ingroup buf + */ + +#define OMX_BUFFERFLAG_EOS 0x00000001 + +/** Start Time Buffer Flag: + * + * The source of a stream (e.g. a demux component) sets the STARTTIME + * flag on the buffer that contains the starting timestamp for the + * stream. The starting timestamp corresponds to the first data that + * should be displayed at startup or after a seek. + * The first timestamp of the stream is not necessarily the start time. + * For instance, in the case of a seek to a particular video frame, + * the target frame may be an interframe. Thus the first buffer of + * the stream will be the intra-frame preceding the target frame and + * the starttime will occur with the target frame (with any other + * required frames required to reconstruct the target intervening). + * + * The STARTTIME flag is directly associated with the buffer's + * timestamp ' thus its association to buffer data and its + * propagation is identical to the timestamp's. + * + * When a Sync Component client receives a buffer with the + * STARTTIME flag it shall perform a SetConfig on its sync port + * using OMX_ConfigTimeClientStartTime and passing the buffer's + * timestamp. + * + * @ingroup buf + */ + +#define OMX_BUFFERFLAG_STARTTIME 0x00000002 + + + +/** Decode Only Buffer Flag: + * + * The source of a stream (e.g. a demux component) sets the DECODEONLY + * flag on any buffer that should shall be decoded but should not be + * displayed. This flag is used, for instance, when a source seeks to + * a target interframe that requires the decode of frames preceding the + * target to facilitate the target's reconstruction. In this case the + * source would emit the frames preceding the target downstream + * but mark them as decode only. + * + * The DECODEONLY is associated with buffer data and propagated in a + * manner identical to the buffer timestamp. + * + * A component that renders data should ignore all buffers with + * the DECODEONLY flag set. + * + * @ingroup buf + */ + +#define OMX_BUFFERFLAG_DECODEONLY 0x00000004 + + +/* Data Corrupt Flag: This flag is set when the IL client believes the data in the associated buffer is corrupt + * @ingroup buf + */ + +#define OMX_BUFFERFLAG_DATACORRUPT 0x00000008 + +/* End of Frame: The buffer contains exactly one end of frame and no data + * occurs after the end of frame. This flag is an optional hint. The absence + * of this flag does not imply the absence of an end of frame within the buffer. + * @ingroup buf +*/ +#define OMX_BUFFERFLAG_ENDOFFRAME 0x00000010 + +/* Sync Frame Flag: This flag is set when the buffer content contains a coded sync frame ' + * a frame that has no dependency on any other frame information + * @ingroup buf + */ +#define OMX_BUFFERFLAG_SYNCFRAME 0x00000020 + +/* Extra data present flag: there is extra data appended to the data stream + * residing in the buffer + * @ingroup buf + */ +#define OMX_BUFFERFLAG_EXTRADATA 0x00000040 + +/** Codec Config Buffer Flag: +* OMX_BUFFERFLAG_CODECCONFIG is an optional flag that is set by an +* output port when all bytes in the buffer form part or all of a set of +* codec specific configuration data. Examples include SPS/PPS nal units +* for OMX_VIDEO_CodingAVC or AudioSpecificConfig data for +* OMX_AUDIO_CodingAAC. Any component that for a given stream sets +* OMX_BUFFERFLAG_CODECCONFIG shall not mix codec configuration bytes +* with frame data in the same buffer, and shall send all buffers +* containing codec configuration bytes before any buffers containing +* frame data that those configurations bytes describe. +* If the stream format for a particular codec has a frame specific +* header at the start of each frame, for example OMX_AUDIO_CodingMP3 or +* OMX_AUDIO_CodingAAC in ADTS mode, then these shall be presented as +* normal without setting OMX_BUFFERFLAG_CODECCONFIG. + * @ingroup buf + */ +#define OMX_BUFFERFLAG_CODECCONFIG 0x00000080 + +/* +* OMX_BUFFERFLAG_READONLY: This flag is set when a component emitting the +* buffer on an output port or the IL client wishes to identify the buffer +* payload contents to be read-only. An IL client or an input port +* shall not alter the contents of the buffer. This flag shall only be +* cleared by the originator of the buffer when the buffer is returned. +* For tunneled ports, the usage of this flag shall be allowed only if the +* components negotiated a read-only tunnel +*/ +#define OMX_BUFFERFLAG_READONLY 0x00000200 + +/** @ingroup buf */ +typedef struct OMX_BUFFERHEADERTYPE +{ + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U8* pBuffer; /**< Pointer to actual block of memory + that is acting as the buffer */ + OMX_U32 nAllocLen; /**< size of the buffer allocated, in bytes */ + OMX_U32 nFilledLen; /**< number of bytes currently in the + buffer */ + OMX_U32 nOffset; /**< start offset of valid data in bytes from + the start of the buffer */ + OMX_PTR pAppPrivate; /**< pointer to any data the application + wants to associate with this buffer */ + OMX_PTR pPlatformPrivate; /**< pointer to any data the platform + wants to associate with this buffer */ + OMX_PTR pInputPortPrivate; /**< pointer to any data the input port + wants to associate with this buffer */ + OMX_PTR pOutputPortPrivate; /**< pointer to any data the output port + wants to associate with this buffer */ + OMX_HANDLETYPE hMarkTargetComponent; /**< The component that will generate a + mark event upon processing this buffer. */ + OMX_PTR pMarkData; /**< Application specific data associated with + the mark sent on a mark event to disambiguate + this mark from others. */ + OMX_U32 nTickCount; /**< Optional entry that the component and + application can update with a tick count + when they access the component. This + value should be in microseconds. Since + this is a value relative to an arbitrary + starting point, this value cannot be used + to determine absolute time. This is an + optional entry and not all components + will update it.*/ + OMX_TICKS nTimeStamp; /**< Timestamp corresponding to the sample + starting at the first logical sample + boundary in the buffer. Timestamps of + successive samples within the buffer may + be inferred by adding the duration of the + of the preceding buffer to the timestamp + of the preceding buffer.*/ + OMX_U32 nFlags; /**< buffer specific flags */ + OMX_U32 nOutputPortIndex; /**< The index of the output port (if any) using + this buffer */ + OMX_U32 nInputPortIndex; /**< The index of the input port (if any) using + this buffer */ +} OMX_BUFFERHEADERTYPE; + +/** The OMX_EXTRADATATYPE enumeration is used to define the + * possible extra data payload types. + * NB: this enum is binary backwards compatible with the previous + * OMX_EXTRADATA_QUANT define. This should be replaced with + * OMX_ExtraDataQuantization. + */ +typedef enum OMX_EXTRADATATYPE +{ + OMX_ExtraDataNone = 0, /**< Indicates that no more extra data sections follow */ + OMX_ExtraDataQuantization, /**< The data payload contains quantization data */ + OMX_ExtraDataKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_ExtraDataVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_ExtraDataMax = 0x7FFFFFFF +} OMX_EXTRADATATYPE; + + +typedef struct OMX_OTHER_EXTRADATATYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_EXTRADATATYPE eType; /* Extra Data type */ + OMX_U32 nDataSize; /* Size of the supporting data to follow */ + OMX_U8 data[1]; /* Supporting data hint */ +} OMX_OTHER_EXTRADATATYPE; + +/** @ingroup comp */ +typedef struct OMX_PORT_PARAM_TYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPorts; /**< The number of ports for this component */ + OMX_U32 nStartPortNumber; /** first port number for this type of port */ +} OMX_PORT_PARAM_TYPE; + +/** @ingroup comp */ +typedef enum OMX_EVENTTYPE +{ + OMX_EventCmdComplete, /**< component has sucessfully completed a command */ + OMX_EventError, /**< component has detected an error condition */ + OMX_EventMark, /**< component has detected a buffer mark */ + OMX_EventPortSettingsChanged, /**< component is reported a port settings change */ + OMX_EventBufferFlag, /**< component has detected an EOS */ + OMX_EventResourcesAcquired, /**< component has been granted resources and is + automatically starting the state change from + OMX_StateWaitForResources to OMX_StateIdle. */ + OMX_EventComponentResumed, /**< Component resumed due to reacquisition of resources */ + OMX_EventDynamicResourcesAvailable, /**< Component has acquired previously unavailable dynamic resources */ + OMX_EventPortFormatDetected, /**< Component has detected a supported format. */ + OMX_EventKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_EventVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_EventMax = 0x7FFFFFFF +} OMX_EVENTTYPE; + +typedef struct OMX_CALLBACKTYPE +{ + /** The EventHandler method is used to notify the application when an + event of interest occurs. Events are defined in the OMX_EVENTTYPE + enumeration. Please see that enumeration for details of what will + be returned for each type of event. Callbacks should not return + an error to the component, so if an error occurs, the application + shall handle it internally. This is a blocking call. + + The application should return from this call within 5 msec to avoid + blocking the component for an excessively long period of time. + + @param hComponent + handle of the component to access. This is the component + handle returned by the call to the GetHandle function. + @param pAppData + pointer to an application defined value that was provided in the + pAppData parameter to the OMX_GetHandle method for the component. + This application defined value is provided so that the application + can have a component specific context when receiving the callback. + @param eEvent + Event that the component wants to notify the application about. + @param nData1 + nData will be the OMX_ERRORTYPE for an error event and will be + an OMX_COMMANDTYPE for a command complete event and OMX_INDEXTYPE for a OMX_PortSettingsChanged event. + @param nData2 + nData2 will hold further information related to the event. Can be OMX_STATETYPE for + a OMX_CommandStateSet command or port index for a OMX_PortSettingsChanged event. + Default value is 0 if not used. ) + @param pEventData + Pointer to additional event-specific data (see spec for meaning). + */ + + OMX_ERRORTYPE (*EventHandler)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_PTR pAppData, + OMX_IN OMX_EVENTTYPE eEvent, + OMX_IN OMX_U32 nData1, + OMX_IN OMX_U32 nData2, + OMX_IN OMX_PTR pEventData); + + /** The EmptyBufferDone method is used to return emptied buffers from an + input port back to the application for reuse. This is a blocking call + so the application should not attempt to refill the buffers during this + call, but should queue them and refill them in another thread. There + is no error return, so the application shall handle any errors generated + internally. + + The application should return from this call within 5 msec. + + @param hComponent + handle of the component to access. This is the component + handle returned by the call to the GetHandle function. + @param pAppData + pointer to an application defined value that was provided in the + pAppData parameter to the OMX_GetHandle method for the component. + This application defined value is provided so that the application + can have a component specific context when receiving the callback. + @param pBuffer + pointer to an OMX_BUFFERHEADERTYPE structure allocated with UseBuffer + or AllocateBuffer indicating the buffer that was emptied. + @ingroup buf + */ + OMX_ERRORTYPE (*EmptyBufferDone)( + OMX_IN OMX_HANDLETYPE hComponent, + OMX_IN OMX_PTR pAppData, + OMX_IN OMX_BUFFERHEADERTYPE* pBuffer); + + /** The FillBufferDone method is used to return filled buffers from an + output port back to the application for emptying and then reuse. + This is a blocking call so the application should not attempt to + empty the buffers during this call, but should queue the buffers + and empty them in another thread. There is no error return, so + the application shall handle any errors generated internally. The + application shall also update the buffer header to indicate the + number of bytes placed into the buffer. + + The application should return from this call within 5 msec. + + @param hComponent + handle of the component to access. This is the component + handle returned by the call to the GetHandle function. + @param pAppData + pointer to an application defined value that was provided in the + pAppData parameter to the OMX_GetHandle method for the component. + This application defined value is provided so that the application + can have a component specific context when receiving the callback. + @param pBuffer + pointer to an OMX_BUFFERHEADERTYPE structure allocated with UseBuffer + or AllocateBuffer indicating the buffer that was filled. + @ingroup buf + */ + OMX_ERRORTYPE (*FillBufferDone)( + OMX_OUT OMX_HANDLETYPE hComponent, + OMX_OUT OMX_PTR pAppData, + OMX_OUT OMX_BUFFERHEADERTYPE* pBuffer); + +} OMX_CALLBACKTYPE; + +/** The OMX_BUFFERSUPPLIERTYPE enumeration is used to dictate port supplier + preference when tunneling between two ports. + @ingroup tun buf +*/ +typedef enum OMX_BUFFERSUPPLIERTYPE +{ + OMX_BufferSupplyUnspecified = 0x0, /**< port supplying the buffers is unspecified, + or don't care */ + OMX_BufferSupplyInput, /**< input port supplies the buffers */ + OMX_BufferSupplyOutput, /**< output port supplies the buffers */ + OMX_BufferSupplyKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_BufferSupplyVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_BufferSupplyMax = 0x7FFFFFFF +} OMX_BUFFERSUPPLIERTYPE; + + +/** buffer supplier parameter + * @ingroup tun + */ +typedef struct OMX_PARAM_BUFFERSUPPLIERTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_BUFFERSUPPLIERTYPE eBufferSupplier; /**< buffer supplier */ +} OMX_PARAM_BUFFERSUPPLIERTYPE; + + +/**< indicates that buffers received by an input port of a tunnel + may not modify the data in the buffers + @ingroup tun + */ +#define OMX_PORTTUNNELFLAG_READONLY 0x00000001 + + +/** The OMX_TUNNELSETUPTYPE structure is used to pass data from an output + port to an input port as part the two ComponentTunnelRequest calls + resulting from a OMX_SetupTunnel call from the IL Client. + @ingroup tun + */ +typedef struct OMX_TUNNELSETUPTYPE +{ + OMX_U32 nTunnelFlags; /**< bit flags for tunneling */ + OMX_BUFFERSUPPLIERTYPE eSupplier; /**< supplier preference */ +} OMX_TUNNELSETUPTYPE; + +/* OMX Component headers is included to enable the core to use + macros for functions into the component for OMX release 1.0. + Developers should not access any structures or data from within + the component header directly */ +/* TO BE REMOVED - #include */ + +/** GetComponentVersion will return information about the component. + This is a blocking call. This macro will go directly from the + application to the component (via a core macro). The + component will return from this call within 5 msec. + @param [in] hComponent + handle of component to execute the command + @param [out] pComponentName + pointer to an empty string of length 128 bytes. The component + will write its name into this string. The name will be + terminated by a single zero byte. The name of a component will + be 127 bytes or less to leave room for the trailing zero byte. + An example of a valid component name is "OMX.ABC.ChannelMixer\0". + @param [out] pComponentVersion + pointer to an OMX Version structure that the component will fill + in. The component will fill in a value that indicates the + component version. NOTE: the component version is NOT the same + as the OMX Specification version (found in all structures). The + component version is defined by the vendor of the component and + its value is entirely up to the component vendor. + @param [out] pSpecVersion + pointer to an OMX Version structure that the component will fill + in. The SpecVersion is the version of the specification that the + component was built against. Please note that this value may or + may not match the structure's version. For example, if the + component was built against the 2.0 specification, but the + application (which creates the structure is built against the + 1.0 specification the versions would be different. + @param [out] pComponentUUID + pointer to the UUID of the component which will be filled in by + the component. The UUID is a unique identifier that is set at + RUN time for the component and is unique to each instantion of + the component. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp + */ +#define OMX_GetComponentVersion( \ + hComponent, \ + pComponentName, \ + pComponentVersion, \ + pSpecVersion, \ + pComponentUUID) \ + ((OMX_COMPONENTTYPE*)hComponent)->GetComponentVersion( \ + hComponent, \ + pComponentName, \ + pComponentVersion, \ + pSpecVersion, \ + pComponentUUID) /* Macro End */ + + +/** Send a command to the component. This call is a non-blocking call. + The component should check the parameters and then queue the command + to the component thread to be executed. The component thread shall + send the EventHandler() callback at the conclusion of the command. + This macro will go directly from the application to the component (via + a core macro). The component will return from this call within 5 msec. + + When the command is "OMX_CommandStateSet" the component will queue a + state transition to the new state idenfied in nParam. + + When the command is "OMX_CommandFlush", to flush a port's buffer queues, + the command will force the component to return all buffers NOT CURRENTLY + BEING PROCESSED to the application, in the order in which the buffers + were received. + + When the command is "OMX_CommandPortDisable" or + "OMX_CommandPortEnable", the component's port (given by the value of + nParam) will be stopped or restarted. + + When the command "OMX_CommandMarkBuffer" is used to mark a buffer, the + pCmdData will point to a OMX_MARKTYPE structure containing the component + handle of the component to examine the buffer chain for the mark. nParam1 + contains the index of the port on which the buffer mark is applied. + + Specification text for more details. + + @param [in] hComponent + handle of component to execute the command + @param [in] Cmd + Command for the component to execute + @param [in] nParam + Parameter for the command to be executed. When Cmd has the value + OMX_CommandStateSet, value is a member of OMX_STATETYPE. When Cmd has + the value OMX_CommandFlush, value of nParam indicates which port(s) + to flush. -1 is used to flush all ports a single port index will + only flush that port. When Cmd has the value "OMX_CommandPortDisable" + or "OMX_CommandPortEnable", the component's port is given by + the value of nParam. When Cmd has the value "OMX_CommandMarkBuffer" + the components pot is given by the value of nParam. + @param [in] pCmdData + Parameter pointing to the OMX_MARKTYPE structure when Cmd has the value + "OMX_CommandMarkBuffer". + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp + */ +#define OMX_SendCommand( \ + hComponent, \ + Cmd, \ + nParam, \ + pCmdData) \ + ((OMX_COMPONENTTYPE*)hComponent)->SendCommand( \ + hComponent, \ + Cmd, \ + nParam, \ + pCmdData) /* Macro End */ + + +/** The OMX_GetParameter macro will get one of the current parameter + settings from the component. This macro cannot only be invoked when + the component is in the OMX_StateInvalid state. The nParamIndex + parameter is used to indicate which structure is being requested from + the component. The application shall allocate the correct structure + and shall fill in the structure size and version information before + invoking this macro. When the parameter applies to a port, the + caller shall fill in the appropriate nPortIndex value indicating the + port on which the parameter applies. If the component has not had + any settings changed, then the component should return a set of + valid DEFAULT parameters for the component. This is a blocking + call. + + The component should return from this call within 20 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [in] nParamIndex + Index of the structure to be filled. This value is from the + OMX_INDEXTYPE enumeration. + @param [in,out] pComponentParameterStructure + Pointer to application allocated structure to be filled by the + component. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp + */ +#define OMX_GetParameter( \ + hComponent, \ + nParamIndex, \ + pComponentParameterStructure) \ + ((OMX_COMPONENTTYPE*)hComponent)->GetParameter( \ + hComponent, \ + nParamIndex, \ + pComponentParameterStructure) /* Macro End */ + + +/** The OMX_SetParameter macro will send an initialization parameter + structure to a component. Each structure shall be sent one at a time, + in a separate invocation of the macro. This macro can only be + invoked when the component is in the OMX_StateLoaded state, or the + port is disabled (when the parameter applies to a port). The + nParamIndex parameter is used to indicate which structure is being + passed to the component. The application shall allocate the + correct structure and shall fill in the structure size and version + information (as well as the actual data) before invoking this macro. + The application is free to dispose of this structure after the call + as the component is required to copy any data it shall retain. This + is a blocking call. + + The component should return from this call within 20 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [in] nIndex + Index of the structure to be sent. This value is from the + OMX_INDEXTYPE enumeration. + @param [in] pComponentParameterStructure + pointer to application allocated structure to be used for + initialization by the component. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp + */ +#define OMX_SetParameter( \ + hComponent, \ + nParamIndex, \ + pComponentParameterStructure) \ + ((OMX_COMPONENTTYPE*)hComponent)->SetParameter( \ + hComponent, \ + nParamIndex, \ + pComponentParameterStructure) /* Macro End */ + + +/** The OMX_GetConfig macro will get one of the configuration structures + from a component. This macro can be invoked anytime after the + component has been loaded. The nParamIndex call parameter is used to + indicate which structure is being requested from the component. The + application shall allocate the correct structure and shall fill in the + structure size and version information before invoking this macro. + If the component has not had this configuration parameter sent before, + then the component should return a set of valid DEFAULT values for the + component. This is a blocking call. + + The component should return from this call within 5 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [in] nIndex + Index of the structure to be filled. This value is from the + OMX_INDEXTYPE enumeration. + @param [in,out] pComponentConfigStructure + pointer to application allocated structure to be filled by the + component. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp +*/ +#define OMX_GetConfig( \ + hComponent, \ + nConfigIndex, \ + pComponentConfigStructure) \ + ((OMX_COMPONENTTYPE*)hComponent)->GetConfig( \ + hComponent, \ + nConfigIndex, \ + pComponentConfigStructure) /* Macro End */ + + +/** The OMX_SetConfig macro will send one of the configuration + structures to a component. Each structure shall be sent one at a time, + each in a separate invocation of the macro. This macro can be invoked + anytime after the component has been loaded. The application shall + allocate the correct structure and shall fill in the structure size + and version information (as well as the actual data) before invoking + this macro. The application is free to dispose of this structure after + the call as the component is required to copy any data it shall retain. + This is a blocking call. + + The component should return from this call within 5 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [in] nConfigIndex + Index of the structure to be sent. This value is from the + OMX_INDEXTYPE enumeration above. + @param [in] pComponentConfigStructure + pointer to application allocated structure to be used for + initialization by the component. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp + */ +#define OMX_SetConfig( \ + hComponent, \ + nConfigIndex, \ + pComponentConfigStructure) \ + ((OMX_COMPONENTTYPE*)hComponent)->SetConfig( \ + hComponent, \ + nConfigIndex, \ + pComponentConfigStructure) /* Macro End */ + + +/** The OMX_GetExtensionIndex macro will invoke a component to translate + a vendor specific configuration or parameter string into an OMX + structure index. There is no requirement for the vendor to support + this command for the indexes already found in the OMX_INDEXTYPE + enumeration (this is done to save space in small components). The + component shall support all vendor supplied extension indexes not found + in the master OMX_INDEXTYPE enumeration. This is a blocking call. + + The component should return from this call within 5 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the GetHandle function. + @param [in] cParameterName + OMX_STRING that shall be less than 128 characters long including + the trailing null byte. This is the string that will get + translated by the component into a configuration index. + @param [out] pIndexType + a pointer to a OMX_INDEXTYPE to receive the index value. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp + */ +#define OMX_GetExtensionIndex( \ + hComponent, \ + cParameterName, \ + pIndexType) \ + ((OMX_COMPONENTTYPE*)hComponent)->GetExtensionIndex( \ + hComponent, \ + cParameterName, \ + pIndexType) /* Macro End */ + + +/** The OMX_GetState macro will invoke the component to get the current + state of the component and place the state value into the location + pointed to by pState. + + The component should return from this call within 5 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [out] pState + pointer to the location to receive the state. The value returned + is one of the OMX_STATETYPE members + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp + */ +#define OMX_GetState( \ + hComponent, \ + pState) \ + ((OMX_COMPONENTTYPE*)hComponent)->GetState( \ + hComponent, \ + pState) /* Macro End */ + + +/** The OMX_UseBuffer macro will request that the component use + a buffer (and allocate its own buffer header) already allocated + by another component, or by the IL Client. This is a blocking + call. + + The component should return from this call within 20 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [out] ppBuffer + pointer to an OMX_BUFFERHEADERTYPE structure used to receive the + pointer to the buffer header + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp buf + */ + +#define OMX_UseBuffer( \ + hComponent, \ + ppBufferHdr, \ + nPortIndex, \ + pAppPrivate, \ + nSizeBytes, \ + pBuffer) \ + ((OMX_COMPONENTTYPE*)hComponent)->UseBuffer( \ + hComponent, \ + ppBufferHdr, \ + nPortIndex, \ + pAppPrivate, \ + nSizeBytes, \ + pBuffer) + + +/** The OMX_AllocateBuffer macro will request that the component allocate + a new buffer and buffer header. The component will allocate the + buffer and the buffer header and return a pointer to the buffer + header. This is a blocking call. + + The component should return from this call within 5 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [out] ppBuffer + pointer to an OMX_BUFFERHEADERTYPE structure used to receive + the pointer to the buffer header + @param [in] nPortIndex + nPortIndex is used to select the port on the component the buffer will + be used with. The port can be found by using the nPortIndex + value as an index into the Port Definition array of the component. + @param [in] pAppPrivate + pAppPrivate is used to initialize the pAppPrivate member of the + buffer header structure. + @param [in] nSizeBytes + size of the buffer to allocate. Used when bAllocateNew is true. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp buf + */ +#define OMX_AllocateBuffer( \ + hComponent, \ + ppBuffer, \ + nPortIndex, \ + pAppPrivate, \ + nSizeBytes) \ + ((OMX_COMPONENTTYPE*)hComponent)->AllocateBuffer( \ + hComponent, \ + ppBuffer, \ + nPortIndex, \ + pAppPrivate, \ + nSizeBytes) /* Macro End */ + + +/** The OMX_FreeBuffer macro will release a buffer header from the component + which was allocated using either OMX_AllocateBuffer or OMX_UseBuffer. If + the component allocated the buffer (see the OMX_UseBuffer macro) then + the component shall free the buffer and buffer header. This is a + blocking call. + + The component should return from this call within 20 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [in] nPortIndex + nPortIndex is used to select the port on the component the buffer will + be used with. + @param [in] pBuffer + pointer to an OMX_BUFFERHEADERTYPE structure allocated with UseBuffer + or AllocateBuffer. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp buf + */ +#define OMX_FreeBuffer( \ + hComponent, \ + nPortIndex, \ + pBuffer) \ + ((OMX_COMPONENTTYPE*)hComponent)->FreeBuffer( \ + hComponent, \ + nPortIndex, \ + pBuffer) /* Macro End */ + + +/** The OMX_EmptyThisBuffer macro will send a buffer full of data to an + input port of a component. The buffer will be emptied by the component + and returned to the application via the EmptyBufferDone call back. + This is a non-blocking call in that the component will record the buffer + and return immediately and then empty the buffer, later, at the proper + time. As expected, this macro may be invoked only while the component + is in the OMX_StateExecuting. If nPortIndex does not specify an input + port, the component shall return an error. + + The component should return from this call within 5 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [in] pBuffer + pointer to an OMX_BUFFERHEADERTYPE structure allocated with UseBuffer + or AllocateBuffer. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp buf + */ +#define OMX_EmptyThisBuffer( \ + hComponent, \ + pBuffer) \ + ((OMX_COMPONENTTYPE*)hComponent)->EmptyThisBuffer( \ + hComponent, \ + pBuffer) /* Macro End */ + + +/** The OMX_FillThisBuffer macro will send an empty buffer to an + output port of a component. The buffer will be filled by the component + and returned to the application via the FillBufferDone call back. + This is a non-blocking call in that the component will record the buffer + and return immediately and then fill the buffer, later, at the proper + time. As expected, this macro may be invoked only while the component + is in the OMX_ExecutingState. If nPortIndex does not specify an output + port, the component shall return an error. + + The component should return from this call within 5 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [in] pBuffer + pointer to an OMX_BUFFERHEADERTYPE structure allocated with UseBuffer + or AllocateBuffer. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp buf + */ +#define OMX_FillThisBuffer( \ + hComponent, \ + pBuffer) \ + ((OMX_COMPONENTTYPE*)hComponent)->FillThisBuffer( \ + hComponent, \ + pBuffer) /* Macro End */ + + + +/** The OMX_UseEGLImage macro will request that the component use + a EGLImage provided by EGL (and allocate its own buffer header) + This is a blocking call. + + The component should return from this call within 20 msec. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the OMX_GetHandle function. + @param [out] ppBuffer + pointer to an OMX_BUFFERHEADERTYPE structure used to receive the + pointer to the buffer header. Note that the memory location used + for this buffer is NOT visible to the IL Client. + @param [in] nPortIndex + nPortIndex is used to select the port on the component the buffer will + be used with. The port can be found by using the nPortIndex + value as an index into the Port Definition array of the component. + @param [in] pAppPrivate + pAppPrivate is used to initialize the pAppPrivate member of the + buffer header structure. + @param [in] eglImage + eglImage contains the handle of the EGLImage to use as a buffer on the + specified port. The component is expected to validate properties of + the EGLImage against the configuration of the port to ensure the component + can use the EGLImage as a buffer. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup comp buf + */ +#define OMX_UseEGLImage( \ + hComponent, \ + ppBufferHdr, \ + nPortIndex, \ + pAppPrivate, \ + eglImage) \ + ((OMX_COMPONENTTYPE*)hComponent)->UseEGLImage( \ + hComponent, \ + ppBufferHdr, \ + nPortIndex, \ + pAppPrivate, \ + eglImage) + +/** The OMX_Init method is used to initialize the OMX core. It shall be the + first call made into OMX and it should only be executed one time without + an interviening OMX_Deinit call. + + The core should return from this call within 20 msec. + + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup core + */ +OMX_API OMX_ERRORTYPE OMX_APIENTRY OMX_Init(void); + + +/** The OMX_Deinit method is used to deinitialize the OMX core. It shall be + the last call made into OMX. In the event that the core determines that + thare are components loaded when this call is made, the core may return + with an error rather than try to unload the components. + + The core should return from this call within 20 msec. + + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup core + */ +OMX_API OMX_ERRORTYPE OMX_APIENTRY OMX_Deinit(void); + + +/** The OMX_ComponentNameEnum method will enumerate through all the names of + recognised valid components in the system. This function is provided + as a means to detect all the components in the system run-time. There is + no strict ordering to the enumeration order of component names, although + each name will only be enumerated once. If the OMX core supports run-time + installation of new components, it is only requried to detect newly + installed components when the first call to enumerate component names + is made (i.e. when nIndex is 0x0). + + The core should return from this call in 20 msec. + + @param [out] cComponentName + pointer to a null terminated string with the component name. The + names of the components are strings less than 127 bytes in length + plus the trailing null for a maximum size of 128 bytes. An example + of a valid component name is "OMX.TI.AUDIO.DSP.MIXER\0". Names are + assigned by the vendor, but shall start with "OMX." and then have + the Vendor designation next. + @param [in] nNameLength + number of characters in the cComponentName string. With all + component name strings restricted to less than 128 characters + (including the trailing null) it is recomended that the caller + provide a input string for the cComponentName of 128 characters. + @param [in] nIndex + number containing the enumeration index for the component. + Multiple calls to OMX_ComponentNameEnum with increasing values + of nIndex will enumerate through the component names in the + system until OMX_ErrorNoMore is returned. The value of nIndex + is 0 to (N-1), where N is the number of valid installed components + in the system. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. When the value of nIndex exceeds the number of + components in the system minus 1, OMX_ErrorNoMore will be + returned. Otherwise the appropriate OMX error will be returned. + @ingroup core + */ +OMX_API OMX_ERRORTYPE OMX_APIENTRY OMX_ComponentNameEnum( + OMX_OUT OMX_STRING cComponentName, + OMX_IN OMX_U32 nNameLength, + OMX_IN OMX_U32 nIndex); + + +/** The OMX_GetHandle method will locate the component specified by the + component name given, load that component into memory and then invoke + the component's methods to create an instance of the component. + + The core should return from this call within 20 msec. + + @param [out] pHandle + pointer to an OMX_HANDLETYPE pointer to be filled in by this method. + @param [in] cComponentName + pointer to a null terminated string with the component name. The + names of the components are strings less than 127 bytes in length + plus the trailing null for a maximum size of 128 bytes. An example + of a valid component name is "OMX.TI.AUDIO.DSP.MIXER\0". Names are + assigned by the vendor, but shall start with "OMX." and then have + the Vendor designation next. + @param [in] pAppData + pointer to an application defined value that will be returned + during callbacks so that the application can identify the source + of the callback. + @param [in] pCallBacks + pointer to a OMX_CALLBACKTYPE structure that will be passed to the + component to initialize it with. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup core + */ +OMX_API OMX_ERRORTYPE OMX_APIENTRY OMX_GetHandle( + OMX_OUT OMX_HANDLETYPE* pHandle, + OMX_IN OMX_STRING cComponentName, + OMX_IN OMX_PTR pAppData, + OMX_IN OMX_CALLBACKTYPE* pCallBacks); + + +/** The OMX_FreeHandle method will free a handle allocated by the OMX_GetHandle + method. If the component reference count goes to zero, the component will + be unloaded from memory. + + The core should return from this call within 20 msec when the component is + in the OMX_StateLoaded state. + + @param [in] hComponent + Handle of the component to be accessed. This is the component + handle returned by the call to the GetHandle function. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + @ingroup core + */ +OMX_API OMX_ERRORTYPE OMX_APIENTRY OMX_FreeHandle( + OMX_IN OMX_HANDLETYPE hComponent); + + + +/** The OMX_SetupTunnel method will handle the necessary calls to the components + to setup the specified tunnel the two components. NOTE: This is + an actual method (not a #define macro). This method will make calls into + the component ComponentTunnelRequest method to do the actual tunnel + connection. + + The ComponentTunnelRequest method on both components will be called. + This method shall not be called unless the component is in the + OMX_StateLoaded state except when the ports used for the tunnel are + disabled. In this case, the component may be in the OMX_StateExecuting, + OMX_StatePause, or OMX_StateIdle states. + + The core should return from this call within 20 msec. + + @param [in] hOutput + Handle of the component to be accessed. Also this is the handle + of the component whose port, specified in the nPortOutput parameter + will be used the source for the tunnel. This is the component handle + returned by the call to the OMX_GetHandle function. There is a + requirement that hOutput be the source for the data when + tunelling (i.e. nPortOutput is an output port). If 0x0, the component + specified in hInput will have it's port specified in nPortInput + setup for communication with the application / IL client. + @param [in] nPortOutput + nPortOutput is used to select the source port on component to be + used in the tunnel. + @param [in] hInput + This is the component to setup the tunnel with. This is the handle + of the component whose port, specified in the nPortInput parameter + will be used the destination for the tunnel. This is the component handle + returned by the call to the OMX_GetHandle function. There is a + requirement that hInput be the destination for the data when + tunelling (i.e. nPortInut is an input port). If 0x0, the component + specified in hOutput will have it's port specified in nPortPOutput + setup for communication with the application / IL client. + @param [in] nPortInput + nPortInput is used to select the destination port on component to be + used in the tunnel. + @return OMX_ERRORTYPE + If the command successfully executes, the return code will be + OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. + When OMX_ErrorNotImplemented is returned, one or both components is + a non-interop component and does not support tunneling. + + On failure, the ports of both components are setup for communication + with the application / IL Client. + @ingroup core tun + */ +OMX_API OMX_ERRORTYPE OMX_APIENTRY OMX_SetupTunnel( + OMX_IN OMX_HANDLETYPE hOutput, + OMX_IN OMX_U32 nPortOutput, + OMX_IN OMX_HANDLETYPE hInput, + OMX_IN OMX_U32 nPortInput); + +/** @ingroup cp */ +OMX_API OMX_ERRORTYPE OMX_GetContentPipe( + OMX_OUT OMX_HANDLETYPE *hPipe, + OMX_IN OMX_STRING szURI); + +/** The OMX_GetComponentsOfRole method will return the number of components that support the given + role and (if the compNames field is non-NULL) the names of those components. The call will fail if + an insufficiently sized array of names is supplied. To ensure the array is sufficiently sized the + client should: + * first call this function with the compNames field NULL to determine the number of component names + * second call this function with the compNames field pointing to an array of names allocated + according to the number returned by the first call. + + The core should return from this call within 5 msec. + + @param [in] role + This is generic standard component name consisting only of component class + name and the type within that class (e.g. 'audio_decoder.aac'). + @param [inout] pNumComps + This is used both as input and output. + + If compNames is NULL, the input is ignored and the output specifies how many components support + the given role. + + If compNames is not NULL, on input it bounds the size of the input structure and + on output, it specifies the number of components string names listed within the compNames parameter. + @param [inout] compNames + If NULL this field is ignored. If non-NULL this points to an array of 128-byte strings which accepts + a list of the names of all physical components that implement the specified standard component name. + Each name is NULL terminated. numComps indicates the number of names. + @ingroup core + */ +OMX_API OMX_ERRORTYPE OMX_GetComponentsOfRole ( + OMX_IN OMX_STRING role, + OMX_INOUT OMX_U32 *pNumComps, + OMX_INOUT OMX_U8 **compNames); + +/** The OMX_GetRolesOfComponent method will return the number of roles supported by the given + component and (if the roles field is non-NULL) the names of those roles. The call will fail if + an insufficiently sized array of names is supplied. To ensure the array is sufficiently sized the + client should: + * first call this function with the roles field NULL to determine the number of role names + * second call this function with the roles field pointing to an array of names allocated + according to the number returned by the first call. + + The core should return from this call within 5 msec. + + @param [in] compName + This is the name of the component being queried about. + @param [inout] pNumRoles + This is used both as input and output. + + If roles is NULL, the input is ignored and the output specifies how many roles the component supports. + + If compNames is not NULL, on input it bounds the size of the input structure and + on output, it specifies the number of roles string names listed within the roles parameter. + @param [out] roles + If NULL this field is ignored. If non-NULL this points to an array of 128-byte strings + which accepts a list of the names of all standard components roles implemented on the + specified component name. numComps indicates the number of names. + @ingroup core + */ +OMX_API OMX_ERRORTYPE OMX_GetRolesOfComponent ( + OMX_IN OMX_STRING compName, + OMX_INOUT OMX_U32 *pNumRoles, + OMX_OUT OMX_U8 **roles); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif +/* File EOF */ + diff --git a/phonelibs/openmax/include/OMX_CoreExt.h b/phonelibs/openmax/include/OMX_CoreExt.h new file mode 100644 index 0000000000..3ec14b05f3 --- /dev/null +++ b/phonelibs/openmax/include/OMX_CoreExt.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2009 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** OMX_CoreExt.h - OpenMax IL version 1.1.2 + * The OMX_CoreExt header file contains extensions to the definitions used + * by both the application and the component to access common items. + */ + +#ifndef OMX_CoreExt_h +#define OMX_CoreExt_h + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* Each OMX header shall include all required header files to allow the + * header to compile without errors. The includes below are required + * for this header file to compile successfully + */ +#include + + +/** Event type extensions. */ +typedef enum OMX_EVENTEXTTYPE +{ + OMX_EventIndexSettingChanged = OMX_EventKhronosExtensions, /**< component signals the IL client of a change + in a param, config, or extension */ + OMX_EventExtMax = 0x7FFFFFFF +} OMX_EVENTEXTTYPE; + + +/** Enable or disable a callback event. */ +typedef struct OMX_CONFIG_CALLBACKREQUESTTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_INDEXTYPE nIndex; /**< the index the callback is requested for */ + OMX_BOOL bEnable; /**< enable (OMX_TRUE) or disable (OMX_FALSE) the callback */ +} OMX_CONFIG_CALLBACKREQUESTTYPE; + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OMX_CoreExt_h */ +/* File EOF */ diff --git a/phonelibs/openmax/include/OMX_IVCommon.h b/phonelibs/openmax/include/OMX_IVCommon.h new file mode 100644 index 0000000000..ec717565a0 --- /dev/null +++ b/phonelibs/openmax/include/OMX_IVCommon.h @@ -0,0 +1,933 @@ +/** + * Copyright (c) 2008 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** + * @file OMX_IVCommon.h - OpenMax IL version 1.1.2 + * The structures needed by Video and Image components to exchange + * parameters and configuration data with the components. + */ +#ifndef OMX_IVCommon_h +#define OMX_IVCommon_h + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * Each OMX header must include all required header files to allow the header + * to compile without errors. The includes below are required for this header + * file to compile successfully + */ + +#include + +/** @defgroup iv OpenMAX IL Imaging and Video Domain + * Common structures for OpenMAX IL Imaging and Video domains + * @{ + */ + + +/** + * Enumeration defining possible uncompressed image/video formats. + * + * ENUMS: + * Unused : Placeholder value when format is N/A + * Monochrome : black and white + * 8bitRGB332 : Red 7:5, Green 4:2, Blue 1:0 + * 12bitRGB444 : Red 11:8, Green 7:4, Blue 3:0 + * 16bitARGB4444 : Alpha 15:12, Red 11:8, Green 7:4, Blue 3:0 + * 16bitARGB1555 : Alpha 15, Red 14:10, Green 9:5, Blue 4:0 + * 16bitRGB565 : Red 15:11, Green 10:5, Blue 4:0 + * 16bitBGR565 : Blue 15:11, Green 10:5, Red 4:0 + * 18bitRGB666 : Red 17:12, Green 11:6, Blue 5:0 + * 18bitARGB1665 : Alpha 17, Red 16:11, Green 10:5, Blue 4:0 + * 19bitARGB1666 : Alpha 18, Red 17:12, Green 11:6, Blue 5:0 + * 24bitRGB888 : Red 24:16, Green 15:8, Blue 7:0 + * 24bitBGR888 : Blue 24:16, Green 15:8, Red 7:0 + * 24bitARGB1887 : Alpha 23, Red 22:15, Green 14:7, Blue 6:0 + * 25bitARGB1888 : Alpha 24, Red 23:16, Green 15:8, Blue 7:0 + * 32bitBGRA8888 : Blue 31:24, Green 23:16, Red 15:8, Alpha 7:0 + * 32bitARGB8888 : Alpha 31:24, Red 23:16, Green 15:8, Blue 7:0 + * YUV411Planar : U,Y are subsampled by a factor of 4 horizontally + * YUV411PackedPlanar : packed per payload in planar slices + * YUV420Planar : Three arrays Y,U,V. + * YUV420PackedPlanar : packed per payload in planar slices + * YUV420SemiPlanar : Two arrays, one is all Y, the other is U and V + * YUV422Planar : Three arrays Y,U,V. + * YUV422PackedPlanar : packed per payload in planar slices + * YUV422SemiPlanar : Two arrays, one is all Y, the other is U and V + * YCbYCr : Organized as 16bit YUYV (i.e. YCbYCr) + * YCrYCb : Organized as 16bit YVYU (i.e. YCrYCb) + * CbYCrY : Organized as 16bit UYVY (i.e. CbYCrY) + * CrYCbY : Organized as 16bit VYUY (i.e. CrYCbY) + * YUV444Interleaved : Each pixel contains equal parts YUV + * RawBayer8bit : SMIA camera output format + * RawBayer10bit : SMIA camera output format + * RawBayer8bitcompressed : SMIA camera output format + */ +typedef enum OMX_COLOR_FORMATTYPE { + OMX_COLOR_FormatUnused, + OMX_COLOR_FormatMonochrome, + OMX_COLOR_Format8bitRGB332, + OMX_COLOR_Format12bitRGB444, + OMX_COLOR_Format16bitARGB4444, + OMX_COLOR_Format16bitARGB1555, + OMX_COLOR_Format16bitRGB565, + OMX_COLOR_Format16bitBGR565, + OMX_COLOR_Format18bitRGB666, + OMX_COLOR_Format18bitARGB1665, + OMX_COLOR_Format19bitARGB1666, + OMX_COLOR_Format24bitRGB888, + OMX_COLOR_Format24bitBGR888, + OMX_COLOR_Format24bitARGB1887, + OMX_COLOR_Format25bitARGB1888, + OMX_COLOR_Format32bitBGRA8888, + OMX_COLOR_Format32bitARGB8888, + OMX_COLOR_FormatYUV411Planar, + OMX_COLOR_FormatYUV411PackedPlanar, + OMX_COLOR_FormatYUV420Planar, + OMX_COLOR_FormatYUV420PackedPlanar, + OMX_COLOR_FormatYUV420SemiPlanar, + OMX_COLOR_FormatYUV422Planar, + OMX_COLOR_FormatYUV422PackedPlanar, + OMX_COLOR_FormatYUV422SemiPlanar, + OMX_COLOR_FormatYCbYCr, + OMX_COLOR_FormatYCrYCb, + OMX_COLOR_FormatCbYCrY, + OMX_COLOR_FormatCrYCbY, + OMX_COLOR_FormatYUV444Interleaved, + OMX_COLOR_FormatRawBayer8bit, + OMX_COLOR_FormatRawBayer10bit, + OMX_COLOR_FormatRawBayer8bitcompressed, + OMX_COLOR_FormatL2, + OMX_COLOR_FormatL4, + OMX_COLOR_FormatL8, + OMX_COLOR_FormatL16, + OMX_COLOR_FormatL24, + OMX_COLOR_FormatL32, + OMX_COLOR_FormatYUV420PackedSemiPlanar, + OMX_COLOR_FormatYUV422PackedSemiPlanar, + OMX_COLOR_Format18BitBGR666, + OMX_COLOR_Format24BitARGB6666, + OMX_COLOR_Format24BitABGR6666, + OMX_COLOR_FormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_COLOR_FormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + /** + +/** @defgroup imaging OpenMAX IL Imaging Domain + * @ingroup iv + * Structures for OpenMAX IL Imaging domain + * @{ + */ + +/** + * Enumeration used to define the possible image compression coding. + */ +typedef enum OMX_IMAGE_CODINGTYPE { + OMX_IMAGE_CodingUnused, /**< Value when format is N/A */ + OMX_IMAGE_CodingAutoDetect, /**< Auto detection of image format */ + OMX_IMAGE_CodingJPEG, /**< JPEG/JFIF image format */ + OMX_IMAGE_CodingJPEG2K, /**< JPEG 2000 image format */ + OMX_IMAGE_CodingEXIF, /**< EXIF image format */ + OMX_IMAGE_CodingTIFF, /**< TIFF image format */ + OMX_IMAGE_CodingGIF, /**< Graphics image format */ + OMX_IMAGE_CodingPNG, /**< PNG image format */ + OMX_IMAGE_CodingLZW, /**< LZW image format */ + OMX_IMAGE_CodingBMP, /**< Windows Bitmap format */ + OMX_IMAGE_CodingKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_IMAGE_CodingVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_IMAGE_CodingMax = 0x7FFFFFFF +} OMX_IMAGE_CODINGTYPE; + + +/** + * Data structure used to define an image path. The number of image paths + * for input and output will vary by type of the image component. + * + * Input (aka Source) : Zero Inputs, one Output, + * Splitter : One Input, 2 or more Outputs, + * Processing Element : One Input, one output, + * Mixer : 2 or more inputs, one output, + * Output (aka Sink) : One Input, zero outputs. + * + * The PortDefinition structure is used to define all of the parameters + * necessary for the compliant component to setup an input or an output + * image path. If additional vendor specific data is required, it should + * be transmitted to the component using the CustomCommand function. + * Compliant components will prepopulate this structure with optimal + * values during the OMX_GetParameter() command. + * + * STRUCT MEMBERS: + * cMIMEType : MIME type of data for the port + * pNativeRender : Platform specific reference for a display if a + * sync, otherwise this field is 0 + * nFrameWidth : Width of frame to be used on port if + * uncompressed format is used. Use 0 for + * unknown, don't care or variable + * nFrameHeight : Height of frame to be used on port if + * uncompressed format is used. Use 0 for + * unknown, don't care or variable + * nStride : Number of bytes per span of an image (i.e. + * indicates the number of bytes to get from + * span N to span N+1, where negative stride + * indicates the image is bottom up + * nSliceHeight : Height used when encoding in slices + * bFlagErrorConcealment : Turns on error concealment if it is supported by + * the OMX component + * eCompressionFormat : Compression format used in this instance of + * the component. When OMX_IMAGE_CodingUnused is + * specified, eColorFormat is valid + * eColorFormat : Decompressed format used by this component + * pNativeWindow : Platform specific reference for a window object if a + * display sink , otherwise this field is 0x0. + */ +typedef struct OMX_IMAGE_PORTDEFINITIONTYPE { + OMX_STRING cMIMEType; + OMX_NATIVE_DEVICETYPE pNativeRender; + OMX_U32 nFrameWidth; + OMX_U32 nFrameHeight; + OMX_S32 nStride; + OMX_U32 nSliceHeight; + OMX_BOOL bFlagErrorConcealment; + OMX_IMAGE_CODINGTYPE eCompressionFormat; + OMX_COLOR_FORMATTYPE eColorFormat; + OMX_NATIVE_WINDOWTYPE pNativeWindow; +} OMX_IMAGE_PORTDEFINITIONTYPE; + + +/** + * Port format parameter. This structure is used to enumerate the various + * data input/output format supported by the port. + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Indicates which port to set + * nIndex : Indicates the enumeration index for the format from + * 0x0 to N-1 + * eCompressionFormat : Compression format used in this instance of the + * component. When OMX_IMAGE_CodingUnused is specified, + * eColorFormat is valid + * eColorFormat : Decompressed format used by this component + */ +typedef struct OMX_IMAGE_PARAM_PORTFORMATTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nIndex; + OMX_IMAGE_CODINGTYPE eCompressionFormat; + OMX_COLOR_FORMATTYPE eColorFormat; +} OMX_IMAGE_PARAM_PORTFORMATTYPE; + + +/** + * Flash control type + * + * ENUMS + * Torch : Flash forced constantly on + */ +typedef enum OMX_IMAGE_FLASHCONTROLTYPE { + OMX_IMAGE_FlashControlOn = 0, + OMX_IMAGE_FlashControlOff, + OMX_IMAGE_FlashControlAuto, + OMX_IMAGE_FlashControlRedEyeReduction, + OMX_IMAGE_FlashControlFillin, + OMX_IMAGE_FlashControlTorch, + OMX_IMAGE_FlashControlKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_IMAGE_FlashControlVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_IMAGE_FlashControlMax = 0x7FFFFFFF +} OMX_IMAGE_FLASHCONTROLTYPE; + + +/** + * Flash control configuration + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * eFlashControl : Flash control type + */ +typedef struct OMX_IMAGE_PARAM_FLASHCONTROLTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_IMAGE_FLASHCONTROLTYPE eFlashControl; +} OMX_IMAGE_PARAM_FLASHCONTROLTYPE; + + +/** + * Focus control type + */ +typedef enum OMX_IMAGE_FOCUSCONTROLTYPE { + OMX_IMAGE_FocusControlOn = 0, + OMX_IMAGE_FocusControlOff, + OMX_IMAGE_FocusControlAuto, + OMX_IMAGE_FocusControlAutoLock, + OMX_IMAGE_FocusControlKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_IMAGE_FocusControlVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_IMAGE_FocusControlMax = 0x7FFFFFFF +} OMX_IMAGE_FOCUSCONTROLTYPE; + + +/** + * Focus control configuration + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * eFocusControl : Focus control + * nFocusSteps : Focus can take on values from 0 mm to infinity. + * Interest is only in number of steps over this range. + * nFocusStepIndex : Current focus step index + */ +typedef struct OMX_IMAGE_CONFIG_FOCUSCONTROLTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_IMAGE_FOCUSCONTROLTYPE eFocusControl; + OMX_U32 nFocusSteps; + OMX_U32 nFocusStepIndex; +} OMX_IMAGE_CONFIG_FOCUSCONTROLTYPE; + + +/** + * Q Factor for JPEG compression, which controls the tradeoff between image + * quality and size. Q Factor provides a more simple means of controlling + * JPEG compression quality, without directly programming Quantization + * tables for chroma and luma + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * nQFactor : JPEG Q factor value in the range of 1-100. A factor of 1 + * produces the smallest, worst quality images, and a factor + * of 100 produces the largest, best quality images. A + * typical default is 75 for small good quality images + */ +typedef struct OMX_IMAGE_PARAM_QFACTORTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nQFactor; +} OMX_IMAGE_PARAM_QFACTORTYPE; + +/** + * Quantization table type + */ + +typedef enum OMX_IMAGE_QUANTIZATIONTABLETYPE { + OMX_IMAGE_QuantizationTableLuma = 0, + OMX_IMAGE_QuantizationTableChroma, + OMX_IMAGE_QuantizationTableChromaCb, + OMX_IMAGE_QuantizationTableChromaCr, + OMX_IMAGE_QuantizationTableKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_IMAGE_QuantizationTableVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_IMAGE_QuantizationTableMax = 0x7FFFFFFF +} OMX_IMAGE_QUANTIZATIONTABLETYPE; + +/** + * JPEG quantization tables are used to determine DCT compression for + * YUV data, as an alternative to specifying Q factor, providing exact + * control of compression + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * eQuantizationTable : Quantization table type + * nQuantizationMatrix[64] : JPEG quantization table of coefficients stored + * in increasing columns then by rows of data (i.e. + * row 1, ... row 8). Quantization values are in + * the range 0-255 and stored in linear order + * (i.e. the component will zig-zag the + * quantization table data if required internally) + */ +typedef struct OMX_IMAGE_PARAM_QUANTIZATIONTABLETYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_IMAGE_QUANTIZATIONTABLETYPE eQuantizationTable; + OMX_U8 nQuantizationMatrix[64]; +} OMX_IMAGE_PARAM_QUANTIZATIONTABLETYPE; + + +/** + * Huffman table type, the same Huffman table is applied for chroma and + * luma component + */ +typedef enum OMX_IMAGE_HUFFMANTABLETYPE { + OMX_IMAGE_HuffmanTableAC = 0, + OMX_IMAGE_HuffmanTableDC, + OMX_IMAGE_HuffmanTableACLuma, + OMX_IMAGE_HuffmanTableACChroma, + OMX_IMAGE_HuffmanTableDCLuma, + OMX_IMAGE_HuffmanTableDCChroma, + OMX_IMAGE_HuffmanTableKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_IMAGE_HuffmanTableVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_IMAGE_HuffmanTableMax = 0x7FFFFFFF +} OMX_IMAGE_HUFFMANTABLETYPE; + +/** + * JPEG Huffman table + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * eHuffmanTable : Huffman table type + * nNumberOfHuffmanCodeOfLength[16] : 0-16, number of Huffman codes of each + * possible length + * nHuffmanTable[256] : 0-255, the size used for AC and DC + * HuffmanTable are 16 and 162 + */ +typedef struct OMX_IMAGE_PARAM_HUFFMANTTABLETYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_IMAGE_HUFFMANTABLETYPE eHuffmanTable; + OMX_U8 nNumberOfHuffmanCodeOfLength[16]; + OMX_U8 nHuffmanTable[256]; +}OMX_IMAGE_PARAM_HUFFMANTTABLETYPE; + +/** @} */ +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif +/* File EOF */ diff --git a/phonelibs/openmax/include/OMX_Index.h b/phonelibs/openmax/include/OMX_Index.h new file mode 100644 index 0000000000..a1f17487d3 --- /dev/null +++ b/phonelibs/openmax/include/OMX_Index.h @@ -0,0 +1,259 @@ +/* + * Copyright (c) 2008 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** @file OMX_Index.h - OpenMax IL version 1.1.2 + * The OMX_Index header file contains the definitions for both applications + * and components . + */ + + +#ifndef OMX_Index_h +#define OMX_Index_h + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +/* Each OMX header must include all required header files to allow the + * header to compile without errors. The includes below are required + * for this header file to compile successfully + */ +#include + + +/** The OMX_INDEXTYPE enumeration is used to select a structure when either + * getting or setting parameters and/or configuration data. Each entry in + * this enumeration maps to an OMX specified structure. When the + * OMX_GetParameter, OMX_SetParameter, OMX_GetConfig or OMX_SetConfig methods + * are used, the second parameter will always be an entry from this enumeration + * and the third entry will be the structure shown in the comments for the entry. + * For example, if the application is initializing a cropping function, the + * OMX_SetConfig command would have OMX_IndexConfigCommonInputCrop as the second parameter + * and would send a pointer to an initialized OMX_RECTTYPE structure as the + * third parameter. + * + * The enumeration entries named with the OMX_Config prefix are sent using + * the OMX_SetConfig command and the enumeration entries named with the + * OMX_PARAM_ prefix are sent using the OMX_SetParameter command. + */ +typedef enum OMX_INDEXTYPE { + + OMX_IndexComponentStartUnused = 0x01000000, + OMX_IndexParamPriorityMgmt, /**< reference: OMX_PRIORITYMGMTTYPE */ + OMX_IndexParamAudioInit, /**< reference: OMX_PORT_PARAM_TYPE */ + OMX_IndexParamImageInit, /**< reference: OMX_PORT_PARAM_TYPE */ + OMX_IndexParamVideoInit, /**< reference: OMX_PORT_PARAM_TYPE */ + OMX_IndexParamOtherInit, /**< reference: OMX_PORT_PARAM_TYPE */ + OMX_IndexParamNumAvailableStreams, /**< reference: OMX_PARAM_U32TYPE */ + OMX_IndexParamActiveStream, /**< reference: OMX_PARAM_U32TYPE */ + OMX_IndexParamSuspensionPolicy, /**< reference: OMX_PARAM_SUSPENSIONPOLICYTYPE */ + OMX_IndexParamComponentSuspended, /**< reference: OMX_PARAM_SUSPENSIONTYPE */ + OMX_IndexConfigCapturing, /**< reference: OMX_CONFIG_BOOLEANTYPE */ + OMX_IndexConfigCaptureMode, /**< reference: OMX_CONFIG_CAPTUREMODETYPE */ + OMX_IndexAutoPauseAfterCapture, /**< reference: OMX_CONFIG_BOOLEANTYPE */ + OMX_IndexParamContentURI, /**< reference: OMX_PARAM_CONTENTURITYPE */ + OMX_IndexParamCustomContentPipe, /**< reference: OMX_PARAM_CONTENTPIPETYPE */ + OMX_IndexParamDisableResourceConcealment, /**< reference: OMX_RESOURCECONCEALMENTTYPE */ + OMX_IndexConfigMetadataItemCount, /**< reference: OMX_CONFIG_METADATAITEMCOUNTTYPE */ + OMX_IndexConfigContainerNodeCount, /**< reference: OMX_CONFIG_CONTAINERNODECOUNTTYPE */ + OMX_IndexConfigMetadataItem, /**< reference: OMX_CONFIG_METADATAITEMTYPE */ + OMX_IndexConfigCounterNodeID, /**< reference: OMX_CONFIG_CONTAINERNODEIDTYPE */ + OMX_IndexParamMetadataFilterType, /**< reference: OMX_PARAM_METADATAFILTERTYPE */ + OMX_IndexParamMetadataKeyFilter, /**< reference: OMX_PARAM_METADATAFILTERTYPE */ + OMX_IndexConfigPriorityMgmt, /**< reference: OMX_PRIORITYMGMTTYPE */ + OMX_IndexParamStandardComponentRole, /**< reference: OMX_PARAM_COMPONENTROLETYPE */ + + OMX_IndexPortStartUnused = 0x02000000, + OMX_IndexParamPortDefinition, /**< reference: OMX_PARAM_PORTDEFINITIONTYPE */ + OMX_IndexParamCompBufferSupplier, /**< reference: OMX_PARAM_BUFFERSUPPLIERTYPE */ + OMX_IndexReservedStartUnused = 0x03000000, + + /* Audio parameters and configurations */ + OMX_IndexAudioStartUnused = 0x04000000, + OMX_IndexParamAudioPortFormat, /**< reference: OMX_AUDIO_PARAM_PORTFORMATTYPE */ + OMX_IndexParamAudioPcm, /**< reference: OMX_AUDIO_PARAM_PCMMODETYPE */ + OMX_IndexParamAudioAac, /**< reference: OMX_AUDIO_PARAM_AACPROFILETYPE */ + OMX_IndexParamAudioRa, /**< reference: OMX_AUDIO_PARAM_RATYPE */ + OMX_IndexParamAudioMp3, /**< reference: OMX_AUDIO_PARAM_MP3TYPE */ + OMX_IndexParamAudioAdpcm, /**< reference: OMX_AUDIO_PARAM_ADPCMTYPE */ + OMX_IndexParamAudioG723, /**< reference: OMX_AUDIO_PARAM_G723TYPE */ + OMX_IndexParamAudioG729, /**< reference: OMX_AUDIO_PARAM_G729TYPE */ + OMX_IndexParamAudioAmr, /**< reference: OMX_AUDIO_PARAM_AMRTYPE */ + OMX_IndexParamAudioWma, /**< reference: OMX_AUDIO_PARAM_WMATYPE */ + OMX_IndexParamAudioSbc, /**< reference: OMX_AUDIO_PARAM_SBCTYPE */ + OMX_IndexParamAudioMidi, /**< reference: OMX_AUDIO_PARAM_MIDITYPE */ + OMX_IndexParamAudioGsm_FR, /**< reference: OMX_AUDIO_PARAM_GSMFRTYPE */ + OMX_IndexParamAudioMidiLoadUserSound, /**< reference: OMX_AUDIO_PARAM_MIDILOADUSERSOUNDTYPE */ + OMX_IndexParamAudioG726, /**< reference: OMX_AUDIO_PARAM_G726TYPE */ + OMX_IndexParamAudioGsm_EFR, /**< reference: OMX_AUDIO_PARAM_GSMEFRTYPE */ + OMX_IndexParamAudioGsm_HR, /**< reference: OMX_AUDIO_PARAM_GSMHRTYPE */ + OMX_IndexParamAudioPdc_FR, /**< reference: OMX_AUDIO_PARAM_PDCFRTYPE */ + OMX_IndexParamAudioPdc_EFR, /**< reference: OMX_AUDIO_PARAM_PDCEFRTYPE */ + OMX_IndexParamAudioPdc_HR, /**< reference: OMX_AUDIO_PARAM_PDCHRTYPE */ + OMX_IndexParamAudioTdma_FR, /**< reference: OMX_AUDIO_PARAM_TDMAFRTYPE */ + OMX_IndexParamAudioTdma_EFR, /**< reference: OMX_AUDIO_PARAM_TDMAEFRTYPE */ + OMX_IndexParamAudioQcelp8, /**< reference: OMX_AUDIO_PARAM_QCELP8TYPE */ + OMX_IndexParamAudioQcelp13, /**< reference: OMX_AUDIO_PARAM_QCELP13TYPE */ + OMX_IndexParamAudioEvrc, /**< reference: OMX_AUDIO_PARAM_EVRCTYPE */ + OMX_IndexParamAudioSmv, /**< reference: OMX_AUDIO_PARAM_SMVTYPE */ + OMX_IndexParamAudioVorbis, /**< reference: OMX_AUDIO_PARAM_VORBISTYPE */ + + OMX_IndexConfigAudioMidiImmediateEvent, /**< reference: OMX_AUDIO_CONFIG_MIDIIMMEDIATEEVENTTYPE */ + OMX_IndexConfigAudioMidiControl, /**< reference: OMX_AUDIO_CONFIG_MIDICONTROLTYPE */ + OMX_IndexConfigAudioMidiSoundBankProgram, /**< reference: OMX_AUDIO_CONFIG_MIDISOUNDBANKPROGRAMTYPE */ + OMX_IndexConfigAudioMidiStatus, /**< reference: OMX_AUDIO_CONFIG_MIDISTATUSTYPE */ + OMX_IndexConfigAudioMidiMetaEvent, /**< reference: OMX_AUDIO_CONFIG_MIDIMETAEVENTTYPE */ + OMX_IndexConfigAudioMidiMetaEventData, /**< reference: OMX_AUDIO_CONFIG_MIDIMETAEVENTDATATYPE */ + OMX_IndexConfigAudioVolume, /**< reference: OMX_AUDIO_CONFIG_VOLUMETYPE */ + OMX_IndexConfigAudioBalance, /**< reference: OMX_AUDIO_CONFIG_BALANCETYPE */ + OMX_IndexConfigAudioChannelMute, /**< reference: OMX_AUDIO_CONFIG_CHANNELMUTETYPE */ + OMX_IndexConfigAudioMute, /**< reference: OMX_AUDIO_CONFIG_MUTETYPE */ + OMX_IndexConfigAudioLoudness, /**< reference: OMX_AUDIO_CONFIG_LOUDNESSTYPE */ + OMX_IndexConfigAudioEchoCancelation, /**< reference: OMX_AUDIO_CONFIG_ECHOCANCELATIONTYPE */ + OMX_IndexConfigAudioNoiseReduction, /**< reference: OMX_AUDIO_CONFIG_NOISEREDUCTIONTYPE */ + OMX_IndexConfigAudioBass, /**< reference: OMX_AUDIO_CONFIG_BASSTYPE */ + OMX_IndexConfigAudioTreble, /**< reference: OMX_AUDIO_CONFIG_TREBLETYPE */ + OMX_IndexConfigAudioStereoWidening, /**< reference: OMX_AUDIO_CONFIG_STEREOWIDENINGTYPE */ + OMX_IndexConfigAudioChorus, /**< reference: OMX_AUDIO_CONFIG_CHORUSTYPE */ + OMX_IndexConfigAudioEqualizer, /**< reference: OMX_AUDIO_CONFIG_EQUALIZERTYPE */ + OMX_IndexConfigAudioReverberation, /**< reference: OMX_AUDIO_CONFIG_REVERBERATIONTYPE */ + OMX_IndexConfigAudioChannelVolume, /**< reference: OMX_AUDIO_CONFIG_CHANNELVOLUMETYPE */ + + /* Image specific parameters and configurations */ + OMX_IndexImageStartUnused = 0x05000000, + OMX_IndexParamImagePortFormat, /**< reference: OMX_IMAGE_PARAM_PORTFORMATTYPE */ + OMX_IndexParamFlashControl, /**< reference: OMX_IMAGE_PARAM_FLASHCONTROLTYPE */ + OMX_IndexConfigFocusControl, /**< reference: OMX_IMAGE_CONFIG_FOCUSCONTROLTYPE */ + OMX_IndexParamQFactor, /**< reference: OMX_IMAGE_PARAM_QFACTORTYPE */ + OMX_IndexParamQuantizationTable, /**< reference: OMX_IMAGE_PARAM_QUANTIZATIONTABLETYPE */ + OMX_IndexParamHuffmanTable, /**< reference: OMX_IMAGE_PARAM_HUFFMANTTABLETYPE */ + OMX_IndexConfigFlashControl, /**< reference: OMX_IMAGE_PARAM_FLASHCONTROLTYPE */ + + /* Video specific parameters and configurations */ + OMX_IndexVideoStartUnused = 0x06000000, + OMX_IndexParamVideoPortFormat, /**< reference: OMX_VIDEO_PARAM_PORTFORMATTYPE */ + OMX_IndexParamVideoQuantization, /**< reference: OMX_VIDEO_PARAM_QUANTIZATIONTYPE */ + OMX_IndexParamVideoFastUpdate, /**< reference: OMX_VIDEO_PARAM_VIDEOFASTUPDATETYPE */ + OMX_IndexParamVideoBitrate, /**< reference: OMX_VIDEO_PARAM_BITRATETYPE */ + OMX_IndexParamVideoMotionVector, /**< reference: OMX_VIDEO_PARAM_MOTIONVECTORTYPE */ + OMX_IndexParamVideoIntraRefresh, /**< reference: OMX_VIDEO_PARAM_INTRAREFRESHTYPE */ + OMX_IndexParamVideoErrorCorrection, /**< reference: OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE */ + OMX_IndexParamVideoVBSMC, /**< reference: OMX_VIDEO_PARAM_VBSMCTYPE */ + OMX_IndexParamVideoMpeg2, /**< reference: OMX_VIDEO_PARAM_MPEG2TYPE */ + OMX_IndexParamVideoMpeg4, /**< reference: OMX_VIDEO_PARAM_MPEG4TYPE */ + OMX_IndexParamVideoWmv, /**< reference: OMX_VIDEO_PARAM_WMVTYPE */ + OMX_IndexParamVideoRv, /**< reference: OMX_VIDEO_PARAM_RVTYPE */ + OMX_IndexParamVideoAvc, /**< reference: OMX_VIDEO_PARAM_AVCTYPE */ + OMX_IndexParamVideoH263, /**< reference: OMX_VIDEO_PARAM_H263TYPE */ + OMX_IndexParamVideoProfileLevelQuerySupported, /**< reference: OMX_VIDEO_PARAM_PROFILELEVELTYPE */ + OMX_IndexParamVideoProfileLevelCurrent, /**< reference: OMX_VIDEO_PARAM_PROFILELEVELTYPE */ + OMX_IndexConfigVideoBitrate, /**< reference: OMX_VIDEO_CONFIG_BITRATETYPE */ + OMX_IndexConfigVideoFramerate, /**< reference: OMX_CONFIG_FRAMERATETYPE */ + OMX_IndexConfigVideoIntraVOPRefresh, /**< reference: OMX_CONFIG_INTRAREFRESHVOPTYPE */ + OMX_IndexConfigVideoIntraMBRefresh, /**< reference: OMX_CONFIG_MACROBLOCKERRORMAPTYPE */ + OMX_IndexConfigVideoMBErrorReporting, /**< reference: OMX_CONFIG_MBERRORREPORTINGTYPE */ + OMX_IndexParamVideoMacroblocksPerFrame, /**< reference: OMX_PARAM_MACROBLOCKSTYPE */ + OMX_IndexConfigVideoMacroBlockErrorMap, /**< reference: OMX_CONFIG_MACROBLOCKERRORMAPTYPE */ + OMX_IndexParamVideoSliceFMO, /**< reference: OMX_VIDEO_PARAM_AVCSLICEFMO */ + OMX_IndexConfigVideoAVCIntraPeriod, /**< reference: OMX_VIDEO_CONFIG_AVCINTRAPERIOD */ + OMX_IndexConfigVideoNalSize, /**< reference: OMX_VIDEO_CONFIG_NALSIZE */ + OMX_IndexConfigCommonDeinterlace, /**< reference: OMX_VIDEO_CONFIG_DEINTERLACE */ + + /* Image & Video common Configurations */ + OMX_IndexCommonStartUnused = 0x07000000, + OMX_IndexParamCommonDeblocking, /**< reference: OMX_PARAM_DEBLOCKINGTYPE */ + OMX_IndexParamCommonSensorMode, /**< reference: OMX_PARAM_SENSORMODETYPE */ + OMX_IndexParamCommonInterleave, /**< reference: OMX_PARAM_INTERLEAVETYPE */ + OMX_IndexConfigCommonColorFormatConversion, /**< reference: OMX_CONFIG_COLORCONVERSIONTYPE */ + OMX_IndexConfigCommonScale, /**< reference: OMX_CONFIG_SCALEFACTORTYPE */ + OMX_IndexConfigCommonImageFilter, /**< reference: OMX_CONFIG_IMAGEFILTERTYPE */ + OMX_IndexConfigCommonColorEnhancement, /**< reference: OMX_CONFIG_COLORENHANCEMENTTYPE */ + OMX_IndexConfigCommonColorKey, /**< reference: OMX_CONFIG_COLORKEYTYPE */ + OMX_IndexConfigCommonColorBlend, /**< reference: OMX_CONFIG_COLORBLENDTYPE */ + OMX_IndexConfigCommonFrameStabilisation,/**< reference: OMX_CONFIG_FRAMESTABTYPE */ + OMX_IndexConfigCommonRotate, /**< reference: OMX_CONFIG_ROTATIONTYPE */ + OMX_IndexConfigCommonMirror, /**< reference: OMX_CONFIG_MIRRORTYPE */ + OMX_IndexConfigCommonOutputPosition, /**< reference: OMX_CONFIG_POINTTYPE */ + OMX_IndexConfigCommonInputCrop, /**< reference: OMX_CONFIG_RECTTYPE */ + OMX_IndexConfigCommonOutputCrop, /**< reference: OMX_CONFIG_RECTTYPE */ + OMX_IndexConfigCommonDigitalZoom, /**< reference: OMX_CONFIG_SCALEFACTORTYPE */ + OMX_IndexConfigCommonOpticalZoom, /**< reference: OMX_CONFIG_SCALEFACTORTYPE*/ + OMX_IndexConfigCommonWhiteBalance, /**< reference: OMX_CONFIG_WHITEBALCONTROLTYPE */ + OMX_IndexConfigCommonExposure, /**< reference: OMX_CONFIG_EXPOSURECONTROLTYPE */ + OMX_IndexConfigCommonContrast, /**< reference: OMX_CONFIG_CONTRASTTYPE */ + OMX_IndexConfigCommonBrightness, /**< reference: OMX_CONFIG_BRIGHTNESSTYPE */ + OMX_IndexConfigCommonBacklight, /**< reference: OMX_CONFIG_BACKLIGHTTYPE */ + OMX_IndexConfigCommonGamma, /**< reference: OMX_CONFIG_GAMMATYPE */ + OMX_IndexConfigCommonSaturation, /**< reference: OMX_CONFIG_SATURATIONTYPE */ + OMX_IndexConfigCommonLightness, /**< reference: OMX_CONFIG_LIGHTNESSTYPE */ + OMX_IndexConfigCommonExclusionRect, /**< reference: OMX_CONFIG_RECTTYPE */ + OMX_IndexConfigCommonDithering, /**< reference: OMX_CONFIG_DITHERTYPE */ + OMX_IndexConfigCommonPlaneBlend, /**< reference: OMX_CONFIG_PLANEBLENDTYPE */ + OMX_IndexConfigCommonExposureValue, /**< reference: OMX_CONFIG_EXPOSUREVALUETYPE */ + OMX_IndexConfigCommonOutputSize, /**< reference: OMX_FRAMESIZETYPE */ + OMX_IndexParamCommonExtraQuantData, /**< reference: OMX_OTHER_EXTRADATATYPE */ + OMX_IndexConfigCommonFocusRegion, /**< reference: OMX_CONFIG_FOCUSREGIONTYPE */ + OMX_IndexConfigCommonFocusStatus, /**< reference: OMX_PARAM_FOCUSSTATUSTYPE */ + OMX_IndexConfigCommonTransitionEffect, /**< reference: OMX_CONFIG_TRANSITIONEFFECTTYPE */ + + /* Reserved Configuration range */ + OMX_IndexOtherStartUnused = 0x08000000, + OMX_IndexParamOtherPortFormat, /**< reference: OMX_OTHER_PARAM_PORTFORMATTYPE */ + OMX_IndexConfigOtherPower, /**< reference: OMX_OTHER_CONFIG_POWERTYPE */ + OMX_IndexConfigOtherStats, /**< reference: OMX_OTHER_CONFIG_STATSTYPE */ + + + /* Reserved Time range */ + OMX_IndexTimeStartUnused = 0x09000000, + OMX_IndexConfigTimeScale, /**< reference: OMX_TIME_CONFIG_SCALETYPE */ + OMX_IndexConfigTimeClockState, /**< reference: OMX_TIME_CONFIG_CLOCKSTATETYPE */ + OMX_IndexConfigTimeActiveRefClock, /**< reference: OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE */ + OMX_IndexConfigTimeCurrentMediaTime, /**< reference: OMX_TIME_CONFIG_TIMESTAMPTYPE (read only) */ + OMX_IndexConfigTimeCurrentWallTime, /**< reference: OMX_TIME_CONFIG_TIMESTAMPTYPE (read only) */ + OMX_IndexConfigTimeCurrentAudioReference, /**< reference: OMX_TIME_CONFIG_TIMESTAMPTYPE (write only) */ + OMX_IndexConfigTimeCurrentVideoReference, /**< reference: OMX_TIME_CONFIG_TIMESTAMPTYPE (write only) */ + OMX_IndexConfigTimeMediaTimeRequest, /**< reference: OMX_TIME_CONFIG_MEDIATIMEREQUESTTYPE (write only) */ + OMX_IndexConfigTimeClientStartTime, /** + + +/** Khronos standard extension indices. + +This enum lists the current Khronos extension indices to OpenMAX IL. +*/ +typedef enum OMX_INDEXEXTTYPE { + + /* Component parameters and configurations */ + OMX_IndexExtComponentStartUnused = OMX_IndexKhronosExtensions + 0x00100000, + OMX_IndexConfigCallbackRequest, /**< reference: OMX_CONFIG_CALLBACKREQUESTTYPE */ + OMX_IndexConfigCommitMode, /**< reference: OMX_CONFIG_COMMITMODETYPE */ + OMX_IndexConfigCommit, /**< reference: OMX_CONFIG_COMMITTYPE */ + + /* Port parameters and configurations */ + OMX_IndexExtPortStartUnused = OMX_IndexKhronosExtensions + 0x00200000, + + /* Audio parameters and configurations */ + OMX_IndexExtAudioStartUnused = OMX_IndexKhronosExtensions + 0x00400000, + + /* Image parameters and configurations */ + OMX_IndexExtImageStartUnused = OMX_IndexKhronosExtensions + 0x00500000, + + /* Video parameters and configurations */ + OMX_IndexExtVideoStartUnused = OMX_IndexKhronosExtensions + 0x00600000, + OMX_IndexParamNalStreamFormatSupported, /**< reference: OMX_NALSTREAMFORMATTYPE */ + OMX_IndexParamNalStreamFormat, /**< reference: OMX_NALSTREAMFORMATTYPE */ + OMX_IndexParamNalStreamFormatSelect, /**< reference: OMX_NALSTREAMFORMATTYPE */ + OMX_IndexParamVideoVp8, /**< reference: OMX_VIDEO_PARAM_VP8TYPE */ + OMX_IndexConfigVideoVp8ReferenceFrame, /**< reference: OMX_VIDEO_VP8REFERENCEFRAMETYPE */ + OMX_IndexConfigVideoVp8ReferenceFrameType, /**< reference: OMX_VIDEO_VP8REFERENCEFRAMEINFOTYPE */ + OMX_IndexParamVideoReserved, /**< Reserved for future index */ + OMX_IndexParamVideoHevc, /**< reference: OMX_VIDEO_PARAM_HEVCTYPE */ + + /* Image & Video common configurations */ + OMX_IndexExtCommonStartUnused = OMX_IndexKhronosExtensions + 0x00700000, + + /* Other configurations */ + OMX_IndexExtOtherStartUnused = OMX_IndexKhronosExtensions + 0x00800000, + OMX_IndexConfigAutoFramerateConversion, /**< reference: OMX_CONFIG_BOOLEANTYPE */ + OMX_IndexConfigPriority, /**< reference: OMX_PARAM_U32TYPE */ + OMX_IndexConfigOperatingRate, /**< reference: OMX_PARAM_U32TYPE in Q16 format for video and in Hz for audio */ + + /* Time configurations */ + OMX_IndexExtTimeStartUnused = OMX_IndexKhronosExtensions + 0x00900000, + + OMX_IndexExtMax = 0x7FFFFFFF +} OMX_INDEXEXTTYPE; + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OMX_IndexExt_h */ +/* File EOF */ diff --git a/phonelibs/openmax/include/OMX_Other.h b/phonelibs/openmax/include/OMX_Other.h new file mode 100644 index 0000000000..caf7f38448 --- /dev/null +++ b/phonelibs/openmax/include/OMX_Other.h @@ -0,0 +1,337 @@ +/* + * Copyright (c) 2008 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** @file OMX_Other.h - OpenMax IL version 1.1.2 + * The structures needed by Other components to exchange + * parameters and configuration data with the components. + */ + +#ifndef OMX_Other_h +#define OMX_Other_h + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +/* Each OMX header must include all required header files to allow the + * header to compile without errors. The includes below are required + * for this header file to compile successfully + */ + +#include + + +/** + * Enumeration of possible data types which match to multiple domains or no + * domain at all. For types which are vendor specific, a value above + * OMX_OTHER_VENDORTSTART should be used. + */ +typedef enum OMX_OTHER_FORMATTYPE { + OMX_OTHER_FormatTime = 0, /**< Transmission of various timestamps, elapsed time, + time deltas, etc */ + OMX_OTHER_FormatPower, /**< Perhaps used for enabling/disabling power + management, setting clocks? */ + OMX_OTHER_FormatStats, /**< Could be things such as frame rate, frames + dropped, etc */ + OMX_OTHER_FormatBinary, /**< Arbitrary binary data */ + OMX_OTHER_FormatVendorReserved = 1000, /**< Starting value for vendor specific + formats */ + + OMX_OTHER_FormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_OTHER_FormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_OTHER_FormatMax = 0x7FFFFFFF +} OMX_OTHER_FORMATTYPE; + +/** + * Enumeration of seek modes. + */ +typedef enum OMX_TIME_SEEKMODETYPE { + OMX_TIME_SeekModeFast = 0, /**< Prefer seeking to an approximation + * of the requested seek position over + * the actual seek position if it + * results in a faster seek. */ + OMX_TIME_SeekModeAccurate, /**< Prefer seeking to the actual seek + * position over an approximation + * of the requested seek position even + * if it results in a slower seek. */ + OMX_TIME_SeekModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_TIME_SeekModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_TIME_SeekModeMax = 0x7FFFFFFF +} OMX_TIME_SEEKMODETYPE; + +/* Structure representing the seekmode of the component */ +typedef struct OMX_TIME_CONFIG_SEEKMODETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_TIME_SEEKMODETYPE eType; /**< The seek mode */ +} OMX_TIME_CONFIG_SEEKMODETYPE; + +/** Structure representing a time stamp used with the following configs + * on the Clock Component (CC): + * + * OMX_IndexConfigTimeCurrentWallTime: query of the CC’s current wall + * time + * OMX_IndexConfigTimeCurrentMediaTime: query of the CC’s current media + * time + * OMX_IndexConfigTimeCurrentAudioReference and + * OMX_IndexConfigTimeCurrentVideoReference: audio/video reference + * clock sending SC its reference time + * OMX_IndexConfigTimeClientStartTime: a Clock Component client sends + * this structure to the Clock Component via a SetConfig on its + * client port when it receives a buffer with + * OMX_BUFFERFLAG_STARTTIME set. It must use the timestamp + * specified by that buffer for nStartTimestamp. + * + * It’s also used with the following config on components in general: + * + * OMX_IndexConfigTimePosition: IL client querying component position + * (GetConfig) or commanding a component to seek to the given location + * (SetConfig) + */ +typedef struct OMX_TIME_CONFIG_TIMESTAMPTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version + * information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_TICKS nTimestamp; /**< timestamp .*/ +} OMX_TIME_CONFIG_TIMESTAMPTYPE; + +/** Enumeration of possible reference clocks to the media time. */ +typedef enum OMX_TIME_UPDATETYPE { + OMX_TIME_UpdateRequestFulfillment, /**< Update is the fulfillment of a media time request. */ + OMX_TIME_UpdateScaleChanged, /**< Update was generated because the scale chagned. */ + OMX_TIME_UpdateClockStateChanged, /**< Update was generated because the clock state changed. */ + OMX_TIME_UpdateKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_TIME_UpdateVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_TIME_UpdateMax = 0x7FFFFFFF +} OMX_TIME_UPDATETYPE; + +/** Enumeration of possible reference clocks to the media time. */ +typedef enum OMX_TIME_REFCLOCKTYPE { + OMX_TIME_RefClockNone, /**< Use no references. */ + OMX_TIME_RefClockAudio, /**< Use references sent through OMX_IndexConfigTimeCurrentAudioReference */ + OMX_TIME_RefClockVideo, /**< Use references sent through OMX_IndexConfigTimeCurrentVideoReference */ + OMX_TIME_RefClockKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_TIME_RefClockVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_TIME_RefClockMax = 0x7FFFFFFF +} OMX_TIME_REFCLOCKTYPE; + +/** Enumeration of clock states. */ +typedef enum OMX_TIME_CLOCKSTATE { + OMX_TIME_ClockStateRunning, /**< Clock running. */ + OMX_TIME_ClockStateWaitingForStartTime, /**< Clock waiting until the + * prescribed clients emit their + * start time. */ + OMX_TIME_ClockStateStopped, /**< Clock stopped. */ + OMX_TIME_ClockStateKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_TIME_ClockStateVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_TIME_ClockStateMax = 0x7FFFFFFF +} OMX_TIME_CLOCKSTATE; + +/** Structure representing a media time request to the clock component. + * + * A client component sends this structure to the Clock Component via a SetConfig + * on its client port to specify a media timestamp the Clock Component + * should emit. The Clock Component should fulfill the request by sending a + * OMX_TIME_MEDIATIMETYPE when its media clock matches the requested + * timestamp. + * + * The client may require a media time request be fulfilled slightly + * earlier than the media time specified. In this case the client specifies + * an offset which is equal to the difference between wall time corresponding + * to the requested media time and the wall time when it will be + * fulfilled. + * + * A client component may uses these requests and the OMX_TIME_MEDIATIMETYPE to + * time events according to timestamps. If a client must perform an operation O at + * a time T (e.g. deliver a video frame at its corresponding timestamp), it makes a + * media time request at T (perhaps specifying an offset to ensure the request fulfillment + * is a little early). When the clock component passes the resulting OMX_TIME_MEDIATIMETYPE + * structure back to the client component, the client may perform operation O (perhaps having + * to wait a slight amount more time itself as specified by the return values). + */ + +typedef struct OMX_TIME_CONFIG_MEDIATIMEREQUESTTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< port that this structure applies to */ + OMX_PTR pClientPrivate; /**< Client private data to disabiguate this media time + * from others (e.g. the number of the frame to deliver). + * Duplicated in the media time structure that fulfills + * this request. A value of zero is reserved for time scale + * updates. */ + OMX_TICKS nMediaTimestamp; /**< Media timestamp requested.*/ + OMX_TICKS nOffset; /**< Amount of wall clock time by which this + * request should be fulfilled early */ +} OMX_TIME_CONFIG_MEDIATIMEREQUESTTYPE; + +/**< Structure sent from the clock component client either when fulfilling + * a media time request or when the time scale has changed. + * + * In the former case the Clock Component fills this structure and times its emission + * to a client component (via the client port) according to the corresponding media + * time request sent by the client. The Clock Component should time the emission to occur + * when the requested timestamp matches the Clock Component's media time but also the + * prescribed offset early. + * + * Upon scale changes the clock component clears the nClientPrivate data, sends the current + * media time and sets the nScale to the new scale via the client port. It emits a + * OMX_TIME_MEDIATIMETYPE to all clients independent of any requests. This allows clients to + * alter processing to accomodate scaling. For instance a video component might skip inter-frames + * in the case of extreme fastforward. Likewise an audio component might add or remove samples + * from an audio frame to scale audio data. + * + * It is expected that some clock components may not be able to fulfill requests + * at exactly the prescribed time. This is acceptable so long as the request is + * fulfilled at least as early as described and not later. This structure provides + * fields the client may use to wait for the remaining time. + * + * The client may use either the nOffset or nWallTimeAtMedia fields to determine the + * wall time until the nMediaTimestamp actually occurs. In the latter case the + * client can get a more accurate value for offset by getting the current wall + * from the cloc component and subtracting it from nWallTimeAtMedia. + */ + +typedef struct OMX_TIME_MEDIATIMETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nClientPrivate; /**< Client private data to disabiguate this media time + * from others. Copied from the media time request. + * A value of zero is reserved for time scale updates. */ + OMX_TIME_UPDATETYPE eUpdateType; /**< Reason for the update */ + OMX_TICKS nMediaTimestamp; /**< Media time requested. If no media time was + * requested then this is the current media time. */ + OMX_TICKS nOffset; /**< Amount of wall clock time by which this + * request was actually fulfilled early */ + + OMX_TICKS nWallTimeAtMediaTime; /**< Wall time corresponding to nMediaTimeStamp. + * A client may compare this value to current + * media time obtained from the Clock Component to determine + * the wall time until the media timestamp is really + * current. */ + OMX_S32 xScale; /**< Current media time scale in Q16 format. */ + OMX_TIME_CLOCKSTATE eState; /* Seeking Change. Added 7/12.*/ + /**< State of the media time. */ +} OMX_TIME_MEDIATIMETYPE; + +/** Structure representing the current media time scale factor. Applicable only to clock + * component, other components see scale changes via OMX_TIME_MEDIATIMETYPE buffers sent via + * the clock component client ports. Upon recieving this config the clock component changes + * the rate by which the media time increases or decreases effectively implementing trick modes. + */ +typedef struct OMX_TIME_CONFIG_SCALETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_S32 xScale; /**< This is a value in Q16 format which is used for + * scaling the media time */ +} OMX_TIME_CONFIG_SCALETYPE; + +/** Bits used to identify a clock port. Used in OMX_TIME_CONFIG_CLOCKSTATETYPE’s nWaitMask field */ +#define OMX_CLOCKPORT0 0x00000001 +#define OMX_CLOCKPORT1 0x00000002 +#define OMX_CLOCKPORT2 0x00000004 +#define OMX_CLOCKPORT3 0x00000008 +#define OMX_CLOCKPORT4 0x00000010 +#define OMX_CLOCKPORT5 0x00000020 +#define OMX_CLOCKPORT6 0x00000040 +#define OMX_CLOCKPORT7 0x00000080 + +/** Structure representing the current mode of the media clock. + * IL Client uses this config to change or query the mode of the + * media clock of the clock component. Applicable only to clock + * component. + * + * On a SetConfig if eState is OMX_TIME_ClockStateRunning media time + * starts immediately at the prescribed start time. If + * OMX_TIME_ClockStateWaitingForStartTime the Clock Component ignores + * the given nStartTime and waits for all clients specified in the + * nWaitMask to send starttimes (via + * OMX_IndexConfigTimeClientStartTime). The Clock Component then starts + * the media clock using the earliest start time supplied. */ +typedef struct OMX_TIME_CONFIG_CLOCKSTATETYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version + * information */ + OMX_TIME_CLOCKSTATE eState; /**< State of the media time. */ + OMX_TICKS nStartTime; /**< Start time of the media time. */ + OMX_TICKS nOffset; /**< Time to offset the media time by + * (e.g. preroll). Media time will be + * reported to be nOffset ticks earlier. + */ + OMX_U32 nWaitMask; /**< Mask of OMX_CLOCKPORT values. */ +} OMX_TIME_CONFIG_CLOCKSTATETYPE; + +/** Structure representing the reference clock currently being used to + * compute media time. IL client uses this config to change or query the + * clock component's active reference clock */ +typedef struct OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_TIME_REFCLOCKTYPE eClock; /**< Reference clock used to compute media time */ +} OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE; + +/** Descriptor for setting specifics of power type. + * Note: this structure is listed for backwards compatibility. */ +typedef struct OMX_OTHER_CONFIG_POWERTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_BOOL bEnablePM; /**< Flag to enable Power Management */ +} OMX_OTHER_CONFIG_POWERTYPE; + + +/** Descriptor for setting specifics of stats type. + * Note: this structure is listed for backwards compatibility. */ +typedef struct OMX_OTHER_CONFIG_STATSTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + /* what goes here */ +} OMX_OTHER_CONFIG_STATSTYPE; + + +/** + * The PortDefinition structure is used to define all of the parameters + * necessary for the compliant component to setup an input or an output other + * path. + */ +typedef struct OMX_OTHER_PORTDEFINITIONTYPE { + OMX_OTHER_FORMATTYPE eFormat; /**< Type of data expected for this channel */ +} OMX_OTHER_PORTDEFINITIONTYPE; + +/** Port format parameter. This structure is used to enumerate + * the various data input/output format supported by the port. + */ +typedef struct OMX_OTHER_PARAM_PORTFORMATTYPE { + OMX_U32 nSize; /**< size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Indicates which port to set */ + OMX_U32 nIndex; /**< Indicates the enumeration index for the format from 0x0 to N-1 */ + OMX_OTHER_FORMATTYPE eFormat; /**< Type of data expected for this channel */ +} OMX_OTHER_PARAM_PORTFORMATTYPE; + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif +/* File EOF */ diff --git a/phonelibs/openmax/include/OMX_QCOMExtns.h b/phonelibs/openmax/include/OMX_QCOMExtns.h new file mode 100644 index 0000000000..20917932be --- /dev/null +++ b/phonelibs/openmax/include/OMX_QCOMExtns.h @@ -0,0 +1,1888 @@ +/*-------------------------------------------------------------------------- +Copyright (c) 2009-2015, The Linux Foundation. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of The Linux Foundation nor + the names of its contributors may be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +--------------------------------------------------------------------------*/ +#ifndef __OMX_QCOM_EXTENSIONS_H__ +#define __OMX_QCOM_EXTENSIONS_H__ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/*============================================================================ +*//** @file OMX_QCOMExtns.h + This header contains constants and type definitions that specify the + extensions added to the OpenMAX Vendor specific APIs. + +*//*========================================================================*/ + + +/////////////////////////////////////////////////////////////////////////////// +// Include Files +/////////////////////////////////////////////////////////////////////////////// +#include "OMX_Core.h" +#include "OMX_Video.h" + +#define OMX_VIDEO_MAX_HP_LAYERS 6 +/** + * This extension is used to register mapping of a virtual + * address to a physical address. This extension is a parameter + * which can be set using the OMX_SetParameter macro. The data + * pointer corresponding to this extension is + * OMX_QCOM_MemMapEntry. This parameter is a 'write only' + * parameter (Current value cannot be queried using + * OMX_GetParameter macro). + */ +#define OMX_QCOM_EXTN_REGISTER_MMAP "OMX.QCOM.index.param.register_mmap" + +/** + * This structure describes the data pointer corresponding to + * the OMX_QCOM_MMAP_REGISTER_EXTN extension. This parameter + * must be set only 'after' populating a port with a buffer + * using OMX_UseBuffer, wherein the data pointer of the buffer + * corresponds to the virtual address as specified in this + * structure. + */ +struct OMX_QCOM_PARAM_MEMMAPENTRYTYPE +{ + OMX_U32 nSize; /** Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ + OMX_U32 nPortIndex; /**< Port number the structure applies to */ + + /** + * The virtual address of memory block + */ + OMX_U64 nVirtualAddress; + + /** + * The physical address corresponding to the virtual address. The physical + * address is contiguous for the entire valid range of the virtual + * address. + */ + OMX_U64 nPhysicalAddress; +}; + +#define QOMX_VIDEO_IntraRefreshRandom (OMX_VIDEO_IntraRefreshVendorStartUnused + 0) + +/* This error event is used for H.264 long-term reference (LTR) encoding. + * When IL client specifies an LTR frame with its identifier via + * OMX_QCOM_INDEX_CONFIG_VIDEO_LTRUSE to the encoder, if the specified + * LTR frame can not be located by the encoder in its LTR list, the encoder + * issues this error event to IL client to notify the failure of LTRUse config. + */ +#define QOMX_ErrorLTRUseFailed (OMX_ErrorVendorStartUnused + 1) + +#define QOMX_VIDEO_BUFFERFLAG_BFRAME 0x00100000 + +#define QOMX_VIDEO_BUFFERFLAG_EOSEQ 0x00200000 + +#define QOMX_VIDEO_BUFFERFLAG_MBAFF 0x00400000 + +#define QOMX_VIDEO_BUFFERFLAG_CANCEL 0x00800000 + +#define OMX_QCOM_PORTDEFN_EXTN "OMX.QCOM.index.param.portdefn" +/* Allowed APIs on the above Index: OMX_GetParameter() and OMX_SetParameter() */ + +typedef enum OMX_QCOMMemoryRegion +{ + OMX_QCOM_MemRegionInvalid, + OMX_QCOM_MemRegionEBI1, + OMX_QCOM_MemRegionSMI, + OMX_QCOM_MemRegionMax = 0X7FFFFFFF +} OMX_QCOMMemoryRegion; + +typedef enum OMX_QCOMCacheAttr +{ + OMX_QCOM_CacheAttrNone, + OMX_QCOM_CacheAttrWriteBack, + OMX_QCOM_CacheAttrWriteThrough, + OMX_QCOM_CacheAttrMAX = 0X7FFFFFFF +} OMX_QCOMCacheAttr; + +typedef struct OMX_QCOMRectangle +{ + OMX_S32 x; + OMX_S32 y; + OMX_S32 dx; + OMX_S32 dy; +} OMX_QCOMRectangle; + +/** OMX_QCOMFramePackingFormat + * Input or output buffer format + */ +typedef enum OMX_QCOMFramePackingFormat +{ + /* 0 - unspecified + */ + OMX_QCOM_FramePacking_Unspecified, + + /* 1 - Partial frames may be present OMX IL 1.1.1 Figure 2-10: + * Case 1??Each Buffer Filled In Whole or In Part + */ + OMX_QCOM_FramePacking_Arbitrary, + + /* 2 - Multiple complete frames per buffer (integer number) + * OMX IL 1.1.1 Figure 2-11: Case 2—Each Buffer Filled with + * Only Complete Frames of Data + */ + OMX_QCOM_FramePacking_CompleteFrames, + + /* 3 - Only one complete frame per buffer, no partial frame + * OMX IL 1.1.1 Figure 2-12: Case 3—Each Buffer Filled with + * Only One Frame of Compressed Data. Usually at least one + * complete unit of data will be delivered in a buffer for + * uncompressed data formats. + */ + OMX_QCOM_FramePacking_OnlyOneCompleteFrame, + + /* 4 - Only one complete subframe per buffer, no partial subframe + * Example: In H264, one complete NAL per buffer, where one frame + * can contatin multiple NAL + */ + OMX_QCOM_FramePacking_OnlyOneCompleteSubFrame, + + OMX_QCOM_FramePacking_MAX = 0X7FFFFFFF +} OMX_QCOMFramePackingFormat; + +typedef struct OMX_QCOM_PARAM_PORTDEFINITIONTYPE { + OMX_U32 nSize; /** Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion;/** OMX specification version information */ + OMX_U32 nPortIndex; /** Portindex which is extended by this structure */ + + /** Platform specific memory region EBI1, SMI, etc.,*/ + OMX_QCOMMemoryRegion nMemRegion; + + OMX_QCOMCacheAttr nCacheAttr; /** Cache attributes */ + + /** Input or output buffer format */ + OMX_U32 nFramePackingFormat; + +} OMX_QCOM_PARAM_PORTDEFINITIONTYPE; + +typedef struct OMX_QCOM_VIDEO_PARAM_QPRANGETYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 minQP; + OMX_U32 maxQP; +} OMX_QCOM_VIDEO_PARAM_QPRANGETYPE; + +#define OMX_QCOM_PLATFORMPVT_EXTN "OMX.QCOM.index.param.platformprivate" +/** Allowed APIs on the above Index: OMX_SetParameter() */ + +typedef enum OMX_QCOM_PLATFORM_PRIVATE_ENTRY_TYPE +{ + /** Enum for PMEM information */ + OMX_QCOM_PLATFORM_PRIVATE_PMEM = 0x1 +} OMX_QCOM_PLATFORM_PRIVATE_ENTRY_TYPE; + +/** IL client will set the following structure. A failure + * code will be returned if component does not support the + * value provided for 'type'. + */ +struct OMX_QCOM_PLATFORMPRIVATE_EXTN +{ + OMX_U32 nSize; /** Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /** OMX spec version information */ + OMX_U32 nPortIndex; /** Port number on which usebuffer extn is applied */ + + /** Type of extensions should match an entry from + OMX_QCOM_PLATFORM_PRIVATE_ENTRY_TYPE + */ + OMX_QCOM_PLATFORM_PRIVATE_ENTRY_TYPE type; +}; + +typedef struct OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO +{ + /** pmem file descriptor */ + unsigned long pmem_fd; + /** Offset from pmem device base address */ + OMX_U32 offset; + OMX_U32 size; + OMX_U32 mapped_size; + OMX_PTR buffer; +}OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO; + +typedef struct OMX_QCOM_PLATFORM_PRIVATE_ENTRY +{ + /** Entry type */ + OMX_QCOM_PLATFORM_PRIVATE_ENTRY_TYPE type; + + /** Pointer to platform specific entry */ + OMX_PTR entry; +}OMX_QCOM_PLATFORM_PRIVATE_ENTRY; + +typedef struct OMX_QCOM_PLATFORM_PRIVATE_LIST +{ + /** Number of entries */ + OMX_U32 nEntries; + + /** Pointer to array of platform specific entries * + * Contiguous block of OMX_QCOM_PLATFORM_PRIVATE_ENTRY element + */ + OMX_QCOM_PLATFORM_PRIVATE_ENTRY* entryList; +}OMX_QCOM_PLATFORM_PRIVATE_LIST; + +#define OMX_QCOM_FRAME_PACKING_FORMAT "OMX.QCOM.index.param.framepackfmt" +/* Allowed API call: OMX_GetParameter() */ +/* IL client can use this index to rerieve the list of frame formats * + * supported by the component */ + +typedef struct OMX_QCOM_FRAME_PACKINGFORMAT_TYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nIndex; + OMX_QCOMFramePackingFormat eframePackingFormat; +} OMX_QCOM_FRAME_PACKINGFORMAT_TYPE; + + +/** + * Following is the enum for color formats supported on Qualcomm + * MSMs YVU420SemiPlanar color format is not defined in OpenMAX + * 1.1.1 and prior versions of OpenMAX specification. + */ + +enum OMX_QCOM_COLOR_FORMATTYPE +{ + +/** YVU420SemiPlanar: YVU planar format, organized with a first + * plane containing Y pixels, and a second plane containing + * interleaved V and U pixels. V and U pixels are sub-sampled + * by a factor of two both horizontally and vertically. + */ + QOMX_COLOR_FormatYVU420SemiPlanar = 0x7FA30C00, + QOMX_COLOR_FormatYVU420PackedSemiPlanar32m4ka, + QOMX_COLOR_FormatYUV420PackedSemiPlanar16m2ka, + QOMX_COLOR_FormatYUV420PackedSemiPlanar64x32Tile2m8ka, + QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m, + QOMX_COLOR_FORMATYUV420PackedSemiPlanar32mMultiView, + QOMX_COLOR_FORMATYUV420PackedSemiPlanar32mCompressed, + QOMX_COLOR_Format32bitRGBA8888, + QOMX_COLOR_Format32bitRGBA8888Compressed, + QOMX_COLOR_FormatAndroidOpaque = (OMX_COLOR_FORMATTYPE) OMX_COLOR_FormatVendorStartUnused + 0x789, +}; + +enum OMX_QCOM_VIDEO_CODINGTYPE +{ +/** Codecs support by qualcomm which are not listed in OMX 1.1.x + * spec + * */ + OMX_QCOM_VIDEO_CodingVC1 = 0x7FA30C00 , + OMX_QCOM_VIDEO_CodingWMV9 = 0x7FA30C01, + QOMX_VIDEO_CodingDivx = 0x7FA30C02, /**< Value when coding is Divx */ + QOMX_VIDEO_CodingSpark = 0x7FA30C03, /**< Value when coding is Sorenson Spark */ + QOMX_VIDEO_CodingVp = 0x7FA30C04, + QOMX_VIDEO_CodingVp8 = OMX_VIDEO_CodingVP8, /**< keeping old enum for backwards compatibility*/ + QOMX_VIDEO_CodingHevc = OMX_VIDEO_CodingHEVC, /**< keeping old enum for backwards compatibility*/ + QOMX_VIDEO_CodingMVC = 0x7FA30C07, + QOMX_VIDEO_CodingVp9 = OMX_VIDEO_CodingVP9, /**< keeping old enum for backwards compatibility*/ +}; + +enum OMX_QCOM_EXTN_INDEXTYPE +{ + /** Qcom proprietary extension index list */ + + /* "OMX.QCOM.index.param.register_mmap" */ + OMX_QcomIndexRegmmap = 0x7F000000, + + /* "OMX.QCOM.index.param.platformprivate" */ + OMX_QcomIndexPlatformPvt = 0x7F000001, + + /* "OMX.QCOM.index.param.portdefn" */ + OMX_QcomIndexPortDefn = 0x7F000002, + + /* "OMX.QCOM.index.param.framepackingformat" */ + OMX_QcomIndexPortFramePackFmt = 0x7F000003, + + /*"OMX.QCOM.index.param.Interlaced */ + OMX_QcomIndexParamInterlaced = 0x7F000004, + + /*"OMX.QCOM.index.config.interlaceformat */ + OMX_QcomIndexConfigInterlaced = 0x7F000005, + + /*"OMX.QCOM.index.param.syntaxhdr" */ + QOMX_IndexParamVideoSyntaxHdr = 0x7F000006, + + /*"OMX.QCOM.index.config.intraperiod" */ + QOMX_IndexConfigVideoIntraperiod = 0x7F000007, + + /*"OMX.QCOM.index.config.randomIntrarefresh" */ + QOMX_IndexConfigVideoIntraRefresh = 0x7F000008, + + /*"OMX.QCOM.index.config.video.TemporalSpatialTradeOff" */ + QOMX_IndexConfigVideoTemporalSpatialTradeOff = 0x7F000009, + + /*"OMX.QCOM.index.param.video.EncoderMode" */ + QOMX_IndexParamVideoEncoderMode = 0x7F00000A, + + /*"OMX.QCOM.index.param.Divxtype */ + OMX_QcomIndexParamVideoDivx = 0x7F00000B, + + /*"OMX.QCOM.index.param.Sparktype */ + OMX_QcomIndexParamVideoSpark = 0x7F00000C, + + /*"OMX.QCOM.index.param.Vptype */ + OMX_QcomIndexParamVideoVp = 0x7F00000D, + + OMX_QcomIndexQueryNumberOfVideoDecInstance = 0x7F00000E, + + OMX_QcomIndexParamVideoSyncFrameDecodingMode = 0x7F00000F, + + OMX_QcomIndexParamVideoDecoderPictureOrder = 0x7F000010, + + /* "OMX.QCOM.index.config.video.FramePackingInfo" */ + OMX_QcomIndexConfigVideoFramePackingArrangement = 0x7F000011, + + OMX_QcomIndexParamConcealMBMapExtraData = 0x7F000012, + + OMX_QcomIndexParamFrameInfoExtraData = 0x7F000013, + + OMX_QcomIndexParamInterlaceExtraData = 0x7F000014, + + OMX_QcomIndexParamH264TimeInfo = 0x7F000015, + + OMX_QcomIndexParamIndexExtraDataType = 0x7F000016, + + OMX_GoogleAndroidIndexEnableAndroidNativeBuffers = 0x7F000017, + + OMX_GoogleAndroidIndexUseAndroidNativeBuffer = 0x7F000018, + + OMX_GoogleAndroidIndexGetAndroidNativeBufferUsage = 0x7F000019, + + /*"OMX.QCOM.index.config.video.QPRange" */ + OMX_QcomIndexConfigVideoQPRange = 0x7F00001A, + + /*"OMX.QCOM.index.param.EnableTimeStampReoder"*/ + OMX_QcomIndexParamEnableTimeStampReorder = 0x7F00001B, + + /*"OMX.google.android.index.storeMetaDataInBuffers"*/ + OMX_QcomIndexParamVideoMetaBufferMode = 0x7F00001C, + + /*"OMX.google.android.index.useAndroidNativeBuffer2"*/ + OMX_GoogleAndroidIndexUseAndroidNativeBuffer2 = 0x7F00001D, + + /*"OMX.QCOM.index.param.VideoMaxAllowedBitrateCheck"*/ + OMX_QcomIndexParamVideoMaxAllowedBitrateCheck = 0x7F00001E, + + OMX_QcomIndexEnableSliceDeliveryMode = 0x7F00001F, + + /* "OMX.QCOM.index.param.video.ExtnUserExtraData" */ + OMX_QcomIndexEnableExtnUserData = 0x7F000020, + + /*"OMX.QCOM.index.param.video.EnableSmoothStreaming"*/ + OMX_QcomIndexParamEnableSmoothStreaming = 0x7F000021, + + /*"OMX.QCOM.index.param.video.QPRange" */ + OMX_QcomIndexParamVideoQPRange = 0x7F000022, + + OMX_QcomIndexEnableH263PlusPType = 0x7F000023, + + /*"OMX.QCOM.index.param.video.LTRCountRangeSupported"*/ + QOMX_IndexParamVideoLTRCountRangeSupported = 0x7F000024, + + /*"OMX.QCOM.index.param.video.LTRMode"*/ + QOMX_IndexParamVideoLTRMode = 0x7F000025, + + /*"OMX.QCOM.index.param.video.LTRCount"*/ + QOMX_IndexParamVideoLTRCount = 0x7F000026, + + /*"OMX.QCOM.index.config.video.LTRPeriod"*/ + QOMX_IndexConfigVideoLTRPeriod = 0x7F000027, + + /*"OMX.QCOM.index.config.video.LTRUse"*/ + QOMX_IndexConfigVideoLTRUse = 0x7F000028, + + /*"OMX.QCOM.index.config.video.LTRMark"*/ + QOMX_IndexConfigVideoLTRMark = 0x7F000029, + + /* OMX.google.android.index.prependSPSPPSToIDRFrames */ + OMX_QcomIndexParamSequenceHeaderWithIDR = 0x7F00002A, + + OMX_QcomIndexParamH264AUDelimiter = 0x7F00002B, + + OMX_QcomIndexParamVideoDownScalar = 0x7F00002C, + + /* "OMX.QCOM.index.param.video.FramePackingExtradata" */ + OMX_QcomIndexParamVideoFramePackingExtradata = 0x7F00002D, + + /* "OMX.QCOM.index.config.activeregiondetection" */ + OMX_QcomIndexConfigActiveRegionDetection = 0x7F00002E, + + /* "OMX.QCOM.index.config.activeregiondetectionstatus" */ + OMX_QcomIndexConfigActiveRegionDetectionStatus = 0x7F00002F, + + /* "OMX.QCOM.index.config.scalingmode" */ + OMX_QcomIndexConfigScalingMode = 0x7F000030, + + /* "OMX.QCOM.index.config.noisereduction" */ + OMX_QcomIndexConfigNoiseReduction = 0x7F000031, + + /* "OMX.QCOM.index.config.imageenhancement" */ + OMX_QcomIndexConfigImageEnhancement = 0x7F000032, + + /* google smooth-streaming support */ + OMX_QcomIndexParamVideoAdaptivePlaybackMode = 0x7F000033, + + /* H.264 MVC codec index */ + QOMX_IndexParamVideoMvc = 0x7F000034, + + /* "OMX.QCOM.index.param.video.QPExtradata" */ + OMX_QcomIndexParamVideoQPExtraData = 0x7F000035, + + /* "OMX.QCOM.index.param.video.InputBitsInfoExtradata" */ + OMX_QcomIndexParamVideoInputBitsInfoExtraData = 0x7F000036, + + /* VP8 Hierarchical P support */ + OMX_QcomIndexHierarchicalStructure = 0x7F000037, + + OMX_QcomIndexParamPerfLevel = 0x7F000038, + + OMX_QcomIndexParamH264VUITimingInfo = 0x7F000039, + + OMX_QcomIndexParamPeakBitrate = 0x7F00003A, + + /* Enable InitialQP index */ + QOMX_IndexParamVideoInitialQp = 0x7F00003B, + + OMX_QcomIndexParamSetMVSearchrange = 0x7F00003C, + + OMX_QcomIndexConfigPerfLevel = 0x7F00003D, + + /*"OMX.QCOM.index.param.video.LTRCount"*/ + OMX_QcomIndexParamVideoLTRCount = QOMX_IndexParamVideoLTRCount, + + /*"OMX.QCOM.index.config.video.LTRUse"*/ + OMX_QcomIndexConfigVideoLTRUse = QOMX_IndexConfigVideoLTRUse, + + /*"OMX.QCOM.index.config.video.LTRMark"*/ + OMX_QcomIndexConfigVideoLTRMark = QOMX_IndexConfigVideoLTRMark, + + /*"OMX.QCOM.index.param.video.CustomBufferSize"*/ + OMX_QcomIndexParamVideoCustomBufferSize = 0x7F00003E, + + /* Max Hierarchical P layers */ + OMX_QcomIndexMaxHierarchicallayers = 0x7F000041, + + /* Set Encoder Performance Index */ + OMX_QcomIndexConfigVideoVencPerfMode = 0x7F000042, + + /* Set Hybrid Hier-p layers */ + OMX_QcomIndexParamVideoHybridHierpMode = 0x7F000043, + + OMX_QcomIndexFlexibleYUVDescription = 0x7F000044, + + /* Vpp Hqv Control Type */ + OMX_QcomIndexParamVppHqvControl = 0x7F000045, + + /* Enable VPP */ + OMX_QcomIndexParamEnableVpp = 0x7F000046, + + /* MBI statistics mode */ + OMX_QcomIndexParamMBIStatisticsMode = 0x7F000047, + + /* Set PictureTypeDecode */ + OMX_QcomIndexConfigPictureTypeDecode = 0x7F000048, + + OMX_QcomIndexConfigH264EntropyCodingCabac = 0x7F000049, + + /* "OMX.QCOM.index.param.video.InputBatch" */ + OMX_QcomIndexParamBatchSize = 0x7F00004A, + + OMX_QcomIndexConfigNumHierPLayers = 0x7F00004B, + + OMX_QcomIndexConfigRectType = 0x7F00004C, + + OMX_QcomIndexConfigBaseLayerId = 0x7F00004E, + + OMX_QcomIndexParamDriverVersion = 0x7F00004F, + + OMX_QcomIndexConfigQp = 0x7F000050, + + OMX_QcomIndexParamVencAspectRatio = 0x7F000051, + + OMX_QTIIndexParamVQZipSEIExtraData = 0x7F000052, + + /* Enable VQZIP SEI NAL type */ + OMX_QTIIndexParamVQZIPSEIType = 0x7F000053, + + OMX_QTIIndexParamPassInputBufferFd = 0x7F000054, + + /* Set Prefer-adaptive playback*/ + /* "OMX.QTI.index.param.video.PreferAdaptivePlayback" */ + OMX_QTIIndexParamVideoPreferAdaptivePlayback = 0x7F000055, + + /* Set time params */ + OMX_QTIIndexConfigSetTimeData = 0x7F000056, + /* Force Compressed format for DPB when resolution <=1080p + * and OPB is cpu_access */ + /* OMX.QTI.index.param.video.ForceCompressedForDPB */ + OMX_QTIIndexParamForceCompressedForDPB = 0x7F000057, + + /* Enable ROI info */ + OMX_QTIIndexParamVideoEnableRoiInfo = 0x7F000058, + + /* Configure ROI info */ + OMX_QTIIndexConfigVideoRoiInfo = 0x7F000059, + + /* Set Low Latency Mode */ + OMX_QTIIndexParamLowLatencyMode = 0x7F00005A, + + /* Force OPB to UnCompressed mode */ + OMX_QTIIndexParamForceUnCompressedForOPB = 0x7F00005B, + +}; + +/** +* This is custom extension to configure Low Latency Mode. +* +* STRUCT MEMBERS +* +* nSize : Size of Structure in bytes +* nVersion : OpenMAX IL specification version information +* bLowLatencyMode : Enable/Disable Low Latency mode +*/ + +typedef struct QOMX_EXTNINDEX_VIDEO_VENC_LOW_LATENCY_MODE +{ + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_BOOL bLowLatencyMode; +} QOMX_EXTNINDEX_VIDEO_VENC_LOW_LATENCY_MODE; + +/** +* This is custom extension to configure Encoder Aspect Ratio. +* +* STRUCT MEMBERS +* +* nSize : Size of Structure in bytes +* nVersion : OpenMAX IL specification version information +* nSARWidth : Horizontal aspect size +* nSARHeight : Vertical aspect size +*/ + +typedef struct QOMX_EXTNINDEX_VIDEO_VENC_SAR +{ + OMX_U32 nSize; + OMX_U32 nVersion; + OMX_U32 nSARWidth; + OMX_U32 nSARHeight; +} QOMX_EXTNINDEX_VIDEO_VENC_SAR; + +/** +* This is custom extension to configure Hier-p layers. +* This mode configures Hier-p layers dynamically. +* +* STRUCT MEMBERS +* +* nSize : Size of Structure in bytes +* nVersion : OpenMAX IL specification version information +* nNumHierLayers: Set the number of Hier-p layers for the session +* - This should be less than the MAX Hier-P +* layers set for the session. +*/ + +typedef struct QOMX_EXTNINDEX_VIDEO_HIER_P_LAYERS { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nNumHierLayers; +} QOMX_EXTNINDEX_VIDEO_HIER_P_LAYERS; + + +/** +* This is custom extension to configure Hybrid Hier-p settings. +* This mode is different from enabling Hier-p mode. This +* property enables Hier-p encoding with LTR referencing in each +* sub-GOP. +* +* STRUCT MEMBERS +* +* nSize : Size of Structure in bytes +* nVersion : OpenMAX IL specification version information +* nKeyFrameInterval : Indicates the I frame interval +* nHpLayers : Set the number of Hier-p layers for the session +* - This should be <= 6. (1 Base layer + +* 5 Enhancement layers) +* nTemporalLayerBitrateRatio[OMX_VIDEO_MAX_HP_LAYERS] : Bitrate to +* be set for each enhancement layer +* nMinQuantizer : minimum session QP +* nMaxQuantizer : Maximun session QP +*/ + +typedef struct QOMX_EXTNINDEX_VIDEO_HYBRID_HP_MODE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nKeyFrameInterval; + OMX_U32 nTemporalLayerBitrateRatio[OMX_VIDEO_MAX_HP_LAYERS]; + OMX_U32 nMinQuantizer; + OMX_U32 nMaxQuantizer; + OMX_U32 nHpLayers; +} QOMX_EXTNINDEX_VIDEO_HYBRID_HP_MODE; + +/** + * Encoder Performance Mode. This structure is used to set + * performance mode or power save mode when encoding. The search + * range is modified to save power or improve quality. + * + * STRUCT MEMBERS: + * OMX_U32 nPerfMode : Performance mode: + * 1: MAX_QUALITY + * 2: POWER_SAVE + */ + +typedef struct QOMX_EXTNINDEX_VIDEO_PERFMODE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPerfMode; +} QOMX_EXTNINDEX_VIDEO_PERFMODE; + +/** + * Initial QP parameter. This structure is used to enable + * vendor specific extension to let client enable setting + * initial QP values to I P B Frames + * + * STRUCT MEMBERS: + * nSize : Size of Structure in bytes + * nVersion : OpenMAX IL specification version information + * nPortIndex : Index of the port to which this structure applies + * OMX_U32 nQpI : First Iframe QP + * OMX_U32 nQpP : First Pframe QP + * OMX_U32 nQpB : First Bframe QP + * OMX_U32 bEnableInitQp : Bit field indicating which frame type(s) shall + * use the specified initial QP. + * Bit 0: Enable initial QP for I/IDR + * and use value specified in nInitQpI + * Bit 1: Enable initial QP for P + * and use value specified in nInitQpP + * Bit 2: Enable initial QP for B + * and use value specified in nInitQpB + */ + +typedef struct QOMX_EXTNINDEX_VIDEO_INITIALQP { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nQpI; + OMX_U32 nQpP; + OMX_U32 nQpB; + OMX_U32 bEnableInitQp; +} QOMX_EXTNINDEX_VIDEO_INITIALQP; + +/** + * Extension index parameter. This structure is used to enable + * vendor specific extension on input/output port and + * to pass the required flags and data, if any. + * The format of flags and data being passed is known to + * the client and component apriori. + * + * STRUCT MEMBERS: + * nSize : Size of Structure plus pData size + * nVersion : OMX specification version information + * nPortIndex : Indicates which port to set + * bEnable : Extension index enable (1) or disable (0) + * nFlags : Extension index flags, if any + * nDataSize : Size of the extension index data to follow + * pData : Extension index data, if present. + */ +typedef struct QOMX_EXTNINDEX_PARAMTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bEnable; + OMX_U32 nFlags; + OMX_U32 nDataSize; + OMX_PTR pData; +} QOMX_EXTNINDEX_PARAMTYPE; + +/** + * Range index parameter. This structure is used to enable + * vendor specific extension on input/output port and + * to pass the required minimum and maximum values + * + * STRUCT MEMBERS: + * nSize : Size of Structure in bytes + * nVersion : OpenMAX IL specification version information + * nPortIndex : Index of the port to which this structure applies + * nMin : Minimum value + * nMax : Maximum value + * nSteSize : Step size + */ +typedef struct QOMX_EXTNINDEX_RANGETYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_S32 nMin; + OMX_S32 nMax; + OMX_S32 nStepSize; +} QOMX_EXTNINDEX_RANGETYPE; + +/** + * Specifies LTR mode types. + */ +typedef enum QOMX_VIDEO_LTRMODETYPE +{ + QOMX_VIDEO_LTRMode_Disable = 0x0, /**< LTR encoding is disabled */ + QOMX_VIDEO_LTRMode_Manual = 0x1, /**< In this mode, IL client configures + ** the encoder the LTR count and manually + ** controls the marking and use of LTR + ** frames during video encoding. + */ + QOMX_VIDEO_LTRMode_Auto = 0x2, /**< In this mode, IL client configures + ** the encoder the LTR count and LTR + ** period. The encoder marks LTR frames + ** automatically based on the LTR period + ** during video encoding. IL client controls + ** the use of LTR frames. + */ + QOMX_VIDEO_LTRMode_MAX = 0x7FFFFFFF /** Maximum LTR Mode type */ +} QOMX_VIDEO_LTRMODETYPE; + +/** + * LTR mode index parameter. This structure is used + * to enable vendor specific extension on output port + * to pass the LTR mode information. + * + * STRUCT MEMBERS: + * nSize : Size of Structure in bytes + * nVersion : OpenMAX IL specification version information + * nPortIndex : Index of the port to which this structure applies + * eLTRMode : Specifies the LTR mode used in encoder + */ +typedef struct QOMX_VIDEO_PARAM_LTRMODE_TYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + QOMX_VIDEO_LTRMODETYPE eLTRMode; +} QOMX_VIDEO_PARAM_LTRMODE_TYPE; + +/** + * LTR count index parameter. This structure is used + * to enable vendor specific extension on output port + * to pass the LTR count information. + * + * STRUCT MEMBERS: + * nSize : Size of Structure in bytes + * nVersion : OpenMAX IL specification version information + * nPortIndex : Index of the port to which this structure applies + * nCount : Specifies the number of LTR frames stored in the + * encoder component + */ +typedef struct QOMX_VIDEO_PARAM_LTRCOUNT_TYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nCount; +} QOMX_VIDEO_PARAM_LTRCOUNT_TYPE; + + +/** + * This should be used with OMX_QcomIndexParamVideoLTRCount extension. + */ +typedef QOMX_VIDEO_PARAM_LTRCOUNT_TYPE OMX_QCOM_VIDEO_PARAM_LTRCOUNT_TYPE; + +/** + * LTR period index parameter. This structure is used + * to enable vendor specific extension on output port + * to pass the LTR period information. + * + * STRUCT MEMBERS: + * nSize : Size of Structure in bytes + * nVersion : OpenMAX IL specification version information + * nPortIndex : Index of the port to which this structure applies + * nFrames : Specifies the number of frames between two consecutive + * LTR frames. + */ +typedef struct QOMX_VIDEO_CONFIG_LTRPERIOD_TYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nFrames; +} QOMX_VIDEO_CONFIG_LTRPERIOD_TYPE; + +/** + * Marks the next encoded frame as an LTR frame. + * STRUCT MEMBERS: + * nSize : Size of Structure in bytes + * nVersion : OpenMAX IL specification version information + * nPortIndex : Index of the port to which this structure applies + * nID : Specifies the identifier of the LTR frame to be marked + * as reference frame for encoding subsequent frames. + */ +typedef struct QOMX_VIDEO_CONFIG_LTRMARK_TYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nID; +} QOMX_VIDEO_CONFIG_LTRMARK_TYPE; + +/** + * This should be used with OMX_QcomIndexConfigVideoLTRMark extension. + */ +typedef QOMX_VIDEO_CONFIG_LTRMARK_TYPE OMX_QCOM_VIDEO_CONFIG_LTRMARK_TYPE; + +/** + * Specifies an LTR frame to encode subsequent frames. + * STRUCT MEMBERS: + * nSize : Size of Structure in bytes + * nVersion : OpenMAX IL specification version information + * nPortIndex : Index of the port to which this structure applies + * nID : Specifies the identifier of the LTR frame to be used + as reference frame for encoding subsequent frames. + * nFrames : Specifies the number of subsequent frames to be + encoded using the LTR frame with its identifier + nID as reference frame. Short-term reference frames + will be used thereafter. The value of 0xFFFFFFFF + indicates that all subsequent frames will be + encodedusing this LTR frame as reference frame. + */ +typedef struct QOMX_VIDEO_CONFIG_LTRUSE_TYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nID; + OMX_U32 nFrames; +} QOMX_VIDEO_CONFIG_LTRUSE_TYPE; + +/** + * This should be used with OMX_QcomIndexConfigVideoLTRUse extension. + */ +typedef QOMX_VIDEO_CONFIG_LTRUSE_TYPE OMX_QCOM_VIDEO_CONFIG_LTRUSE_TYPE; + +/** + * Enumeration used to define the video encoder modes + * + * ENUMS: + * EncoderModeDefault : Default video recording mode. + * All encoder settings made through + * OMX_SetParameter/OMX_SetConfig are applied. No + * parameter is overridden. + * EncoderModeMMS : Video recording mode for MMS (Multimedia Messaging + * Service). This mode is similar to EncoderModeDefault + * except that here the Rate control mode is overridden + * internally and set as a variant of variable bitrate with + * variable frame rate. After this mode is set if the IL + * client tries to set OMX_VIDEO_CONTROLRATETYPE via + * OMX_IndexParamVideoBitrate that would be rejected. For + * this, client should set mode back to EncoderModeDefault + * first and then change OMX_VIDEO_CONTROLRATETYPE. + */ +typedef enum QOMX_VIDEO_ENCODERMODETYPE +{ + QOMX_VIDEO_EncoderModeDefault = 0x00, + QOMX_VIDEO_EncoderModeMMS = 0x01, + QOMX_VIDEO_EncoderModeMax = 0x7FFFFFFF +} QOMX_VIDEO_ENCODERMODETYPE; + +/** + * This structure is used to set the video encoder mode. + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version info + * nPortIndex : Port that this structure applies to + * nMode : defines the video encoder mode + */ +typedef struct QOMX_VIDEO_PARAM_ENCODERMODETYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + QOMX_VIDEO_ENCODERMODETYPE nMode; +} QOMX_VIDEO_PARAM_ENCODERMODETYPE; + +/** + * This structure describes the parameters corresponding to the + * QOMX_VIDEO_SYNTAXHDRTYPE extension. This parameter can be queried + * during the loaded state. + */ + +typedef struct QOMX_VIDEO_SYNTAXHDRTYPE +{ + OMX_U32 nSize; /** Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion;/** OMX specification version information */ + OMX_U32 nPortIndex; /** Portindex which is extended by this structure */ + OMX_U32 nBytes; /** The number of bytes filled in to the buffer */ + OMX_U8 data[1]; /** Buffer to store the header information */ +} QOMX_VIDEO_SYNTAXHDRTYPE; + +/** + * This structure describes the parameters corresponding to the + * QOMX_VIDEO_TEMPORALSPATIALTYPE extension. This parameter can be set + * dynamically during any state except the state invalid. This is primarily + * used for setting MaxQP from the application. This is set on the out port. + */ + +typedef struct QOMX_VIDEO_TEMPORALSPATIALTYPE +{ + OMX_U32 nSize; /** Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion;/** OMX specification version information */ + OMX_U32 nPortIndex; /** Portindex which is extended by this structure */ + OMX_U32 nTSFactor; /** Temoral spatial tradeoff factor value in 0-100 */ +} QOMX_VIDEO_TEMPORALSPATIALTYPE; + +/** + * This structure describes the parameters corresponding to the + * OMX_QCOM_VIDEO_CONFIG_INTRAPERIODTYPE extension. This parameter can be set + * dynamically during any state except the state invalid. This is set on the out port. + */ + +typedef struct QOMX_VIDEO_INTRAPERIODTYPE +{ + OMX_U32 nSize; /** Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion;/** OMX specification version information */ + OMX_U32 nPortIndex; /** Portindex which is extended by this structure */ + OMX_U32 nIDRPeriod; /** This specifies coding a frame as IDR after every nPFrames + of intra frames. If this parameter is set to 0, only the + first frame of the encode session is an IDR frame. This + field is ignored for non-AVC codecs and is used only for + codecs that support IDR Period */ + OMX_U32 nPFrames; /** The number of "P" frames between two "I" frames */ + OMX_U32 nBFrames; /** The number of "B" frames between two "I" frames */ +} QOMX_VIDEO_INTRAPERIODTYPE; + +/** + * This structure describes the parameters corresponding to the + * OMX_QCOM_VIDEO_CONFIG_ULBUFFEROCCUPANCYTYPE extension. This parameter can be set + * dynamically during any state except the state invalid. This is used for the buffer negotiation + * with other clients. This is set on the out port. + */ +typedef struct OMX_QCOM_VIDEO_CONFIG_ULBUFFEROCCUPANCYTYPE +{ + OMX_U32 nSize; /** Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /** OMX specification version information */ + OMX_U32 nPortIndex; /** Portindex which is extended by this structure */ + OMX_U32 nBufferOccupancy; /** The number of bytes to be set for the buffer occupancy */ +} OMX_QCOM_VIDEO_CONFIG_ULBUFFEROCCUPANCYTYPE; + +/** + * This structure describes the parameters corresponding to the + * OMX_QCOM_VIDEO_CONFIG_RANDOMINTRAREFRESHTYPE extension. This parameter can be set + * dynamically during any state except the state invalid. This is primarily used for the dynamic/random + * intrarefresh. This is set on the out port. + */ +typedef struct OMX_QCOM_VIDEO_CONFIG_RANDOMINTRAREFRESHTYPE +{ + OMX_U32 nSize; /** Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion;/** OMX specification version information */ + OMX_U32 nPortIndex; /** Portindex which is extended by this structure */ + OMX_U32 nRirMBs; /** The number of MBs to be set for intrarefresh */ +} OMX_QCOM_VIDEO_CONFIG_RANDOMINTRAREFRESHTYPE; + + +/** + * This structure describes the parameters corresponding to the + * OMX_QCOM_VIDEO_CONFIG_QPRANGE extension. This parameter can be set + * dynamically during any state except the state invalid. This is primarily + * used for the min/max QP to be set from the application. This + * is set on the out port. + */ +typedef struct OMX_QCOM_VIDEO_CONFIG_QPRANGE +{ + OMX_U32 nSize; /** Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion;/** OMX specification version information */ + OMX_U32 nPortIndex; /** Portindex which is extended by this structure */ + OMX_U32 nMinQP; /** The number for minimum quantization parameter */ + OMX_U32 nMaxQP; /** The number for maximum quantization parameter */ +} OMX_QCOM_VIDEO_CONFIG_QPRANGE; + +/** + * This structure describes the parameters for the + * OMX_QcomIndexParamH264AUDelimiter extension. It enables/disables + * the AU delimiters in the H264 stream, which is used by WFD. + */ +typedef struct OMX_QCOM_VIDEO_CONFIG_H264_AUD +{ + OMX_U32 nSize; /** Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion;/** OMX specification version information */ + OMX_BOOL bEnable; /** Enable/disable the setting */ +} OMX_QCOM_VIDEO_CONFIG_H264_AUD; + +typedef enum QOMX_VIDEO_PERF_LEVEL +{ + OMX_QCOM_PerfLevelNominal, + OMX_QCOM_PerfLevelTurbo +} QOMX_VIDEO_PERF_LEVEL; + +/** + * This structure describes the parameters corresponding + * to OMX_QcomIndexParamPerfLevel extension. It will set + * the performance mode specified as QOMX_VIDEO_PERF_LEVEL. + */ +typedef struct OMX_QCOM_VIDEO_PARAM_PERF_LEVEL { + OMX_U32 nSize; /** Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /** OMX specification version information */ + QOMX_VIDEO_PERF_LEVEL ePerfLevel; /** Performance level */ +} OMX_QCOM_VIDEO_PARAM_PERF_LEVEL; + +/** + * This structure describes the parameters corresponding + * to OMX_QcomIndexConfigPerfLevel extension. It will set + * the performance mode specified as QOMX_VIDEO_PERF_LEVEL. + */ +typedef struct OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL { + OMX_U32 nSize; /** Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /** OMX specification version information */ + QOMX_VIDEO_PERF_LEVEL ePerfLevel; /** Performance level */ +} OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL; + +typedef enum QOMX_VIDEO_PICTURE_TYPE_DECODE +{ + OMX_QCOM_PictypeDecode_IPB, + OMX_QCOM_PictypeDecode_I +} QOMX_VIDEO_PICTURE_TYPE_DECODE; + +/** + * This structure describes the parameters corresponding + * to OMX_QcomIndexConfigPictureTypeDecode extension. It + * will set the picture type decode specified by eDecodeType. + */ +typedef struct OMX_QCOM_VIDEO_CONFIG_PICTURE_TYPE_DECODE { + OMX_U32 nSize; /** Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /** OMX specification version information */ + QOMX_VIDEO_PICTURE_TYPE_DECODE eDecodeType; /** Decode type */ +} OMX_QCOM_VIDEO_CONFIG_PICTURE_TYPE_DECODE; + +/** + * This structure describes the parameters corresponding + * to OMX_QcomIndexParamH264VUITimingInfo extension. It + * will enable/disable the VUI timing info. + */ +typedef struct OMX_QCOM_VIDEO_PARAM_VUI_TIMING_INFO { + OMX_U32 nSize; /** Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /** OMX specification version information */ + OMX_BOOL bEnable; /** Enable/disable the setting */ +} OMX_QCOM_VIDEO_PARAM_VUI_TIMING_INFO; + +/** + * This structure describes the parameters corresponding + * to OMX_QcomIndexParamVQZIPSEIType extension. It + * will enable/disable the VQZIP SEI info. + */ +typedef struct OMX_QTI_VIDEO_PARAM_VQZIP_SEI_TYPE { + OMX_U32 nSize; /** Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /** OMX specification version information */ + OMX_BOOL bEnable; /** Enable/disable the setting */ +} OMX_QTI_VIDEO_PARAM_VQZIP_SEI_TYPE; + +/** + * This structure describes the parameters corresponding + * to OMX_QcomIndexParamPeakBitrate extension. It will + * set the peak bitrate specified by nPeakBitrate. + */ +typedef struct OMX_QCOM_VIDEO_PARAM_PEAK_BITRATE { + OMX_U32 nSize; /** Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /** OMX specification version information */ + OMX_U32 nPeakBitrate; /** Peak bitrate value */ +} OMX_QCOM_VIDEO_PARAM_PEAK_BITRATE; + +/** + * This structure describes the parameters corresponding + * to OMX_QTIIndexParamForceCompressedForDPB extension. Enabling + * this extension will force the split mode DPB(compressed)/OPB(Linear) + * for all resolutions.On some chipsets preferred mode would be combined + * Linear for both DPB/OPB to save memory. For example on 8996 preferred mode + * would be combined linear for resolutions <= 1080p . + * Enabling this might save power but with the cost + * of increased memory i.e almost double the number on output YUV buffers. + */ +typedef struct OMX_QTI_VIDEO_PARAM_FORCE_COMPRESSED_FOR_DPB_TYPE { + OMX_U32 nSize; /** Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion; /** OMX specification version information */ + OMX_BOOL bEnable; /** Enable/disable the setting */ +} OMX_QTI_VIDEO_PARAM_FORCE_COMPRESSED_FOR_DPB_TYPE; + +/** + * This structure describes the parameters corresponding + * to OMX_QTIIndexParamForceUnCompressedForOPB extension. Enabling this + * extension will force the OPB to be linear for the current video session. + * If this property is not set, then the OPB will be set to linear or compressed + * based on resolution selected and/or if cpu access is requested on the + * OPB buffer. + */ +typedef struct OMX_QTI_VIDEO_PARAM_FORCE_UNCOMPRESSED_FOR_OPB_TYPE { + OMX_U32 nSize; /** Sizeo f the structure in bytes */ + OMX_VERSIONTYPE nVersion; /** OMX specification version information */ + OMX_BOOL bEnable; /** Enable/disable the setting */ +} OMX_QTI_VIDEO_PARAM_FORCE_UNCOMPRESSED_FOR_OPB_TYPE; + +typedef struct OMX_VENDOR_EXTRADATATYPE { + OMX_U32 nPortIndex; + OMX_U32 nDataSize; + OMX_U8 *pData; // cdata (codec_data/extradata) +} OMX_VENDOR_EXTRADATATYPE; + +/** + * This structure describes the parameters corresponding to the + * OMX_VENDOR_VIDEOFRAMERATE extension. This parameter can be set + * dynamically during any state except the state invalid. This is + * used for frame rate to be set from the application. This + * is set on the in port. + */ +typedef struct OMX_VENDOR_VIDEOFRAMERATE { + OMX_U32 nSize; /** Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion;/** OMX specification version information */ + OMX_U32 nPortIndex; /** Portindex which is extended by this structure */ + OMX_U32 nFps; /** Frame rate value */ + OMX_BOOL bEnabled; /** Flag to enable or disable client's frame rate value */ +} OMX_VENDOR_VIDEOFRAMERATE; + +typedef enum OMX_INDEXVENDORTYPE { + OMX_IndexVendorFileReadInputFilename = 0xFF000001, + OMX_IndexVendorParser3gpInputFilename = 0xFF000002, + OMX_IndexVendorVideoExtraData = 0xFF000003, + OMX_IndexVendorAudioExtraData = 0xFF000004, + OMX_IndexVendorVideoFrameRate = 0xFF000005, +} OMX_INDEXVENDORTYPE; + +typedef enum OMX_QCOM_VC1RESOLUTIONTYPE +{ + OMX_QCOM_VC1_PICTURE_RES_1x1, + OMX_QCOM_VC1_PICTURE_RES_2x1, + OMX_QCOM_VC1_PICTURE_RES_1x2, + OMX_QCOM_VC1_PICTURE_RES_2x2 +} OMX_QCOM_VC1RESOLUTIONTYPE; + +typedef enum OMX_QCOM_INTERLACETYPE +{ + OMX_QCOM_InterlaceFrameProgressive, + OMX_QCOM_InterlaceInterleaveFrameTopFieldFirst, + OMX_QCOM_InterlaceInterleaveFrameBottomFieldFirst, + OMX_QCOM_InterlaceFrameTopFieldFirst, + OMX_QCOM_InterlaceFrameBottomFieldFirst, + OMX_QCOM_InterlaceFieldTop, + OMX_QCOM_InterlaceFieldBottom +}OMX_QCOM_INTERLACETYPE; + +typedef struct OMX_QCOM_PARAM_VIDEO_INTERLACETYPE +{ + OMX_U32 nSize; /** Size of the structure in bytes */ + OMX_VERSIONTYPE nVersion;/** OMX specification version information */ + OMX_U32 nPortIndex; /** Portindex which is extended by this structure */ + OMX_BOOL bInterlace; /** Interlace content **/ +}OMX_QCOM_PARAM_VIDEO_INTERLACETYPE; + +typedef struct OMX_QCOM_CONFIG_INTERLACETYPE +{ + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nIndex; + OMX_QCOM_INTERLACETYPE eInterlaceType; +}OMX_QCOM_CONFIG_INTERLACETYPE; + +#define MAX_PAN_SCAN_WINDOWS 4 + +typedef struct OMX_QCOM_PANSCAN +{ + OMX_U32 numWindows; + OMX_QCOMRectangle window[MAX_PAN_SCAN_WINDOWS]; +} OMX_QCOM_PANSCAN; + +typedef struct OMX_QCOM_ASPECT_RATIO +{ + OMX_U32 aspectRatioX; + OMX_U32 aspectRatioY; +} OMX_QCOM_ASPECT_RATIO; + +typedef struct OMX_QCOM_DISPLAY_ASPECT_RATIO +{ + OMX_U32 displayVerticalSize; + OMX_U32 displayHorizontalSize; +} OMX_QCOM_DISPLAY_ASPECT_RATIO; + +typedef struct OMX_QCOM_FRAME_PACK_ARRANGEMENT +{ + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 id; + OMX_U32 cancel_flag; + OMX_U32 type; + OMX_U32 quincunx_sampling_flag; + OMX_U32 content_interpretation_type; + OMX_U32 spatial_flipping_flag; + OMX_U32 frame0_flipped_flag; + OMX_U32 field_views_flag; + OMX_U32 current_frame_is_frame0_flag; + OMX_U32 frame0_self_contained_flag; + OMX_U32 frame1_self_contained_flag; + OMX_U32 frame0_grid_position_x; + OMX_U32 frame0_grid_position_y; + OMX_U32 frame1_grid_position_x; + OMX_U32 frame1_grid_position_y; + OMX_U32 reserved_byte; + OMX_U32 repetition_period; + OMX_U32 extension_flag; +} OMX_QCOM_FRAME_PACK_ARRANGEMENT; + +typedef struct OMX_QCOM_EXTRADATA_QP +{ + OMX_U32 nQP; +} OMX_QCOM_EXTRADATA_QP; + +typedef struct OMX_QCOM_EXTRADATA_BITS_INFO +{ + OMX_U32 header_bits; + OMX_U32 frame_bits; +} OMX_QCOM_EXTRADATA_BITS_INFO; + +typedef struct OMX_QCOM_EXTRADATA_USERDATA { + OMX_U32 type; + OMX_U32 data[1]; +} OMX_QCOM_EXTRADATA_USERDATA; + +typedef struct OMX_QCOM_EXTRADATA_FRAMEINFO +{ + // common frame meta data. interlace related info removed + OMX_VIDEO_PICTURETYPE ePicType; + OMX_QCOM_INTERLACETYPE interlaceType; + OMX_QCOM_PANSCAN panScan; + OMX_QCOM_ASPECT_RATIO aspectRatio; + OMX_QCOM_DISPLAY_ASPECT_RATIO displayAspectRatio; + OMX_U32 nConcealedMacroblocks; + OMX_U32 nFrameRate; + OMX_TICKS nTimeStamp; +} OMX_QCOM_EXTRADATA_FRAMEINFO; + +typedef struct OMX_QCOM_EXTRADATA_FRAMEDIMENSION +{ + /** Frame Dimensions added to each YUV buffer */ + OMX_U32 nDecWidth; /** Width rounded to multiple of 16 */ + OMX_U32 nDecHeight; /** Height rounded to multiple of 16 */ + OMX_U32 nActualWidth; /** Actual Frame Width */ + OMX_U32 nActualHeight; /** Actual Frame Height */ + +} OMX_QCOM_EXTRADATA_FRAMEDIMENSION; + +typedef struct OMX_QCOM_H264EXTRADATA +{ + OMX_U64 seiTimeStamp; +} OMX_QCOM_H264EXTRADATA; + +typedef struct OMX_QCOM_VC1EXTRADATA +{ + OMX_U32 nVC1RangeY; + OMX_U32 nVC1RangeUV; + OMX_QCOM_VC1RESOLUTIONTYPE eVC1PicResolution; +} OMX_QCOM_VC1EXTRADATA; + +typedef union OMX_QCOM_EXTRADATA_CODEC_DATA +{ + OMX_QCOM_H264EXTRADATA h264ExtraData; + OMX_QCOM_VC1EXTRADATA vc1ExtraData; +} OMX_QCOM_EXTRADATA_CODEC_DATA; + +typedef struct OMX_QCOM_EXTRADATA_MBINFO +{ + OMX_U32 nFormat; + OMX_U32 nDataSize; + OMX_U8 data[0]; +} OMX_QCOM_EXTRADATA_MBINFO; + +typedef struct OMX_QCOM_EXTRADATA_VQZIPSEI { + OMX_U32 nSize; + OMX_U8 data[0]; +} OMX_QCOM_EXTRADATA_VQZIPSEI; + +typedef struct OMX_QTI_VIDEO_PARAM_ENABLE_ROIINFO { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bEnableRoiInfo; +} OMX_QTI_VIDEO_PARAM_ENABLE_ROIINFO; + +typedef struct OMX_QTI_VIDEO_CONFIG_ROIINFO { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_S32 nUpperQpOffset; + OMX_S32 nLowerQpOffset; + OMX_BOOL bUseRoiInfo; + OMX_S32 nRoiMBInfoSize; + OMX_PTR pRoiMBInfo; +} OMX_QTI_VIDEO_CONFIG_ROIINFO; + +typedef enum OMX_QCOM_EXTRADATATYPE +{ + OMX_ExtraDataFrameInfo = 0x7F000001, + OMX_ExtraDataH264 = 0x7F000002, + OMX_ExtraDataVC1 = 0x7F000003, + OMX_ExtraDataFrameDimension = 0x7F000004, + OMX_ExtraDataVideoEncoderSliceInfo = 0x7F000005, + OMX_ExtraDataConcealMB = 0x7F000006, + OMX_ExtraDataInterlaceFormat = 0x7F000007, + OMX_ExtraDataPortDef = 0x7F000008, + OMX_ExtraDataMP2ExtnData = 0x7F000009, + OMX_ExtraDataMP2UserData = 0x7F00000a, + OMX_ExtraDataVideoLTRInfo = 0x7F00000b, + OMX_ExtraDataFramePackingArrangement = 0x7F00000c, + OMX_ExtraDataQP = 0x7F00000d, + OMX_ExtraDataInputBitsInfo = 0x7F00000e, + OMX_ExtraDataVideoEncoderMBInfo = 0x7F00000f, + OMX_ExtraDataVQZipSEI = 0x7F000010, +} OMX_QCOM_EXTRADATATYPE; + +typedef struct OMX_STREAMINTERLACEFORMATTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bInterlaceFormat; + OMX_U32 nInterlaceFormats; +} OMX_STREAMINTERLACEFORMAT; + +typedef enum OMX_INTERLACETYPE +{ + OMX_InterlaceFrameProgressive, + OMX_InterlaceInterleaveFrameTopFieldFirst, + OMX_InterlaceInterleaveFrameBottomFieldFirst, + OMX_InterlaceFrameTopFieldFirst, + OMX_InterlaceFrameBottomFieldFirst +} OMX_INTERLACES; + + +#define OMX_EXTRADATA_HEADER_SIZE 20 + +/** + * AVC profile types, each profile indicates support for various + * performance bounds and different annexes. + */ +typedef enum QOMX_VIDEO_AVCPROFILETYPE { + QOMX_VIDEO_AVCProfileBaseline = OMX_VIDEO_AVCProfileBaseline, + QOMX_VIDEO_AVCProfileMain = OMX_VIDEO_AVCProfileMain, + QOMX_VIDEO_AVCProfileExtended = OMX_VIDEO_AVCProfileExtended, + QOMX_VIDEO_AVCProfileHigh = OMX_VIDEO_AVCProfileHigh, + QOMX_VIDEO_AVCProfileHigh10 = OMX_VIDEO_AVCProfileHigh10, + QOMX_VIDEO_AVCProfileHigh422 = OMX_VIDEO_AVCProfileHigh422, + QOMX_VIDEO_AVCProfileHigh444 = OMX_VIDEO_AVCProfileHigh444, + /* QCom specific profile indexes */ + QOMX_VIDEO_AVCProfileConstrained = OMX_VIDEO_AVCProfileVendorStartUnused, + QOMX_VIDEO_AVCProfileConstrainedBaseline, + QOMX_VIDEO_AVCProfileConstrainedHigh, +} QOMX_VIDEO_AVCPROFILETYPE; + + +/** + * H.264 MVC Profiles + */ +typedef enum QOMX_VIDEO_MVCPROFILETYPE { + QOMX_VIDEO_MVCProfileStereoHigh = 0x1, + QOMX_VIDEO_MVCProfileMultiViewHigh = 0x2, + QOMX_VIDEO_MVCProfileKhronosExtensions = 0x6F000000, + QOMX_VIDEO_MVCProfileVendorStartUnused = 0x7F000000, + QOMX_VIDEO_MVCProfileMax = 0x7FFFFFFF +} QOMX_VIDEO_MVCPROFILETYPE; + +/** + * H.264 MVC Levels + */ +typedef enum QOMX_VIDEO_MVCLEVELTYPE { + QOMX_VIDEO_MVCLevel1 = 0x01, /**< Level 1 */ + QOMX_VIDEO_MVCLevel1b = 0x02, /**< Level 1b */ + QOMX_VIDEO_MVCLevel11 = 0x04, /**< Level 1.1 */ + QOMX_VIDEO_MVCLevel12 = 0x08, /**< Level 1.2 */ + QOMX_VIDEO_MVCLevel13 = 0x10, /**< Level 1.3 */ + QOMX_VIDEO_MVCLevel2 = 0x20, /**< Level 2 */ + QOMX_VIDEO_MVCLevel21 = 0x40, /**< Level 2.1 */ + QOMX_VIDEO_MVCLevel22 = 0x80, /**< Level 2.2 */ + QOMX_VIDEO_MVCLevel3 = 0x100, /**< Level 3 */ + QOMX_VIDEO_MVCLevel31 = 0x200, /**< Level 3.1 */ + QOMX_VIDEO_MVCLevel32 = 0x400, /**< Level 3.2 */ + QOMX_VIDEO_MVCLevel4 = 0x800, /**< Level 4 */ + QOMX_VIDEO_MVCLevel41 = 0x1000, /**< Level 4.1 */ + QOMX_VIDEO_MVCLevel42 = 0x2000, /**< Level 4.2 */ + QOMX_VIDEO_MVCLevel5 = 0x4000, /**< Level 5 */ + QOMX_VIDEO_MVCLevel51 = 0x8000, /**< Level 5.1 */ + QOMX_VIDEO_MVCLevelKhronosExtensions = 0x6F000000, + QOMX_VIDEO_MVCLevelVendorStartUnused = 0x7F000000, + QOMX_VIDEO_MVCLevelMax = 0x7FFFFFFF +} QOMX_VIDEO_MVCLEVELTYPE; + +/** + * DivX Versions + */ +typedef enum QOMX_VIDEO_DIVXFORMATTYPE { + QOMX_VIDEO_DIVXFormatUnused = 0x01, /**< Format unused or unknown */ + QOMX_VIDEO_DIVXFormat311 = 0x02, /**< DivX 3.11 */ + QOMX_VIDEO_DIVXFormat4 = 0x04, /**< DivX 4 */ + QOMX_VIDEO_DIVXFormat5 = 0x08, /**< DivX 5 */ + QOMX_VIDEO_DIVXFormat6 = 0x10, /**< DivX 6 */ + QOMX_VIDEO_DIVXFormatKhronosExtensions = 0x6F000000, + QOMX_VIDEO_DIVXFormatVendorStartUnused = 0x7F000000, + QOMX_VIDEO_DIVXFormatMax = 0x7FFFFFFF +} QOMX_VIDEO_DIVXFORMATTYPE; + +/** + * DivX profile types, each profile indicates support for + * various performance bounds. + */ +typedef enum QOMX_VIDEO_DIVXPROFILETYPE { + QOMX_VIDEO_DivXProfileqMobile = 0x01, /**< qMobile Profile */ + QOMX_VIDEO_DivXProfileMobile = 0x02, /**< Mobile Profile */ + QOMX_VIDEO_DivXProfileMT = 0x04, /**< Mobile Theatre Profile */ + QOMX_VIDEO_DivXProfileHT = 0x08, /**< Home Theatre Profile */ + QOMX_VIDEO_DivXProfileHD = 0x10, /**< High Definition Profile */ + QOMX_VIDEO_DIVXProfileKhronosExtensions = 0x6F000000, + QOMX_VIDEO_DIVXProfileVendorStartUnused = 0x7F000000, + QOMX_VIDEO_DIVXProfileMax = 0x7FFFFFFF +} QOMX_VIDEO_DIVXPROFILETYPE; + +/** + * DivX Video Params + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * eFormat : Version of DivX stream / data + * eProfile : Profile of DivX stream / data + */ +typedef struct QOMX_VIDEO_PARAM_DIVXTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + QOMX_VIDEO_DIVXFORMATTYPE eFormat; + QOMX_VIDEO_DIVXPROFILETYPE eProfile; +} QOMX_VIDEO_PARAM_DIVXTYPE; + + + +/** + * VP Versions + */ +typedef enum QOMX_VIDEO_VPFORMATTYPE { + QOMX_VIDEO_VPFormatUnused = 0x01, /**< Format unused or unknown */ + QOMX_VIDEO_VPFormat6 = 0x02, /**< VP6 Video Format */ + QOMX_VIDEO_VPFormat7 = 0x04, /**< VP7 Video Format */ + QOMX_VIDEO_VPFormat8 = 0x08, /**< VP8 Video Format */ + QOMX_VIDEO_VPFormat9 = 0x10, /**< VP9 Video Format */ + QOMX_VIDEO_VPFormatKhronosExtensions = 0x6F000000, + QOMX_VIDEO_VPFormatVendorStartUnused = 0x7F000000, + QOMX_VIDEO_VPFormatMax = 0x7FFFFFFF +} QOMX_VIDEO_VPFORMATTYPE; + +/** + * VP profile types, each profile indicates support for various + * encoding tools. + */ +typedef enum QOMX_VIDEO_VPPROFILETYPE { + QOMX_VIDEO_VPProfileSimple = 0x01, /**< Simple Profile, applies to VP6 only */ + QOMX_VIDEO_VPProfileAdvanced = 0x02, /**< Advanced Profile, applies to VP6 only */ + QOMX_VIDEO_VPProfileVersion0 = 0x04, /**< Version 0, applies to VP7 and VP8 */ + QOMX_VIDEO_VPProfileVersion1 = 0x08, /**< Version 1, applies to VP7 and VP8 */ + QOMX_VIDEO_VPProfileVersion2 = 0x10, /**< Version 2, applies to VP8 only */ + QOMX_VIDEO_VPProfileVersion3 = 0x20, /**< Version 3, applies to VP8 only */ + QOMX_VIDEO_VPProfileKhronosExtensions = 0x6F000000, + QOMX_VIDEO_VPProfileVendorStartUnused = 0x7F000000, + QOMX_VIDEO_VPProfileMax = 0x7FFFFFFF +} QOMX_VIDEO_VPPROFILETYPE; + +/** + * VP Video Params + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * eFormat : Format of VP stream / data + * eProfile : Profile or Version of VP stream / data + */ +typedef struct QOMX_VIDEO_PARAM_VPTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + QOMX_VIDEO_VPFORMATTYPE eFormat; + QOMX_VIDEO_VPPROFILETYPE eProfile; +} QOMX_VIDEO_PARAM_VPTYPE; + +/** + * Spark Versions + */ +typedef enum QOMX_VIDEO_SPARKFORMATTYPE { + QOMX_VIDEO_SparkFormatUnused = 0x01, /**< Format unused or unknown */ + QOMX_VIDEO_SparkFormat0 = 0x02, /**< Video Format Version 0 */ + QOMX_VIDEO_SparkFormat1 = 0x04, /**< Video Format Version 1 */ + QOMX_VIDEO_SparkFormatKhronosExtensions = 0x6F000000, + QOMX_VIDEO_SparkFormatVendorStartUnused = 0x7F000000, + QOMX_VIDEO_SparkFormatMax = 0x7FFFFFFF +} QOMX_VIDEO_SPARKFORMATTYPE; + +/** + * Spark Video Params + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * eFormat : Version of Spark stream / data + */ +typedef struct QOMX_VIDEO_PARAM_SPARKTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + QOMX_VIDEO_SPARKFORMATTYPE eFormat; +} QOMX_VIDEO_PARAM_SPARKTYPE; + + +typedef struct QOMX_VIDEO_QUERY_DECODER_INSTANCES { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nNumOfInstances; +} QOMX_VIDEO_QUERY_DECODER_INSTANCES; + +typedef struct QOMX_ENABLETYPE { + OMX_BOOL bEnable; +} QOMX_ENABLETYPE; + +typedef enum QOMX_VIDEO_EVENTS { + OMX_EventIndexsettingChanged = OMX_EventVendorStartUnused +} QOMX_VIDEO_EVENTS; + +typedef enum QOMX_VIDEO_PICTURE_ORDER { + QOMX_VIDEO_DISPLAY_ORDER = 0x1, + QOMX_VIDEO_DECODE_ORDER = 0x2 +} QOMX_VIDEO_PICTURE_ORDER; + +typedef struct QOMX_VIDEO_DECODER_PICTURE_ORDER { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + QOMX_VIDEO_PICTURE_ORDER eOutputPictureOrder; +} QOMX_VIDEO_DECODER_PICTURE_ORDER; + +typedef struct QOMX_INDEXEXTRADATATYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bEnabled; + OMX_INDEXTYPE nIndex; +} QOMX_INDEXEXTRADATATYPE; + +typedef struct QOMX_INDEXTIMESTAMPREORDER { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bEnable; +} QOMX_INDEXTIMESTAMPREORDER; + +typedef struct QOMX_INDEXDOWNSCALAR { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bEnable; +} QOMX_INDEXDOWNSCALAR; + +typedef struct QOMX_VIDEO_CUSTOM_BUFFERSIZE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nBufferSize; +} QOMX_VIDEO_CUSTOM_BUFFERSIZE; + +#define OMX_QCOM_INDEX_PARAM_VIDEO_SYNCFRAMEDECODINGMODE "OMX.QCOM.index.param.video.SyncFrameDecodingMode" +#define OMX_QCOM_INDEX_PARAM_INDEXEXTRADATA "OMX.QCOM.index.param.IndexExtraData" +#define OMX_QCOM_INDEX_PARAM_VIDEO_SLICEDELIVERYMODE "OMX.QCOM.index.param.SliceDeliveryMode" +#define OMX_QCOM_INDEX_PARAM_VIDEO_FRAMEPACKING_EXTRADATA "OMX.QCOM.index.param.video.FramePackingExtradata" +#define OMX_QCOM_INDEX_PARAM_VIDEO_QP_EXTRADATA "OMX.QCOM.index.param.video.QPExtradata" +#define OMX_QCOM_INDEX_PARAM_VIDEO_INPUTBITSINFO_EXTRADATA "OMX.QCOM.index.param.video.InputBitsInfoExtradata" +#define OMX_QCOM_INDEX_PARAM_VIDEO_EXTNUSER_EXTRADATA "OMX.QCOM.index.param.video.ExtnUserExtraData" +#define OMX_QCOM_INDEX_CONFIG_VIDEO_FRAMEPACKING_INFO "OMX.QCOM.index.config.video.FramePackingInfo" +#define OMX_QCOM_INDEX_PARAM_VIDEO_MPEG2SEQDISP_EXTRADATA "OMX.QCOM.index.param.video.Mpeg2SeqDispExtraData" + +#define OMX_QCOM_INDEX_PARAM_VIDEO_HIERSTRUCTURE "OMX.QCOM.index.param.video.HierStructure" +#define OMX_QCOM_INDEX_PARAM_VIDEO_LTRCOUNT "OMX.QCOM.index.param.video.LTRCount" +#define OMX_QCOM_INDEX_PARAM_VIDEO_LTRPERIOD "OMX.QCOM.index.param.video.LTRPeriod" +#define OMX_QCOM_INDEX_CONFIG_VIDEO_LTRUSE "OMX.QCOM.index.config.video.LTRUse" +#define OMX_QCOM_INDEX_CONFIG_VIDEO_LTRMARK "OMX.QCOM.index.config.video.LTRMark" +#define OMX_QCOM_INDEX_CONFIG_VIDEO_HIER_P_LAYERS "OMX.QCOM.index.config.video.hierplayers" +#define OMX_QCOM_INDEX_CONFIG_RECTANGLE_TYPE "OMX.QCOM.index.config.video.rectangle" +#define OMX_QCOM_INDEX_PARAM_VIDEO_BASE_LAYER_ID "OMX.QCOM.index.param.video.baselayerid" +#define OMX_QCOM_INDEX_CONFIG_VIDEO_QP "OMX.QCOM.index.config.video.qp" +#define OMX_QCOM_INDEX_PARAM_VIDEO_SAR "OMX.QCOM.index.param.video.sar" +#define OMX_QTI_INDEX_PARAM_VIDEO_LOW_LATENCY "OMX.QTI.index.param.video.LowLatency" + +#define OMX_QCOM_INDEX_PARAM_VIDEO_PASSINPUTBUFFERFD "OMX.QCOM.index.param.video.PassInputBufferFd" +#define OMX_QTI_INDEX_PARAM_VIDEO_PREFER_ADAPTIVE_PLAYBACK "OMX.QTI.index.param.video.PreferAdaptivePlayback" +#define OMX_QTI_INDEX_CONFIG_VIDEO_SETTIMEDATA "OMX.QTI.index.config.video.settimedata" +#define OMX_QTI_INDEX_PARAM_VIDEO_FORCE_COMPRESSED_FOR_DPB "OMX.QTI.index.param.video.ForceCompressedForDPB" +#define OMX_QTI_INDEX_PARAM_VIDEO_ENABLE_ROIINFO "OMX.QTI.index.param.enableRoiInfo" +#define OMX_QTI_INDEX_CONFIG_VIDEO_ROIINFO "OMX.QTI.index.config.RoiInfo" + +typedef enum { + QOMX_VIDEO_FRAME_PACKING_CHECKERBOARD = 0, + QOMX_VIDEO_FRAME_PACKING_COLUMN_INTERLEAVE = 1, + QOMX_VIDEO_FRAME_PACKING_ROW_INTERLEAVE = 2, + QOMX_VIDEO_FRAME_PACKING_SIDE_BY_SIDE = 3, + QOMX_VIDEO_FRAME_PACKING_TOP_BOTTOM = 4, + QOMX_VIDEO_FRAME_PACKING_TEMPORAL = 5, +} QOMX_VIDEO_FRAME_PACKING_ARRANGEMENT; + +typedef enum { + QOMX_VIDEO_CONTENT_UNSPECIFIED = 0, + QOMX_VIDEO_CONTENT_LR_VIEW = 1, + QOMX_VIDEO_CONTENT_RL_VIEW = 2, +} QOMX_VIDEO_CONTENT_INTERPRETATION; + +/** + * Specifies the extended picture types. These values should be + * OR'd along with the types defined in OMX_VIDEO_PICTURETYPE to + * signal all pictures types which are allowed. + * + * ENUMS: + * H.264 Specific Picture Types: IDR + */ +typedef enum QOMX_VIDEO_PICTURETYPE { + QOMX_VIDEO_PictureTypeIDR = OMX_VIDEO_PictureTypeVendorStartUnused + 0x1000 +} QOMX_VIDEO_PICTURETYPE; + +#define OMX_QCOM_INDEX_CONFIG_ACTIVE_REGION_DETECTION "OMX.QCOM.index.config.activeregiondetection" +#define OMX_QCOM_INDEX_CONFIG_ACTIVE_REGION_DETECTION_STATUS "OMX.QCOM.index.config.activeregiondetectionstatus" +#define OMX_QCOM_INDEX_CONFIG_SCALING_MODE "OMX.QCOM.index.config.scalingmode" +#define OMX_QCOM_INDEX_CONFIG_NOISEREDUCTION "OMX.QCOM.index.config.noisereduction" +#define OMX_QCOM_INDEX_CONFIG_IMAGEENHANCEMENT "OMX.QCOM.index.config.imageenhancement" +#define OMX_QCOM_INDEX_PARAM_HELDBUFFERCOUNT "OMX.QCOM.index.param.HeldBufferCount" /**< reference: QOMX_HELDBUFFERCOUNTTYPE */ + + +typedef struct QOMX_RECTTYPE { + OMX_S32 nLeft; + OMX_S32 nTop; + OMX_U32 nWidth; + OMX_U32 nHeight; +} QOMX_RECTTYPE; + +typedef struct QOMX_ACTIVEREGIONDETECTIONTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bEnable; + QOMX_RECTTYPE sROI; + OMX_U32 nNumExclusionRegions; + QOMX_RECTTYPE sExclusionRegions[1]; +} QOMX_ACTIVEREGIONDETECTIONTYPE; + +typedef struct QOMX_ACTIVEREGIONDETECTION_STATUSTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bDetected; + QOMX_RECTTYPE sDetectedRegion; +} QOMX_ACTIVEREGIONDETECTION_STATUSTYPE; + +typedef enum QOMX_SCALE_MODETYPE { + QOMX_SCALE_MODE_Normal, + QOMX_SCALE_MODE_Anamorphic, + QOMX_SCALE_MODE_Max = 0x7FFFFFFF +} QOMX_SCALE_MODETYPE; + +typedef struct QOMX_SCALINGMODETYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + QOMX_SCALE_MODETYPE eScaleMode; +} QOMX_SCALINGMODETYPE; + +typedef struct QOMX_NOISEREDUCTIONTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bEnable; + OMX_BOOL bAutoMode; + OMX_S32 nNoiseReduction; +} QOMX_NOISEREDUCTIONTYPE; + +typedef struct QOMX_IMAGEENHANCEMENTTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bEnable; + OMX_BOOL bAutoMode; + OMX_S32 nImageEnhancement; +} QOMX_IMAGEENHANCEMENTTYPE; + +/* + * these are part of OMX1.2 but JB MR2 branch doesn't have them defined + * OMX_IndexParamInterlaceFormat + * OMX_INTERLACEFORMATTYPE + */ +#ifndef OMX_IndexParamInterlaceFormat +#define OMX_IndexParamInterlaceFormat (0x7FF00000) +typedef struct OMX_INTERLACEFORMATTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nFormat; + OMX_TICKS nTimeStamp; +} OMX_INTERLACEFORMATTYPE; +#endif + +/** + * This structure is used to indicate the maximum number of buffers + * that a port will hold during data flow. + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version info + * nPortIndex : Port that this structure applies to + * nHeldBufferCount : Read-only, maximum number of buffers that will be held + */ +typedef struct QOMX_HELDBUFFERCOUNTTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nHeldBufferCount; +} QOMX_HELDBUFFERCOUNTTYPE; + +typedef enum QOMX_VIDEO_HIERARCHICALCODINGTYPE { + QOMX_HIERARCHICALCODING_P = 0x01, + QOMX_HIERARCHICALCODING_B = 0x02, +} QOMX_VIDEO_HIERARCHICALCODINGTYPE; + +typedef struct QOMX_VIDEO_HIERARCHICALLAYERS { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nNumLayers; + QOMX_VIDEO_HIERARCHICALCODINGTYPE eHierarchicalCodingType; +} QOMX_VIDEO_HIERARCHICALLAYERS; + +typedef struct QOMX_VIDEO_H264ENTROPYCODINGTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_BOOL bCabac; + OMX_U32 nCabacInitIdc; +} QOMX_VIDEO_H264ENTROPYCODINGTYPE; + + +/* VIDEO POSTPROCESSING CTRLS AND ENUMS */ +#define QOMX_VPP_HQV_CUSTOMPAYLOAD_SZ 256 +#define VPP_HQV_CONTROL_GLOBAL_START (VPP_HQV_CONTROL_CUST + 1) + +typedef enum QOMX_VPP_HQV_MODE { + VPP_HQV_MODE_OFF, + VPP_HQV_MODE_AUTO, + VPP_HQV_MODE_MANUAL, + VPP_HQV_MODE_MAX +} QOMX_VPP_HQV_MODE; + +typedef enum QOMX_VPP_HQVCONTROLTYPE { + VPP_HQV_CONTROL_CADE = 0x1, + VPP_HQV_CONTROL_CNR = 0x04, + VPP_HQV_CONTROL_AIE = 0x05, + VPP_HQV_CONTROL_FRC = 0x06, + VPP_HQV_CONTROL_CUST = 0x07, + VPP_HQV_CONTROL_GLOBAL_DEMO = VPP_HQV_CONTROL_GLOBAL_START, + VPP_HQV_CONTROL_MAX, +} QOMX_VPP_HQVCONTROLTYPE; + +typedef enum QOMX_VPP_HQV_HUE_MODE { + VPP_HQV_HUE_MODE_OFF, + VPP_HQV_HUE_MODE_ON, + VPP_HQV_HUE_MODE_MAX, +} QOMX_VPP_HQV_HUE_MODE; + +typedef enum QOMX_VPP_HQV_FRC_MODE { + VPP_HQV_FRC_MODE_OFF, + VPP_HQV_FRC_MODE_LOW, + VPP_HQV_FRC_MODE_MED, + VPP_HQV_FRC_MODE_HIGH, + VPP_HQV_FRC_MODE_MAX, +} QOMX_VPP_HQV_FRC_MODE; + + +typedef struct QOMX_VPP_HQVCTRL_CADE { + QOMX_VPP_HQV_MODE mode; + OMX_U32 level; + OMX_S32 contrast; + OMX_S32 saturation; +} QOMX_VPP_HQVCTRL_CADE; + +typedef struct QOMX_VPP_HQVCTRL_CNR { + QOMX_VPP_HQV_MODE mode; + OMX_U32 level; +} QOMX_VPP_HQVCTRL_CNR; + +typedef struct QOMX_VPP_HQVCTRL_AIE { + QOMX_VPP_HQV_MODE mode; + QOMX_VPP_HQV_HUE_MODE hue_mode; + OMX_U32 cade_level; + OMX_U32 ltm_level; +} QOMX_VPP_HQVCTRL_AIE; + +typedef struct QOMX_VPP_HQVCTRL_CUSTOM { + OMX_U32 id; + OMX_U32 len; + OMX_U8 data[QOMX_VPP_HQV_CUSTOMPAYLOAD_SZ]; +} QOMX_VPP_HQVCTRL_CUSTOM; + +typedef struct QOMX_VPP_HQVCTRL_GLOBAL_DEMO { + OMX_U32 process_percent; +} QOMX_VPP_HQVCTRL_GLOBAL_DEMO; + +typedef struct QOMX_VPP_HQVCTRL_FRC { + QOMX_VPP_HQV_FRC_MODE mode; +} QOMX_VPP_HQVCTRL_FRC; + +typedef struct QOMX_VPP_HQVCONTROL { + QOMX_VPP_HQV_MODE mode; + QOMX_VPP_HQVCONTROLTYPE ctrl_type; + union { + QOMX_VPP_HQVCTRL_CADE cade; + QOMX_VPP_HQVCTRL_CNR cnr; + QOMX_VPP_HQVCTRL_AIE aie; + QOMX_VPP_HQVCTRL_CUSTOM custom; + QOMX_VPP_HQVCTRL_GLOBAL_DEMO global_demo; + QOMX_VPP_HQVCTRL_FRC frc; + }; +} QOMX_VPP_HQVCONTROL; + +/* STRUCTURE TO TURN VPP ON */ +typedef struct QOMX_VPP_ENABLE { + OMX_BOOL enable_vpp; +} QOMX_VPP_ENABLE; + +typedef enum OMX_QOMX_VIDEO_MBISTATISTICSTYPE { + QOMX_MBI_STATISTICS_MODE_DEFAULT = 0, + QOMX_MBI_STATISTICS_MODE_1 = 0x01, + QOMX_MBI_STATISTICS_MODE_2 = 0x02, +} OMX_QOMX_VIDEO_MBISTATISTICSTYPE; + +typedef struct OMX_QOMX_VIDEO_MBI_STATISTICS { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_QOMX_VIDEO_MBISTATISTICSTYPE eMBIStatisticsType; +} OMX_QOMX_VIDEO_MBI_STATISTICS; + +typedef struct QOMX_VIDEO_BATCHSIZETYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nBatchSize; +} QOMX_VIDEO_BATCHSIZETYPE; + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* __OMX_QCOM_EXTENSIONS_H__ */ diff --git a/phonelibs/openmax/include/OMX_Skype_VideoExtensions.h b/phonelibs/openmax/include/OMX_Skype_VideoExtensions.h new file mode 100644 index 0000000000..5cc832930f --- /dev/null +++ b/phonelibs/openmax/include/OMX_Skype_VideoExtensions.h @@ -0,0 +1,155 @@ +/*@@@+++@@@@****************************************************************** + + Microsoft Skype Engineering + Copyright (C) 2014 Microsoft Corporation. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +*@@@---@@@@******************************************************************/ + + +#ifndef __OMX_SKYPE_VIDEOEXTENSIONS_H__ +#define __OMX_SKYPE_VIDEOEXTENSIONS_H__ + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include + +#pragma pack(push, 1) + + +typedef enum OMX_SKYPE_VIDEO_SliceControlMode +{ + OMX_SKYPE_VIDEO_SliceControlModeNone = 0, + OMX_SKYPE_VIDEO_SliceControlModeMB = 1, + OMX_SKYPE_VIDEO_SliceControlModeByte = 2, + OMX_SKYPE_VIDEO_SliceControlModMBRow = 3, +} OMX_SKYPE_VIDEO_SliceControlMode; + + +typedef enum OMX_SKYPE_VIDEO_HierarType +{ + OMX_SKYPE_VIDEO_HierarType_P = 0x01, + OMX_SKYPE_VIDEO_HierarType_B = 0x02, +} OMX_SKYPE_VIDEO_HIERAR_HierarType; + +typedef enum OMX_VIDEO_EXTENSION_AVCPROFILETYPE +{ + OMX_VIDEO_EXT_AVCProfileConstrainedBaseline = 0x01, + OMX_VIDEO_EXT_AVCProfileConstrainedHigh = 0x02, +} OMX_VIDEO_EXTENSION_AVCPROFILETYPE; + +typedef struct OMX_SKYPE_VIDEO_ENCODERPARAMS { + OMX_BOOL bLowLatency; + OMX_BOOL bUseExtendedProfile; + OMX_BOOL bSequenceHeaderWithIDR; + OMX_VIDEO_EXTENSION_AVCPROFILETYPE eProfile; + OMX_U32 nLTRFrames; + OMX_SKYPE_VIDEO_HierarType eHierarType; + OMX_U32 nMaxTemporalLayerCount; + OMX_SKYPE_VIDEO_SliceControlMode eSliceControlMode; + OMX_U32 nSarIndex; + OMX_U32 nSarWidth; + OMX_U32 nSarHeight; +} OMX_SKYPE_VIDEO_ENCODERPARAMS; + +typedef struct OMX_SKYPE_VIDEO_PARAM_ENCODERSETTING { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_SKYPE_VIDEO_ENCODERPARAMS stEncParam; +} OMX_SKYPE_VIDEO_PARAM_ENCODESETTING; + +typedef struct OMX_SKYPE_VIDEO_ENCODERCAP { + OMX_BOOL bLowLatency; + OMX_U32 nMaxFrameWidth; + OMX_U32 nMaxFrameHeight; + OMX_U32 nMaxInstances; + OMX_U32 nMaxTemporaLayerCount; + OMX_U32 nMaxRefFrames; + OMX_U32 nMaxLTRFrames; + OMX_VIDEO_AVCLEVELTYPE nMaxLevel; + OMX_U32 nSliceControlModesBM; + OMX_U32 nMaxMacroblockProcessingRate; + OMX_U32 xMinScaleFactor; +} OMX_SKYPE_VIDEO_ENCODERCAP; + +typedef struct OMX_SKYPE_VIDEO_PARAM_ENCODERCAP { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_SKYPE_VIDEO_ENCODERCAP stEncCap; +} OMX_SKYPE_VIDEO_PARAM_ENCODERCAP; + +typedef struct OMX_SKYPE_VIDEO_DECODERCAP { + OMX_BOOL bLowLatency; + OMX_U32 nMaxFrameWidth; + OMX_U32 nMaxFrameHeight; + OMX_U32 nMaxInstances; + OMX_VIDEO_AVCLEVELTYPE nMaxLevel; + OMX_U32 nMaxMacroblockProcessingRate; +} OMX_SKYPE_VIDEO_DECODERCAP; + +typedef struct OMX_SKYPE_VIDEO_PARAM_DECODERCAP { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_SKYPE_VIDEO_DECODERCAP stDecoderCap; +} OMX_SKYPE_VIDEO_PARAM_DECODERCAP; + +typedef struct OMX_SKYPE_VIDEO_CONFIG_QP { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nQP; +} OMX_SKYPE_VIDEO_CONFIG_QP; + +typedef struct OMX_SKYPE_VIDEO_CONFIG_BASELAYERPID{ + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nPID; +} OMX_SKYPE_VIDEO_CONFIG_BASELAYERPID; + +typedef struct OMX_SKYPE_VIDEO_PARAM_DRIVERVER { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U64 nDriverVersion; +} OMX_SKYPE_VIDEO_PARAM_DRIVERVER; + +typedef enum OMX_SKYPE_VIDEO_DownScaleFactor +{ + OMX_SKYPE_VIDEO_DownScaleFactor_1_1 = 0, + OMX_SKYPE_VIDEO_DownScaleFactor_Equal_AR = 1, + OMX_SKYPE_VIDEO_DownScaleFactor_Any = 2, +} OMX_SKYPE_VIDEO_DownScaleFactor; + +#pragma pack(pop) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/phonelibs/openmax/include/OMX_Types.h b/phonelibs/openmax/include/OMX_Types.h new file mode 100644 index 0000000000..3b9fab4fc2 --- /dev/null +++ b/phonelibs/openmax/include/OMX_Types.h @@ -0,0 +1,359 @@ +/* + * Copyright (c) 2008 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** OMX_Types.h - OpenMax IL version 1.1.2 + * The OMX_Types header file contains the primitive type definitions used by + * the core, the application and the component. This file may need to be + * modified to be used on systems that do not have "char" set to 8 bits, + * "short" set to 16 bits and "long" set to 32 bits. + */ + +#ifndef OMX_Types_h +#define OMX_Types_h + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** The OMX_API and OMX_APIENTRY are platform specific definitions used + * to declare OMX function prototypes. They are modified to meet the + * requirements for a particular platform */ +#ifdef __SYMBIAN32__ +# ifdef __OMX_EXPORTS +# define OMX_API __declspec(dllexport) +# else +# ifdef _WIN32 +# define OMX_API __declspec(dllexport) +# else +# define OMX_API __declspec(dllimport) +# endif +# endif +#else +# ifdef _WIN32 +# ifdef __OMX_EXPORTS +# define OMX_API __declspec(dllexport) +# else +# define OMX_API __declspec(dllimport) +# endif +# else +# ifdef __OMX_EXPORTS +# define OMX_API +# else +# define OMX_API extern +# endif +# endif +#endif + +#ifndef OMX_APIENTRY +#define OMX_APIENTRY +#endif + +/** OMX_IN is used to identify inputs to an OMX function. This designation + will also be used in the case of a pointer that points to a parameter + that is used as an output. */ +#ifndef OMX_IN +#define OMX_IN +#endif + +/** OMX_OUT is used to identify outputs from an OMX function. This + designation will also be used in the case of a pointer that points + to a parameter that is used as an input. */ +#ifndef OMX_OUT +#define OMX_OUT +#endif + + +/** OMX_INOUT is used to identify parameters that may be either inputs or + outputs from an OMX function at the same time. This designation will + also be used in the case of a pointer that points to a parameter that + is used both as an input and an output. */ +#ifndef OMX_INOUT +#define OMX_INOUT +#endif + +/** OMX_ALL is used to as a wildcard to select all entities of the same type + * when specifying the index, or referring to a object by an index. (i.e. + * use OMX_ALL to indicate all N channels). When used as a port index + * for a config or parameter this OMX_ALL denotes that the config or + * parameter applies to the entire component not just one port. */ +#define OMX_ALL 0xFFFFFFFF + +/** In the following we define groups that help building doxygen documentation */ + +/** @defgroup core OpenMAX IL core + * Functions and structure related to the OMX IL core + */ + + /** @defgroup comp OpenMAX IL component + * Functions and structure related to the OMX IL component + */ + +/** @defgroup rpm Resource and Policy Management + * Structures for resource and policy management of components + */ + +/** @defgroup buf Buffer Management + * Buffer handling functions and structures + */ + +/** @defgroup tun Tunneling + * @ingroup core comp + * Structures and functions to manage tunnels among component ports + */ + +/** @defgroup cp Content Pipes + * @ingroup core + */ + + /** @defgroup metadata Metadata handling + * + */ + +/** OMX_U8 is an 8 bit unsigned quantity that is byte aligned */ +typedef unsigned char OMX_U8; + +/** OMX_S8 is an 8 bit signed quantity that is byte aligned */ +typedef signed char OMX_S8; + +/** OMX_U16 is a 16 bit unsigned quantity that is 16 bit word aligned */ +typedef unsigned short OMX_U16; + +/** OMX_S16 is a 16 bit signed quantity that is 16 bit word aligned */ +typedef signed short OMX_S16; + +/** OMX_U32 is a 32 bit unsigned quantity that is 32 bit word aligned */ +typedef unsigned int OMX_U32; + +/** OMX_S32 is a 32 bit signed quantity that is 32 bit word aligned */ +typedef signed int OMX_S32; + + +/* Users with compilers that cannot accept the "long long" designation should + define the OMX_SKIP64BIT macro. It should be noted that this may cause + some components to fail to compile if the component was written to require + 64 bit integral types. However, these components would NOT compile anyway + since the compiler does not support the way the component was written. +*/ +#ifndef OMX_SKIP64BIT +#ifdef __SYMBIAN32__ +/** OMX_U64 is a 64 bit unsigned quantity that is 64 bit word aligned */ +typedef unsigned long long OMX_U64; + +/** OMX_S64 is a 64 bit signed quantity that is 64 bit word aligned */ +typedef signed long long OMX_S64; + +#elif defined(WIN32) + +/** OMX_U64 is a 64 bit unsigned quantity that is 64 bit word aligned */ +typedef unsigned __int64 OMX_U64; + +/** OMX_S64 is a 64 bit signed quantity that is 64 bit word aligned */ +typedef signed __int64 OMX_S64; + +#else /* WIN32 */ + +/** OMX_U64 is a 64 bit unsigned quantity that is 64 bit word aligned */ +typedef unsigned long long OMX_U64; + +/** OMX_S64 is a 64 bit signed quantity that is 64 bit word aligned */ +typedef signed long long OMX_S64; + +#endif /* WIN32 */ +#endif + + +/** The OMX_BOOL type is intended to be used to represent a true or a false + value when passing parameters to and from the OMX core and components. The + OMX_BOOL is a 32 bit quantity and is aligned on a 32 bit word boundary. + */ +typedef enum OMX_BOOL { + OMX_FALSE = 0, + OMX_TRUE = !OMX_FALSE, + OMX_BOOL_MAX = 0x7FFFFFFF +} OMX_BOOL; + +#ifdef OMX_ANDROID_COMPILE_AS_32BIT_ON_64BIT_PLATFORMS + +typedef OMX_U32 OMX_PTR; +typedef OMX_PTR OMX_STRING; +typedef OMX_PTR OMX_BYTE; + +#else + +/** The OMX_PTR type is intended to be used to pass pointers between the OMX + applications and the OMX Core and components. This is a 32 bit pointer and + is aligned on a 32 bit boundary. + */ +typedef void* OMX_PTR; + +/** The OMX_STRING type is intended to be used to pass "C" type strings between + the application and the core and component. The OMX_STRING type is a 32 + bit pointer to a zero terminated string. The pointer is word aligned and + the string is byte aligned. + */ +typedef char* OMX_STRING; + +/** The OMX_BYTE type is intended to be used to pass arrays of bytes such as + buffers between the application and the component and core. The OMX_BYTE + type is a 32 bit pointer to a zero terminated string. The pointer is word + aligned and the string is byte aligned. + */ +typedef unsigned char* OMX_BYTE; + +/** OMX_UUIDTYPE is a very long unique identifier to uniquely identify + at runtime. This identifier should be generated by a component in a way + that guarantees that every instance of the identifier running on the system + is unique. */ + + +#endif + +typedef unsigned char OMX_UUIDTYPE[128]; + +/** The OMX_DIRTYPE enumeration is used to indicate if a port is an input or + an output port. This enumeration is common across all component types. + */ +typedef enum OMX_DIRTYPE +{ + OMX_DirInput, /**< Port is an input port */ + OMX_DirOutput, /**< Port is an output port */ + OMX_DirMax = 0x7FFFFFFF +} OMX_DIRTYPE; + +/** The OMX_ENDIANTYPE enumeration is used to indicate the bit ordering + for numerical data (i.e. big endian, or little endian). + */ +typedef enum OMX_ENDIANTYPE +{ + OMX_EndianBig, /**< big endian */ + OMX_EndianLittle, /**< little endian */ + OMX_EndianMax = 0x7FFFFFFF +} OMX_ENDIANTYPE; + + +/** The OMX_NUMERICALDATATYPE enumeration is used to indicate if data + is signed or unsigned + */ +typedef enum OMX_NUMERICALDATATYPE +{ + OMX_NumericalDataSigned, /**< signed data */ + OMX_NumericalDataUnsigned, /**< unsigned data */ + OMX_NumercialDataMax = 0x7FFFFFFF +} OMX_NUMERICALDATATYPE; + + +/** Unsigned bounded value type */ +typedef struct OMX_BU32 { + OMX_U32 nValue; /**< actual value */ + OMX_U32 nMin; /**< minimum for value (i.e. nValue >= nMin) */ + OMX_U32 nMax; /**< maximum for value (i.e. nValue <= nMax) */ +} OMX_BU32; + + +/** Signed bounded value type */ +typedef struct OMX_BS32 { + OMX_S32 nValue; /**< actual value */ + OMX_S32 nMin; /**< minimum for value (i.e. nValue >= nMin) */ + OMX_S32 nMax; /**< maximum for value (i.e. nValue <= nMax) */ +} OMX_BS32; + + +/** Structure representing some time or duration in microseconds. This structure + * must be interpreted as a signed 64 bit value. The quantity is signed to accommodate + * negative deltas and preroll scenarios. The quantity is represented in microseconds + * to accomodate high resolution timestamps (e.g. DVD presentation timestamps based + * on a 90kHz clock) and to allow more accurate and synchronized delivery (e.g. + * individual audio samples delivered at 192 kHz). The quantity is 64 bit to + * accommodate a large dynamic range (signed 32 bit values would allow only for plus + * or minus 35 minutes). + * + * Implementations with limited precision may convert the signed 64 bit value to + * a signed 32 bit value internally but risk loss of precision. + */ +#ifndef OMX_SKIP64BIT +typedef OMX_S64 OMX_TICKS; +#else +typedef struct OMX_TICKS +{ + OMX_U32 nLowPart; /** low bits of the signed 64 bit tick value */ + OMX_U32 nHighPart; /** high bits of the signed 64 bit tick value */ +} OMX_TICKS; +#endif +#define OMX_TICKS_PER_SECOND 1000000 + +/** Define the public interface for the OMX Handle. The core will not use + this value internally, but the application should only use this value. + */ +typedef void* OMX_HANDLETYPE; + +typedef struct OMX_MARKTYPE +{ + OMX_HANDLETYPE hMarkTargetComponent; /**< The component that will + generate a mark event upon + processing the mark. */ + OMX_PTR pMarkData; /**< Application specific data associated with + the mark sent on a mark event to disambiguate + this mark from others. */ +} OMX_MARKTYPE; + + +/** OMX_NATIVE_DEVICETYPE is used to map a OMX video port to the + * platform & operating specific object used to reference the display + * or can be used by a audio port for native audio rendering */ +typedef void* OMX_NATIVE_DEVICETYPE; + +/** OMX_NATIVE_WINDOWTYPE is used to map a OMX video port to the + * platform & operating specific object used to reference the window */ +typedef void* OMX_NATIVE_WINDOWTYPE; + +/** The OMX_VERSIONTYPE union is used to specify the version for + a structure or component. For a component, the version is entirely + specified by the component vendor. Components doing the same function + from different vendors may or may not have the same version. For + structures, the version shall be set by the entity that allocates the + structure. For structures specified in the OMX 1.1 specification, the + value of the version shall be set to 1.1.0.0 in all cases. Access to the + OMX_VERSIONTYPE can be by a single 32 bit access (e.g. by nVersion) or + by accessing one of the structure elements to, for example, check only + the Major revision. + */ +typedef union OMX_VERSIONTYPE +{ + struct + { + OMX_U8 nVersionMajor; /**< Major version accessor element */ + OMX_U8 nVersionMinor; /**< Minor version accessor element */ + OMX_U8 nRevision; /**< Revision version accessor element */ + OMX_U8 nStep; /**< Step version accessor element */ + } s; + OMX_U32 nVersion; /**< 32 bit value to make accessing the + version easily done in a single word + size copy/compare operation */ +} OMX_VERSIONTYPE; + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif +/* File EOF */ diff --git a/phonelibs/openmax/include/OMX_Video.h b/phonelibs/openmax/include/OMX_Video.h new file mode 100644 index 0000000000..64dbe87b43 --- /dev/null +++ b/phonelibs/openmax/include/OMX_Video.h @@ -0,0 +1,1082 @@ +/** + * Copyright (c) 2008 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** + * @file OMX_Video.h - OpenMax IL version 1.1.2 + * The structures is needed by Video components to exchange parameters + * and configuration data with OMX components. + */ +#ifndef OMX_Video_h +#define OMX_Video_h + +/** @defgroup video OpenMAX IL Video Domain + * @ingroup iv + * Structures for OpenMAX IL Video domain + * @{ + */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +/** + * Each OMX header must include all required header files to allow the + * header to compile without errors. The includes below are required + * for this header file to compile successfully + */ + +#include + + +/** + * Enumeration used to define the possible video compression codings. + * NOTE: This essentially refers to file extensions. If the coding is + * being used to specify the ENCODE type, then additional work + * must be done to configure the exact flavor of the compression + * to be used. For decode cases where the user application can + * not differentiate between MPEG-4 and H.264 bit streams, it is + * up to the codec to handle this. + */ +typedef enum OMX_VIDEO_CODINGTYPE { + OMX_VIDEO_CodingUnused, /**< Value when coding is N/A */ + OMX_VIDEO_CodingAutoDetect, /**< Autodetection of coding type */ + OMX_VIDEO_CodingMPEG2, /**< AKA: H.262 */ + OMX_VIDEO_CodingH263, /**< H.263 */ + OMX_VIDEO_CodingMPEG4, /**< MPEG-4 */ + OMX_VIDEO_CodingWMV, /**< all versions of Windows Media Video */ + OMX_VIDEO_CodingRV, /**< all versions of Real Video */ + OMX_VIDEO_CodingAVC, /**< H.264/AVC */ + OMX_VIDEO_CodingMJPEG, /**< Motion JPEG */ + OMX_VIDEO_CodingVP8, /**< Google VP8, formerly known as On2 VP8 */ + OMX_VIDEO_CodingVP9, /**< Google VP9 */ + OMX_VIDEO_CodingHEVC, /**< HEVC */ + OMX_VIDEO_CodingKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_CodingVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_CodingMax = 0x7FFFFFFF +} OMX_VIDEO_CODINGTYPE; + + +/** + * Data structure used to define a video path. The number of Video paths for + * input and output will vary by type of the Video component. + * + * Input (aka Source) : zero Inputs, one Output, + * Splitter : one Input, 2 or more Outputs, + * Processing Element : one Input, one output, + * Mixer : 2 or more inputs, one output, + * Output (aka Sink) : one Input, zero outputs. + * + * The PortDefinition structure is used to define all of the parameters + * necessary for the compliant component to setup an input or an output video + * path. If additional vendor specific data is required, it should be + * transmitted to the component using the CustomCommand function. Compliant + * components will prepopulate this structure with optimal values during the + * GetDefaultInitParams command. + * + * STRUCT MEMBERS: + * cMIMEType : MIME type of data for the port + * pNativeRender : Platform specific reference for a display if a + * sync, otherwise this field is 0 + * nFrameWidth : Width of frame to be used on channel if + * uncompressed format is used. Use 0 for unknown, + * don't care or variable + * nFrameHeight : Height of frame to be used on channel if + * uncompressed format is used. Use 0 for unknown, + * don't care or variable + * nStride : Number of bytes per span of an image + * (i.e. indicates the number of bytes to get + * from span N to span N+1, where negative stride + * indicates the image is bottom up + * nSliceHeight : Height used when encoding in slices + * nBitrate : Bit rate of frame to be used on channel if + * compressed format is used. Use 0 for unknown, + * don't care or variable + * xFramerate : Frame rate to be used on channel if uncompressed + * format is used. Use 0 for unknown, don't care or + * variable. Units are Q16 frames per second. + * bFlagErrorConcealment : Turns on error concealment if it is supported by + * the OMX component + * eCompressionFormat : Compression format used in this instance of the + * component. When OMX_VIDEO_CodingUnused is + * specified, eColorFormat is used + * eColorFormat : Decompressed format used by this component + * pNativeWindow : Platform specific reference for a window object if a + * display sink , otherwise this field is 0x0. + */ +typedef struct OMX_VIDEO_PORTDEFINITIONTYPE { + OMX_STRING cMIMEType; + OMX_NATIVE_DEVICETYPE pNativeRender; + OMX_U32 nFrameWidth; + OMX_U32 nFrameHeight; + OMX_S32 nStride; + OMX_U32 nSliceHeight; + OMX_U32 nBitrate; + OMX_U32 xFramerate; + OMX_BOOL bFlagErrorConcealment; + OMX_VIDEO_CODINGTYPE eCompressionFormat; + OMX_COLOR_FORMATTYPE eColorFormat; + OMX_NATIVE_WINDOWTYPE pNativeWindow; +} OMX_VIDEO_PORTDEFINITIONTYPE; + +/** + * Port format parameter. This structure is used to enumerate the various + * data input/output format supported by the port. + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Indicates which port to set + * nIndex : Indicates the enumeration index for the format from + * 0x0 to N-1 + * eCompressionFormat : Compression format used in this instance of the + * component. When OMX_VIDEO_CodingUnused is specified, + * eColorFormat is used + * eColorFormat : Decompressed format used by this component + * xFrameRate : Indicates the video frame rate in Q16 format + */ +typedef struct OMX_VIDEO_PARAM_PORTFORMATTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nIndex; + OMX_VIDEO_CODINGTYPE eCompressionFormat; + OMX_COLOR_FORMATTYPE eColorFormat; + OMX_U32 xFramerate; +} OMX_VIDEO_PARAM_PORTFORMATTYPE; + + +/** + * This is a structure for configuring video compression quantization + * parameter values. Codecs may support different QP values for different + * frame types. + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version info + * nPortIndex : Port that this structure applies to + * nQpI : QP value to use for index frames + * nQpP : QP value to use for P frames + * nQpB : QP values to use for bidirectional frames + */ +typedef struct OMX_VIDEO_PARAM_QUANTIZATIONTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nQpI; + OMX_U32 nQpP; + OMX_U32 nQpB; +} OMX_VIDEO_PARAM_QUANTIZATIONTYPE; + + +/** + * Structure for configuration of video fast update parameters. + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version info + * nPortIndex : Port that this structure applies to + * bEnableVFU : Enable/Disable video fast update + * nFirstGOB : Specifies the number of the first macroblock row + * nFirstMB : specifies the first MB relative to the specified first GOB + * nNumMBs : Specifies the number of MBs to be refreshed from nFirstGOB + * and nFirstMB + */ +typedef struct OMX_VIDEO_PARAM_VIDEOFASTUPDATETYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bEnableVFU; + OMX_U32 nFirstGOB; + OMX_U32 nFirstMB; + OMX_U32 nNumMBs; +} OMX_VIDEO_PARAM_VIDEOFASTUPDATETYPE; + + +/** + * Enumeration of possible bitrate control types + */ +typedef enum OMX_VIDEO_CONTROLRATETYPE { + OMX_Video_ControlRateDisable, + OMX_Video_ControlRateVariable, + OMX_Video_ControlRateConstant, + OMX_Video_ControlRateVariableSkipFrames, + OMX_Video_ControlRateConstantSkipFrames, + OMX_Video_ControlRateKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_Video_ControlRateVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_Video_ControlRateMax = 0x7FFFFFFF +} OMX_VIDEO_CONTROLRATETYPE; + + +/** + * Structure for configuring bitrate mode of a codec. + * + * STRUCT MEMBERS: + * nSize : Size of the struct in bytes + * nVersion : OMX spec version info + * nPortIndex : Port that this struct applies to + * eControlRate : Control rate type enum + * nTargetBitrate : Target bitrate to encode with + */ +typedef struct OMX_VIDEO_PARAM_BITRATETYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_VIDEO_CONTROLRATETYPE eControlRate; + OMX_U32 nTargetBitrate; +} OMX_VIDEO_PARAM_BITRATETYPE; + + +/** + * Enumeration of possible motion vector (MV) types + */ +typedef enum OMX_VIDEO_MOTIONVECTORTYPE { + OMX_Video_MotionVectorPixel, + OMX_Video_MotionVectorHalfPel, + OMX_Video_MotionVectorQuarterPel, + OMX_Video_MotionVectorEighthPel, + OMX_Video_MotionVectorKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_Video_MotionVectorVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_Video_MotionVectorMax = 0x7FFFFFFF +} OMX_VIDEO_MOTIONVECTORTYPE; + + +/** + * Structure for configuring the number of motion vectors used as well + * as their accuracy. + * + * STRUCT MEMBERS: + * nSize : Size of the struct in bytes + * nVersion : OMX spec version info + * nPortIndex : port that this structure applies to + * eAccuracy : Enumerated MV accuracy + * bUnrestrictedMVs : Allow unrestricted MVs + * bFourMV : Allow use of 4 MVs + * sXSearchRange : Search range in horizontal direction for MVs + * sYSearchRange : Search range in vertical direction for MVs + */ +typedef struct OMX_VIDEO_PARAM_MOTIONVECTORTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_VIDEO_MOTIONVECTORTYPE eAccuracy; + OMX_BOOL bUnrestrictedMVs; + OMX_BOOL bFourMV; + OMX_S32 sXSearchRange; + OMX_S32 sYSearchRange; +} OMX_VIDEO_PARAM_MOTIONVECTORTYPE; + + +/** + * Enumeration of possible methods to use for Intra Refresh + */ +typedef enum OMX_VIDEO_INTRAREFRESHTYPE { + OMX_VIDEO_IntraRefreshCyclic, + OMX_VIDEO_IntraRefreshAdaptive, + OMX_VIDEO_IntraRefreshBoth, + OMX_VIDEO_IntraRefreshKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_IntraRefreshVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_IntraRefreshRandom, + OMX_VIDEO_IntraRefreshMax = 0x7FFFFFFF +} OMX_VIDEO_INTRAREFRESHTYPE; + + +/** + * Structure for configuring intra refresh mode + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * eRefreshMode : Cyclic, Adaptive, or Both + * nAirMBs : Number of intra macroblocks to refresh in a frame when + * AIR is enabled + * nAirRef : Number of times a motion marked macroblock has to be + * intra coded + * nCirMBs : Number of consecutive macroblocks to be coded as "intra" + * when CIR is enabled + */ +typedef struct OMX_VIDEO_PARAM_INTRAREFRESHTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_VIDEO_INTRAREFRESHTYPE eRefreshMode; + OMX_U32 nAirMBs; + OMX_U32 nAirRef; + OMX_U32 nCirMBs; +} OMX_VIDEO_PARAM_INTRAREFRESHTYPE; + + +/** + * Structure for enabling various error correction methods for video + * compression. + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * bEnableHEC : Enable/disable header extension codes (HEC) + * bEnableResync : Enable/disable resynchronization markers + * nResynchMarkerSpacing : Resynch markers interval (in bits) to be + * applied in the stream + * bEnableDataPartitioning : Enable/disable data partitioning + * bEnableRVLC : Enable/disable reversible variable length + * coding + */ +typedef struct OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bEnableHEC; + OMX_BOOL bEnableResync; + OMX_U32 nResynchMarkerSpacing; + OMX_BOOL bEnableDataPartitioning; + OMX_BOOL bEnableRVLC; +} OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE; + + +/** + * Configuration of variable block-size motion compensation (VBSMC) + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * b16x16 : Enable inter block search 16x16 + * b16x8 : Enable inter block search 16x8 + * b8x16 : Enable inter block search 8x16 + * b8x8 : Enable inter block search 8x8 + * b8x4 : Enable inter block search 8x4 + * b4x8 : Enable inter block search 4x8 + * b4x4 : Enable inter block search 4x4 + */ +typedef struct OMX_VIDEO_PARAM_VBSMCTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL b16x16; + OMX_BOOL b16x8; + OMX_BOOL b8x16; + OMX_BOOL b8x8; + OMX_BOOL b8x4; + OMX_BOOL b4x8; + OMX_BOOL b4x4; +} OMX_VIDEO_PARAM_VBSMCTYPE; + + +/** + * H.263 profile types, each profile indicates support for various + * performance bounds and different annexes. + * + * ENUMS: + * Baseline : Baseline Profile: H.263 (V1), no optional modes + * H320 Coding : H.320 Coding Efficiency Backward Compatibility + * Profile: H.263+ (V2), includes annexes I, J, L.4 + * and T + * BackwardCompatible : Backward Compatibility Profile: H.263 (V1), + * includes annex F + * ISWV2 : Interactive Streaming Wireless Profile: H.263+ + * (V2), includes annexes I, J, K and T + * ISWV3 : Interactive Streaming Wireless Profile: H.263++ + * (V3), includes profile 3 and annexes V and W.6.3.8 + * HighCompression : Conversational High Compression Profile: H.263++ + * (V3), includes profiles 1 & 2 and annexes D and U + * Internet : Conversational Internet Profile: H.263++ (V3), + * includes profile 5 and annex K + * Interlace : Conversational Interlace Profile: H.263++ (V3), + * includes profile 5 and annex W.6.3.11 + * HighLatency : High Latency Profile: H.263++ (V3), includes + * profile 6 and annexes O.1 and P.5 + */ +typedef enum OMX_VIDEO_H263PROFILETYPE { + OMX_VIDEO_H263ProfileBaseline = 0x01, + OMX_VIDEO_H263ProfileH320Coding = 0x02, + OMX_VIDEO_H263ProfileBackwardCompatible = 0x04, + OMX_VIDEO_H263ProfileISWV2 = 0x08, + OMX_VIDEO_H263ProfileISWV3 = 0x10, + OMX_VIDEO_H263ProfileHighCompression = 0x20, + OMX_VIDEO_H263ProfileInternet = 0x40, + OMX_VIDEO_H263ProfileInterlace = 0x80, + OMX_VIDEO_H263ProfileHighLatency = 0x100, + OMX_VIDEO_H263ProfileKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_H263ProfileVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_H263ProfileMax = 0x7FFFFFFF +} OMX_VIDEO_H263PROFILETYPE; + + +/** + * H.263 level types, each level indicates support for various frame sizes, + * bit rates, decoder frame rates. + */ +typedef enum OMX_VIDEO_H263LEVELTYPE { + OMX_VIDEO_H263Level10 = 0x01, + OMX_VIDEO_H263Level20 = 0x02, + OMX_VIDEO_H263Level30 = 0x04, + OMX_VIDEO_H263Level40 = 0x08, + OMX_VIDEO_H263Level45 = 0x10, + OMX_VIDEO_H263Level50 = 0x20, + OMX_VIDEO_H263Level60 = 0x40, + OMX_VIDEO_H263Level70 = 0x80, + OMX_VIDEO_H263LevelKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_H263LevelVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_H263LevelMax = 0x7FFFFFFF +} OMX_VIDEO_H263LEVELTYPE; + + +/** + * Specifies the picture type. These values should be OR'd to signal all + * pictures types which are allowed. + * + * ENUMS: + * Generic Picture Types: I, P and B + * H.263 Specific Picture Types: SI and SP + * H.264 Specific Picture Types: EI and EP + * MPEG-4 Specific Picture Types: S + */ +typedef enum OMX_VIDEO_PICTURETYPE { + OMX_VIDEO_PictureTypeI = 0x01, + OMX_VIDEO_PictureTypeP = 0x02, + OMX_VIDEO_PictureTypeB = 0x04, + OMX_VIDEO_PictureTypeSI = 0x08, + OMX_VIDEO_PictureTypeSP = 0x10, + OMX_VIDEO_PictureTypeEI = 0x11, + OMX_VIDEO_PictureTypeEP = 0x12, + OMX_VIDEO_PictureTypeS = 0x14, + OMX_VIDEO_PictureTypeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_PictureTypeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_PictureTypeMax = 0x7FFFFFFF +} OMX_VIDEO_PICTURETYPE; + + +/** + * H.263 Params + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * nPFrames : Number of P frames between each I frame + * nBFrames : Number of B frames between each I frame + * eProfile : H.263 profile(s) to use + * eLevel : H.263 level(s) to use + * bPLUSPTYPEAllowed : Indicating that it is allowed to use PLUSPTYPE + * (specified in the 1998 version of H.263) to + * indicate custom picture sizes or clock + * frequencies + * nAllowedPictureTypes : Specifies the picture types allowed in the + * bitstream + * bForceRoundingTypeToZero : value of the RTYPE bit (bit 6 of MPPTYPE) is + * not constrained. It is recommended to change + * the value of the RTYPE bit for each reference + * picture in error-free communication + * nPictureHeaderRepetition : Specifies the frequency of picture header + * repetition + * nGOBHeaderInterval : Specifies the interval of non-empty GOB + * headers in units of GOBs + */ +typedef struct OMX_VIDEO_PARAM_H263TYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nPFrames; + OMX_U32 nBFrames; + OMX_VIDEO_H263PROFILETYPE eProfile; + OMX_VIDEO_H263LEVELTYPE eLevel; + OMX_BOOL bPLUSPTYPEAllowed; + OMX_U32 nAllowedPictureTypes; + OMX_BOOL bForceRoundingTypeToZero; + OMX_U32 nPictureHeaderRepetition; + OMX_U32 nGOBHeaderInterval; +} OMX_VIDEO_PARAM_H263TYPE; + + +/** + * MPEG-2 profile types, each profile indicates support for various + * performance bounds and different annexes. + */ +typedef enum OMX_VIDEO_MPEG2PROFILETYPE { + OMX_VIDEO_MPEG2ProfileSimple = 0, /**< Simple Profile */ + OMX_VIDEO_MPEG2ProfileMain, /**< Main Profile */ + OMX_VIDEO_MPEG2Profile422, /**< 4:2:2 Profile */ + OMX_VIDEO_MPEG2ProfileSNR, /**< SNR Profile */ + OMX_VIDEO_MPEG2ProfileSpatial, /**< Spatial Profile */ + OMX_VIDEO_MPEG2ProfileHigh, /**< High Profile */ + OMX_VIDEO_MPEG2ProfileKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_MPEG2ProfileVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_MPEG2ProfileMax = 0x7FFFFFFF +} OMX_VIDEO_MPEG2PROFILETYPE; + + +/** + * MPEG-2 level types, each level indicates support for various frame + * sizes, bit rates, decoder frame rates. No need + */ +typedef enum OMX_VIDEO_MPEG2LEVELTYPE { + OMX_VIDEO_MPEG2LevelLL = 0, /**< Low Level */ + OMX_VIDEO_MPEG2LevelML, /**< Main Level */ + OMX_VIDEO_MPEG2LevelH14, /**< High 1440 */ + OMX_VIDEO_MPEG2LevelHL, /**< High Level */ + OMX_VIDEO_MPEG2LevelKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_MPEG2LevelVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_MPEG2LevelMax = 0x7FFFFFFF +} OMX_VIDEO_MPEG2LEVELTYPE; + + +/** + * MPEG-2 params + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * nPFrames : Number of P frames between each I frame + * nBFrames : Number of B frames between each I frame + * eProfile : MPEG-2 profile(s) to use + * eLevel : MPEG-2 levels(s) to use + */ +typedef struct OMX_VIDEO_PARAM_MPEG2TYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nPFrames; + OMX_U32 nBFrames; + OMX_VIDEO_MPEG2PROFILETYPE eProfile; + OMX_VIDEO_MPEG2LEVELTYPE eLevel; +} OMX_VIDEO_PARAM_MPEG2TYPE; + + +/** + * MPEG-4 profile types, each profile indicates support for various + * performance bounds and different annexes. + * + * ENUMS: + * - Simple Profile, Levels 1-3 + * - Simple Scalable Profile, Levels 1-2 + * - Core Profile, Levels 1-2 + * - Main Profile, Levels 2-4 + * - N-bit Profile, Level 2 + * - Scalable Texture Profile, Level 1 + * - Simple Face Animation Profile, Levels 1-2 + * - Simple Face and Body Animation (FBA) Profile, Levels 1-2 + * - Basic Animated Texture Profile, Levels 1-2 + * - Hybrid Profile, Levels 1-2 + * - Advanced Real Time Simple Profiles, Levels 1-4 + * - Core Scalable Profile, Levels 1-3 + * - Advanced Coding Efficiency Profile, Levels 1-4 + * - Advanced Core Profile, Levels 1-2 + * - Advanced Scalable Texture, Levels 2-3 + */ +typedef enum OMX_VIDEO_MPEG4PROFILETYPE { + OMX_VIDEO_MPEG4ProfileSimple = 0x01, + OMX_VIDEO_MPEG4ProfileSimpleScalable = 0x02, + OMX_VIDEO_MPEG4ProfileCore = 0x04, + OMX_VIDEO_MPEG4ProfileMain = 0x08, + OMX_VIDEO_MPEG4ProfileNbit = 0x10, + OMX_VIDEO_MPEG4ProfileScalableTexture = 0x20, + OMX_VIDEO_MPEG4ProfileSimpleFace = 0x40, + OMX_VIDEO_MPEG4ProfileSimpleFBA = 0x80, + OMX_VIDEO_MPEG4ProfileBasicAnimated = 0x100, + OMX_VIDEO_MPEG4ProfileHybrid = 0x200, + OMX_VIDEO_MPEG4ProfileAdvancedRealTime = 0x400, + OMX_VIDEO_MPEG4ProfileCoreScalable = 0x800, + OMX_VIDEO_MPEG4ProfileAdvancedCoding = 0x1000, + OMX_VIDEO_MPEG4ProfileAdvancedCore = 0x2000, + OMX_VIDEO_MPEG4ProfileAdvancedScalable = 0x4000, + OMX_VIDEO_MPEG4ProfileAdvancedSimple = 0x8000, + OMX_VIDEO_MPEG4ProfileKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_MPEG4ProfileVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_MPEG4ProfileMax = 0x7FFFFFFF +} OMX_VIDEO_MPEG4PROFILETYPE; + + +/** + * MPEG-4 level types, each level indicates support for various frame + * sizes, bit rates, decoder frame rates. No need + */ +typedef enum OMX_VIDEO_MPEG4LEVELTYPE { + OMX_VIDEO_MPEG4Level0 = 0x01, /**< Level 0 */ + OMX_VIDEO_MPEG4Level0b = 0x02, /**< Level 0b */ + OMX_VIDEO_MPEG4Level1 = 0x04, /**< Level 1 */ + OMX_VIDEO_MPEG4Level2 = 0x08, /**< Level 2 */ + OMX_VIDEO_MPEG4Level3 = 0x10, /**< Level 3 */ + OMX_VIDEO_MPEG4Level4 = 0x20, /**< Level 4 */ + OMX_VIDEO_MPEG4Level4a = 0x40, /**< Level 4a */ + OMX_VIDEO_MPEG4Level5 = 0x80, /**< Level 5 */ + OMX_VIDEO_MPEG4LevelKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_MPEG4LevelVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_MPEG4LevelMax = 0x7FFFFFFF +} OMX_VIDEO_MPEG4LEVELTYPE; + + +/** + * MPEG-4 configuration. This structure handles configuration options + * which are specific to MPEG4 algorithms + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * nSliceHeaderSpacing : Number of macroblocks between slice header (H263+ + * Annex K). Put zero if not used + * bSVH : Enable Short Video Header mode + * bGov : Flag to enable GOV + * nPFrames : Number of P frames between each I frame (also called + * GOV period) + * nBFrames : Number of B frames between each I frame + * nIDCVLCThreshold : Value of intra DC VLC threshold + * bACPred : Flag to use ac prediction + * nMaxPacketSize : Maximum size of packet in bytes. + * nTimeIncRes : Used to pass VOP time increment resolution for MPEG4. + * Interpreted as described in MPEG4 standard. + * eProfile : MPEG-4 profile(s) to use. + * eLevel : MPEG-4 level(s) to use. + * nAllowedPictureTypes : Specifies the picture types allowed in the bitstream + * nHeaderExtension : Specifies the number of consecutive video packet + * headers within a VOP + * bReversibleVLC : Specifies whether reversible variable length coding + * is in use + */ +typedef struct OMX_VIDEO_PARAM_MPEG4TYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nSliceHeaderSpacing; + OMX_BOOL bSVH; + OMX_BOOL bGov; + OMX_U32 nPFrames; + OMX_U32 nBFrames; + OMX_U32 nIDCVLCThreshold; + OMX_BOOL bACPred; + OMX_U32 nMaxPacketSize; + OMX_U32 nTimeIncRes; + OMX_VIDEO_MPEG4PROFILETYPE eProfile; + OMX_VIDEO_MPEG4LEVELTYPE eLevel; + OMX_U32 nAllowedPictureTypes; + OMX_U32 nHeaderExtension; + OMX_BOOL bReversibleVLC; +} OMX_VIDEO_PARAM_MPEG4TYPE; + + +/** + * WMV Versions + */ +typedef enum OMX_VIDEO_WMVFORMATTYPE { + OMX_VIDEO_WMVFormatUnused = 0x01, /**< Format unused or unknown */ + OMX_VIDEO_WMVFormat7 = 0x02, /**< Windows Media Video format 7 */ + OMX_VIDEO_WMVFormat8 = 0x04, /**< Windows Media Video format 8 */ + OMX_VIDEO_WMVFormat9 = 0x08, /**< Windows Media Video format 9 */ + OMX_VIDEO_WMFFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_WMFFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_WMVFormatMax = 0x7FFFFFFF +} OMX_VIDEO_WMVFORMATTYPE; + + +/** + * WMV Params + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * eFormat : Version of WMV stream / data + */ +typedef struct OMX_VIDEO_PARAM_WMVTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_VIDEO_WMVFORMATTYPE eFormat; +} OMX_VIDEO_PARAM_WMVTYPE; + + +/** + * Real Video Version + */ +typedef enum OMX_VIDEO_RVFORMATTYPE { + OMX_VIDEO_RVFormatUnused = 0, /**< Format unused or unknown */ + OMX_VIDEO_RVFormat8, /**< Real Video format 8 */ + OMX_VIDEO_RVFormat9, /**< Real Video format 9 */ + OMX_VIDEO_RVFormatG2, /**< Real Video Format G2 */ + OMX_VIDEO_RVFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_RVFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_RVFormatMax = 0x7FFFFFFF +} OMX_VIDEO_RVFORMATTYPE; + + +/** + * Real Video Params + * + * STUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * eFormat : Version of RV stream / data + * nBitsPerPixel : Bits per pixel coded in the frame + * nPaddedWidth : Padded width in pixel of a video frame + * nPaddedHeight : Padded Height in pixels of a video frame + * nFrameRate : Rate of video in frames per second + * nBitstreamFlags : Flags which internal information about the bitstream + * nBitstreamVersion : Bitstream version + * nMaxEncodeFrameSize: Max encoded frame size + * bEnablePostFilter : Turn on/off post filter + * bEnableTemporalInterpolation : Turn on/off temporal interpolation + * bEnableLatencyMode : When enabled, the decoder does not display a decoded + * frame until it has detected that no enhancement layer + * frames or dependent B frames will be coming. This + * detection usually occurs when a subsequent non-B + * frame is encountered + */ +typedef struct OMX_VIDEO_PARAM_RVTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_VIDEO_RVFORMATTYPE eFormat; + OMX_U16 nBitsPerPixel; + OMX_U16 nPaddedWidth; + OMX_U16 nPaddedHeight; + OMX_U32 nFrameRate; + OMX_U32 nBitstreamFlags; + OMX_U32 nBitstreamVersion; + OMX_U32 nMaxEncodeFrameSize; + OMX_BOOL bEnablePostFilter; + OMX_BOOL bEnableTemporalInterpolation; + OMX_BOOL bEnableLatencyMode; +} OMX_VIDEO_PARAM_RVTYPE; + + +/** + * AVC profile types, each profile indicates support for various + * performance bounds and different annexes. + */ +typedef enum OMX_VIDEO_AVCPROFILETYPE { + OMX_VIDEO_AVCProfileBaseline = 0x01, /**< Baseline profile */ + OMX_VIDEO_AVCProfileMain = 0x02, /**< Main profile */ + OMX_VIDEO_AVCProfileExtended = 0x04, /**< Extended profile */ + OMX_VIDEO_AVCProfileHigh = 0x08, /**< High profile */ + OMX_VIDEO_AVCProfileHigh10 = 0x10, /**< High 10 profile */ + OMX_VIDEO_AVCProfileHigh422 = 0x20, /**< High 4:2:2 profile */ + OMX_VIDEO_AVCProfileHigh444 = 0x40, /**< High 4:4:4 profile */ + OMX_VIDEO_AVCProfileKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_AVCProfileVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_AVCProfileMax = 0x7FFFFFFF +} OMX_VIDEO_AVCPROFILETYPE; + + +/** + * AVC level types, each level indicates support for various frame sizes, + * bit rates, decoder frame rates. No need + */ +typedef enum OMX_VIDEO_AVCLEVELTYPE { + OMX_VIDEO_AVCLevel1 = 0x01, /**< Level 1 */ + OMX_VIDEO_AVCLevel1b = 0x02, /**< Level 1b */ + OMX_VIDEO_AVCLevel11 = 0x04, /**< Level 1.1 */ + OMX_VIDEO_AVCLevel12 = 0x08, /**< Level 1.2 */ + OMX_VIDEO_AVCLevel13 = 0x10, /**< Level 1.3 */ + OMX_VIDEO_AVCLevel2 = 0x20, /**< Level 2 */ + OMX_VIDEO_AVCLevel21 = 0x40, /**< Level 2.1 */ + OMX_VIDEO_AVCLevel22 = 0x80, /**< Level 2.2 */ + OMX_VIDEO_AVCLevel3 = 0x100, /**< Level 3 */ + OMX_VIDEO_AVCLevel31 = 0x200, /**< Level 3.1 */ + OMX_VIDEO_AVCLevel32 = 0x400, /**< Level 3.2 */ + OMX_VIDEO_AVCLevel4 = 0x800, /**< Level 4 */ + OMX_VIDEO_AVCLevel41 = 0x1000, /**< Level 4.1 */ + OMX_VIDEO_AVCLevel42 = 0x2000, /**< Level 4.2 */ + OMX_VIDEO_AVCLevel5 = 0x4000, /**< Level 5 */ + OMX_VIDEO_AVCLevel51 = 0x8000, /**< Level 5.1 */ + OMX_VIDEO_AVCLevel52 = 0x10000, /**< Level 5.2 */ + OMX_VIDEO_AVCLevelKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_AVCLevelVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_AVCLevelMax = 0x7FFFFFFF +} OMX_VIDEO_AVCLEVELTYPE; + + +/** + * AVC loop filter modes + * + * OMX_VIDEO_AVCLoopFilterEnable : Enable + * OMX_VIDEO_AVCLoopFilterDisable : Disable + * OMX_VIDEO_AVCLoopFilterDisableSliceBoundary : Disabled on slice boundaries + */ +typedef enum OMX_VIDEO_AVCLOOPFILTERTYPE { + OMX_VIDEO_AVCLoopFilterEnable = 0, + OMX_VIDEO_AVCLoopFilterDisable, + OMX_VIDEO_AVCLoopFilterDisableSliceBoundary, + OMX_VIDEO_AVCLoopFilterKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_AVCLoopFilterVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_AVCLoopFilterMax = 0x7FFFFFFF +} OMX_VIDEO_AVCLOOPFILTERTYPE; + + +/** + * AVC params + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * nSliceHeaderSpacing : Number of macroblocks between slice header, put + * zero if not used + * nPFrames : Number of P frames between each I frame + * nBFrames : Number of B frames between each I frame + * bUseHadamard : Enable/disable Hadamard transform + * nRefFrames : Max number of reference frames to use for inter + * motion search (1-16) + * nRefIdxTrailing : Pic param set ref frame index (index into ref + * frame buffer of trailing frames list), B frame + * support + * nRefIdxForward : Pic param set ref frame index (index into ref + * frame buffer of forward frames list), B frame + * support + * bEnableUEP : Enable/disable unequal error protection. This + * is only valid of data partitioning is enabled. + * bEnableFMO : Enable/disable flexible macroblock ordering + * bEnableASO : Enable/disable arbitrary slice ordering + * bEnableRS : Enable/disable sending of redundant slices + * eProfile : AVC profile(s) to use + * eLevel : AVC level(s) to use + * nAllowedPictureTypes : Specifies the picture types allowed in the + * bitstream + * bFrameMBsOnly : specifies that every coded picture of the + * coded video sequence is a coded frame + * containing only frame macroblocks + * bMBAFF : Enable/disable switching between frame and + * field macroblocks within a picture + * bEntropyCodingCABAC : Entropy decoding method to be applied for the + * syntax elements for which two descriptors appear + * in the syntax tables + * bWeightedPPrediction : Enable/disable weighted prediction shall not + * be applied to P and SP slices + * nWeightedBipredicitonMode : Default weighted prediction is applied to B + * slices + * bconstIpred : Enable/disable intra prediction + * bDirect8x8Inference : Specifies the method used in the derivation + * process for luma motion vectors for B_Skip, + * B_Direct_16x16 and B_Direct_8x8 as specified + * in subclause 8.4.1.2 of the AVC spec + * bDirectSpatialTemporal : Flag indicating spatial or temporal direct + * mode used in B slice coding (related to + * bDirect8x8Inference) . Spatial direct mode is + * more common and should be the default. + * nCabacInitIdx : Index used to init CABAC contexts + * eLoopFilterMode : Enable/disable loop filter + */ +typedef struct OMX_VIDEO_PARAM_AVCTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nSliceHeaderSpacing; + OMX_U32 nPFrames; + OMX_U32 nBFrames; + OMX_BOOL bUseHadamard; + OMX_U32 nRefFrames; + OMX_U32 nRefIdx10ActiveMinus1; + OMX_U32 nRefIdx11ActiveMinus1; + OMX_BOOL bEnableUEP; + OMX_BOOL bEnableFMO; + OMX_BOOL bEnableASO; + OMX_BOOL bEnableRS; + OMX_VIDEO_AVCPROFILETYPE eProfile; + OMX_VIDEO_AVCLEVELTYPE eLevel; + OMX_U32 nAllowedPictureTypes; + OMX_BOOL bFrameMBsOnly; + OMX_BOOL bMBAFF; + OMX_BOOL bEntropyCodingCABAC; + OMX_BOOL bWeightedPPrediction; + OMX_U32 nWeightedBipredicitonMode; + OMX_BOOL bconstIpred ; + OMX_BOOL bDirect8x8Inference; + OMX_BOOL bDirectSpatialTemporal; + OMX_U32 nCabacInitIdc; + OMX_VIDEO_AVCLOOPFILTERTYPE eLoopFilterMode; +} OMX_VIDEO_PARAM_AVCTYPE; + +typedef struct OMX_VIDEO_PARAM_PROFILELEVELTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 eProfile; /**< type is OMX_VIDEO_AVCPROFILETYPE, OMX_VIDEO_H263PROFILETYPE, + or OMX_VIDEO_MPEG4PROFILETYPE depending on context */ + OMX_U32 eLevel; /**< type is OMX_VIDEO_AVCLEVELTYPE, OMX_VIDEO_H263LEVELTYPE, + or OMX_VIDEO_MPEG4PROFILETYPE depending on context */ + OMX_U32 nProfileIndex; /**< Used to query for individual profile support information, + This parameter is valid only for + OMX_IndexParamVideoProfileLevelQuerySupported index, + For all other indices this parameter is to be ignored. */ +} OMX_VIDEO_PARAM_PROFILELEVELTYPE; + +/** + * Structure for dynamically configuring bitrate mode of a codec. + * + * STRUCT MEMBERS: + * nSize : Size of the struct in bytes + * nVersion : OMX spec version info + * nPortIndex : Port that this struct applies to + * nEncodeBitrate : Target average bitrate to be generated in bps + */ +typedef struct OMX_VIDEO_CONFIG_BITRATETYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nEncodeBitrate; +} OMX_VIDEO_CONFIG_BITRATETYPE; + +/** + * Defines Encoder Frame Rate setting + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * xEncodeFramerate : Encoding framerate represented in Q16 format + */ +typedef struct OMX_CONFIG_FRAMERATETYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 xEncodeFramerate; /* Q16 format */ +} OMX_CONFIG_FRAMERATETYPE; + +typedef struct OMX_CONFIG_INTRAREFRESHVOPTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL IntraRefreshVOP; +} OMX_CONFIG_INTRAREFRESHVOPTYPE; + +typedef struct OMX_CONFIG_MACROBLOCKERRORMAPTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nErrMapSize; /* Size of the Error Map in bytes */ + OMX_U8 ErrMap[1]; /* Error map hint */ +} OMX_CONFIG_MACROBLOCKERRORMAPTYPE; + +typedef struct OMX_CONFIG_MBERRORREPORTINGTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bEnabled; +} OMX_CONFIG_MBERRORREPORTINGTYPE; + +typedef struct OMX_PARAM_MACROBLOCKSTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nMacroblocks; +} OMX_PARAM_MACROBLOCKSTYPE; + +/** + * AVC Slice Mode modes + * + * OMX_VIDEO_SLICEMODE_AVCDefault : Normal frame encoding, one slice per frame + * OMX_VIDEO_SLICEMODE_AVCMBSlice : NAL mode, number of MBs per frame + * OMX_VIDEO_SLICEMODE_AVCByteSlice : NAL mode, number of bytes per frame + */ +typedef enum OMX_VIDEO_AVCSLICEMODETYPE { + OMX_VIDEO_SLICEMODE_AVCDefault = 0, + OMX_VIDEO_SLICEMODE_AVCMBSlice, + OMX_VIDEO_SLICEMODE_AVCByteSlice, + OMX_VIDEO_SLICEMODE_AVCKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ + OMX_VIDEO_SLICEMODE_AVCVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ + OMX_VIDEO_SLICEMODE_AVCLevelMax = 0x7FFFFFFF +} OMX_VIDEO_AVCSLICEMODETYPE; + +/** + * AVC FMO Slice Mode Params + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * nNumSliceGroups : Specifies the number of slice groups + * nSliceGroupMapType : Specifies the type of slice groups + * eSliceMode : Specifies the type of slice + */ +typedef struct OMX_VIDEO_PARAM_AVCSLICEFMO { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U8 nNumSliceGroups; + OMX_U8 nSliceGroupMapType; + OMX_VIDEO_AVCSLICEMODETYPE eSliceMode; +} OMX_VIDEO_PARAM_AVCSLICEFMO; + +/** + * AVC IDR Period Configs + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * nIDRPeriod : Specifies periodicity of IDR frames + * nPFrames : Specifies internal of coding Intra frames + */ +typedef struct OMX_VIDEO_CONFIG_AVCINTRAPERIOD { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nIDRPeriod; + OMX_U32 nPFrames; +} OMX_VIDEO_CONFIG_AVCINTRAPERIOD; + +/** + * AVC NAL Size Configs + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * nNaluBytes : Specifies the NAL unit size + */ +typedef struct OMX_VIDEO_CONFIG_NALSIZE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nNaluBytes; +} OMX_VIDEO_CONFIG_NALSIZE; + + +/** + * Deinterlace Config + * + * STRUCT MEMBERS: + * nSize : Size of the structure in bytes + * nVersion : OMX specification version information + * nPortIndex : Port that this structure applies to + * nEnable : Specifies to enable deinterlace + */ +typedef struct OMX_VIDEO_CONFIG_DEINTERLACE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_U32 nEnable; +} OMX_VIDEO_CONFIG_DEINTERLACE; + +/** @} */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif +/* File EOF */ + diff --git a/phonelibs/openmax/include/OMX_VideoExt.h b/phonelibs/openmax/include/OMX_VideoExt.h new file mode 100644 index 0000000000..5bf6fd4878 --- /dev/null +++ b/phonelibs/openmax/include/OMX_VideoExt.h @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2010 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject + * to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** OMX_VideoExt.h - OpenMax IL version 1.1.2 + * The OMX_VideoExt header file contains extensions to the + * definitions used by both the application and the component to + * access video items. + */ + +#ifndef OMX_VideoExt_h +#define OMX_VideoExt_h + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* Each OMX header shall include all required header files to allow the + * header to compile without errors. The includes below are required + * for this header file to compile successfully + */ +#include + +/** NALU Formats */ +typedef enum OMX_NALUFORMATSTYPE { + OMX_NaluFormatStartCodes = 1, + OMX_NaluFormatOneNaluPerBuffer = 2, + OMX_NaluFormatOneByteInterleaveLength = 4, + OMX_NaluFormatTwoByteInterleaveLength = 8, + OMX_NaluFormatFourByteInterleaveLength = 16, + OMX_NaluFormatCodingMax = 0x7FFFFFFF +} OMX_NALUFORMATSTYPE; + +/** NAL Stream Format */ +typedef struct OMX_NALSTREAMFORMATTYPE{ + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_NALUFORMATSTYPE eNaluFormat; +} OMX_NALSTREAMFORMATTYPE; + +/** VP8 profiles */ +typedef enum OMX_VIDEO_VP8PROFILETYPE { + OMX_VIDEO_VP8ProfileMain = 0x01, + OMX_VIDEO_VP8ProfileUnknown = 0x6EFFFFFF, + OMX_VIDEO_VP8ProfileMax = 0x7FFFFFFF +} OMX_VIDEO_VP8PROFILETYPE; + +/** VP8 levels */ +typedef enum OMX_VIDEO_VP8LEVELTYPE { + OMX_VIDEO_VP8Level_Version0 = 0x01, + OMX_VIDEO_VP8Level_Version1 = 0x02, + OMX_VIDEO_VP8Level_Version2 = 0x04, + OMX_VIDEO_VP8Level_Version3 = 0x08, + OMX_VIDEO_VP8LevelUnknown = 0x6EFFFFFF, + OMX_VIDEO_VP8LevelMax = 0x7FFFFFFF +} OMX_VIDEO_VP8LEVELTYPE; + +/** VP8 Param */ +typedef struct OMX_VIDEO_PARAM_VP8TYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_VIDEO_VP8PROFILETYPE eProfile; + OMX_VIDEO_VP8LEVELTYPE eLevel; + OMX_U32 nDCTPartitions; + OMX_BOOL bErrorResilientMode; +} OMX_VIDEO_PARAM_VP8TYPE; + +/** Structure for configuring VP8 reference frames */ +typedef struct OMX_VIDEO_VP8REFERENCEFRAMETYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bPreviousFrameRefresh; + OMX_BOOL bGoldenFrameRefresh; + OMX_BOOL bAlternateFrameRefresh; + OMX_BOOL bUsePreviousFrame; + OMX_BOOL bUseGoldenFrame; + OMX_BOOL bUseAlternateFrame; +} OMX_VIDEO_VP8REFERENCEFRAMETYPE; + +/** Structure for querying VP8 reference frame type */ +typedef struct OMX_VIDEO_VP8REFERENCEFRAMEINFOTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_BOOL bIsIntraFrame; + OMX_BOOL bIsGoldenOrAlternateFrame; +} OMX_VIDEO_VP8REFERENCEFRAMEINFOTYPE; + +/** HEVC Profiles */ +typedef enum OMX_VIDEO_HEVCPROFILETYPE { + OMX_VIDEO_HEVCProfileMain = 0x01, + OMX_VIDEO_HEVCProfileMain10 = 0x02, + OMX_VIDEO_HEVCProfileUnknown = 0x6EFFFFFF, + OMX_VIDEO_HEVCProfileMax = 0x7FFFFFFF +} OMX_VIDEO_HEVCPROFILETYPE; + +/** HEVC levels */ +typedef enum OMX_VIDEO_HEVCLEVELTYPE { + OMX_VIDEO_HEVCLevel_Version0 = 0x0, + OMX_VIDEO_HEVCMainTierLevel1 = 0x1, + OMX_VIDEO_HEVCHighTierLevel1 = 0x2, + OMX_VIDEO_HEVCMainTierLevel2 = 0x4, + OMX_VIDEO_HEVCHighTierLevel2 = 0x8, + OMX_VIDEO_HEVCMainTierLevel21 = 0x10, + OMX_VIDEO_HEVCHighTierLevel21 = 0x20, + OMX_VIDEO_HEVCMainTierLevel3 = 0x40, + OMX_VIDEO_HEVCHighTierLevel3 = 0x80, + OMX_VIDEO_HEVCMainTierLevel31 = 0x100, + OMX_VIDEO_HEVCHighTierLevel31 = 0x200, + OMX_VIDEO_HEVCMainTierLevel4 = 0x400, + OMX_VIDEO_HEVCHighTierLevel4 = 0x800, + OMX_VIDEO_HEVCMainTierLevel41 = 0x1000, + OMX_VIDEO_HEVCHighTierLevel41 = 0x2000, + OMX_VIDEO_HEVCMainTierLevel5 = 0x4000, + OMX_VIDEO_HEVCHighTierLevel5 = 0x8000, + OMX_VIDEO_HEVCMainTierLevel51 = 0x10000, + OMX_VIDEO_HEVCHighTierLevel51 = 0x20000, + OMX_VIDEO_HEVCMainTierLevel52 = 0x40000, + OMX_VIDEO_HEVCHighTierLevel52 = 0x80000, + OMX_VIDEO_HEVCMainTierLevel6 = 0x100000, + OMX_VIDEO_HEVCHighTierLevel6 = 0x200000, + OMX_VIDEO_HEVCMainTierLevel61 = 0x400000, + OMX_VIDEO_HEVCHighTierLevel61 = 0x800000, + OMX_VIDEO_HEVCMainTierLevel62 = 0x1000000, + OMX_VIDEO_HEVCLevelUnknown = 0x6EFFFFFF, + OMX_VIDEO_HEVCLevelMax = 0x7FFFFFFF +} OMX_VIDEO_HEVCLEVELTYPE; + +/** HEVC Param */ +typedef struct OMX_VIDEO_PARAM_HEVCTYPE { + OMX_U32 nSize; + OMX_VERSIONTYPE nVersion; + OMX_U32 nPortIndex; + OMX_VIDEO_HEVCPROFILETYPE eProfile; + OMX_VIDEO_HEVCLEVELTYPE eLevel; +} OMX_VIDEO_PARAM_HEVCTYPE; + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* OMX_VideoExt_h */ +/* File EOF */ diff --git a/phonelibs/snpe/x86_64-linux-clang/libSNPE.so b/phonelibs/snpe/x86_64-linux-clang/libSNPE.so new file mode 100644 index 0000000000..cc1de85075 Binary files /dev/null and b/phonelibs/snpe/x86_64-linux-clang/libSNPE.so differ diff --git a/phonelibs/snpe/x86_64-linux-clang/libsymphony-cpu.so b/phonelibs/snpe/x86_64-linux-clang/libsymphony-cpu.so new file mode 100755 index 0000000000..70d6f146a3 Binary files /dev/null and b/phonelibs/snpe/x86_64-linux-clang/libsymphony-cpu.so differ diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/anchor.h b/phonelibs/yaml-cpp/include/yaml-cpp/anchor.h new file mode 100644 index 0000000000..06759c724d --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/anchor.h @@ -0,0 +1,17 @@ +#ifndef ANCHOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define ANCHOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include + +namespace YAML { +typedef std::size_t anchor_t; +const anchor_t NullAnchor = 0; +} + +#endif // ANCHOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/binary.h b/phonelibs/yaml-cpp/include/yaml-cpp/binary.h new file mode 100644 index 0000000000..29d5dbd027 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/binary.h @@ -0,0 +1,67 @@ +#ifndef BASE64_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define BASE64_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include +#include + +#include "yaml-cpp/dll.h" + +namespace YAML { +YAML_CPP_API std::string EncodeBase64(const unsigned char *data, + std::size_t size); +YAML_CPP_API std::vector DecodeBase64(const std::string &input); + +class YAML_CPP_API Binary { + public: + Binary() : m_unownedData(0), m_unownedSize(0) {} + Binary(const unsigned char *data_, std::size_t size_) + : m_unownedData(data_), m_unownedSize(size_) {} + + bool owned() const { return !m_unownedData; } + std::size_t size() const { return owned() ? m_data.size() : m_unownedSize; } + const unsigned char *data() const { + return owned() ? &m_data[0] : m_unownedData; + } + + void swap(std::vector &rhs) { + if (m_unownedData) { + m_data.swap(rhs); + rhs.clear(); + rhs.resize(m_unownedSize); + std::copy(m_unownedData, m_unownedData + m_unownedSize, rhs.begin()); + m_unownedData = 0; + m_unownedSize = 0; + } else { + m_data.swap(rhs); + } + } + + bool operator==(const Binary &rhs) const { + const std::size_t s = size(); + if (s != rhs.size()) + return false; + const unsigned char *d1 = data(); + const unsigned char *d2 = rhs.data(); + for (std::size_t i = 0; i < s; i++) { + if (*d1++ != *d2++) + return false; + } + return true; + } + + bool operator!=(const Binary &rhs) const { return !(*this == rhs); } + + private: + std::vector m_data; + const unsigned char *m_unownedData; + std::size_t m_unownedSize; +}; +} + +#endif // BASE64_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/contrib/anchordict.h b/phonelibs/yaml-cpp/include/yaml-cpp/contrib/anchordict.h new file mode 100644 index 0000000000..78db9ec928 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/contrib/anchordict.h @@ -0,0 +1,39 @@ +#ifndef ANCHORDICT_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define ANCHORDICT_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include + +#include "../anchor.h" + +namespace YAML { +/** + * An object that stores and retrieves values correlating to {@link anchor_t} + * values. + * + *

Efficient implementation that can make assumptions about how + * {@code anchor_t} values are assigned by the {@link Parser} class. + */ +template +class AnchorDict { + public: + void Register(anchor_t anchor, T value) { + if (anchor > m_data.size()) { + m_data.resize(anchor); + } + m_data[anchor - 1] = value; + } + + T Get(anchor_t anchor) const { return m_data[anchor - 1]; } + + private: + std::vector m_data; +}; +} + +#endif // ANCHORDICT_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/contrib/graphbuilder.h b/phonelibs/yaml-cpp/include/yaml-cpp/contrib/graphbuilder.h new file mode 100644 index 0000000000..7c2159b465 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/contrib/graphbuilder.h @@ -0,0 +1,147 @@ +#ifndef GRAPHBUILDER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define GRAPHBUILDER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include "yaml-cpp/mark.h" +#include + +namespace YAML { +class Parser; + +// GraphBuilderInterface +// . Abstraction of node creation +// . pParentNode is always NULL or the return value of one of the NewXXX() +// functions. +class GraphBuilderInterface { + public: + // Create and return a new node with a null value. + virtual void *NewNull(const Mark &mark, void *pParentNode) = 0; + + // Create and return a new node with the given tag and value. + virtual void *NewScalar(const Mark &mark, const std::string &tag, + void *pParentNode, const std::string &value) = 0; + + // Create and return a new sequence node + virtual void *NewSequence(const Mark &mark, const std::string &tag, + void *pParentNode) = 0; + + // Add pNode to pSequence. pNode was created with one of the NewXxx() + // functions and pSequence with NewSequence(). + virtual void AppendToSequence(void *pSequence, void *pNode) = 0; + + // Note that no moew entries will be added to pSequence + virtual void SequenceComplete(void *pSequence) { (void)pSequence; } + + // Create and return a new map node + virtual void *NewMap(const Mark &mark, const std::string &tag, + void *pParentNode) = 0; + + // Add the pKeyNode => pValueNode mapping to pMap. pKeyNode and pValueNode + // were created with one of the NewXxx() methods and pMap with NewMap(). + virtual void AssignInMap(void *pMap, void *pKeyNode, void *pValueNode) = 0; + + // Note that no more assignments will be made in pMap + virtual void MapComplete(void *pMap) { (void)pMap; } + + // Return the node that should be used in place of an alias referencing + // pNode (pNode by default) + virtual void *AnchorReference(const Mark &mark, void *pNode) { + (void)mark; + return pNode; + } +}; + +// Typesafe wrapper for GraphBuilderInterface. Assumes that Impl defines +// Node, Sequence, and Map types. Sequence and Map must derive from Node +// (unless Node is defined as void). Impl must also implement function with +// all of the same names as the virtual functions in GraphBuilderInterface +// -- including the ones with default implementations -- but with the +// prototypes changed to accept an explicit Node*, Sequence*, or Map* where +// appropriate. +template +class GraphBuilder : public GraphBuilderInterface { + public: + typedef typename Impl::Node Node; + typedef typename Impl::Sequence Sequence; + typedef typename Impl::Map Map; + + GraphBuilder(Impl &impl) : m_impl(impl) { + Map *pMap = NULL; + Sequence *pSeq = NULL; + Node *pNode = NULL; + + // Type consistency checks + pNode = pMap; + pNode = pSeq; + } + + GraphBuilderInterface &AsBuilderInterface() { return *this; } + + virtual void *NewNull(const Mark &mark, void *pParentNode) { + return CheckType(m_impl.NewNull(mark, AsNode(pParentNode))); + } + + virtual void *NewScalar(const Mark &mark, const std::string &tag, + void *pParentNode, const std::string &value) { + return CheckType( + m_impl.NewScalar(mark, tag, AsNode(pParentNode), value)); + } + + virtual void *NewSequence(const Mark &mark, const std::string &tag, + void *pParentNode) { + return CheckType( + m_impl.NewSequence(mark, tag, AsNode(pParentNode))); + } + virtual void AppendToSequence(void *pSequence, void *pNode) { + m_impl.AppendToSequence(AsSequence(pSequence), AsNode(pNode)); + } + virtual void SequenceComplete(void *pSequence) { + m_impl.SequenceComplete(AsSequence(pSequence)); + } + + virtual void *NewMap(const Mark &mark, const std::string &tag, + void *pParentNode) { + return CheckType(m_impl.NewMap(mark, tag, AsNode(pParentNode))); + } + virtual void AssignInMap(void *pMap, void *pKeyNode, void *pValueNode) { + m_impl.AssignInMap(AsMap(pMap), AsNode(pKeyNode), AsNode(pValueNode)); + } + virtual void MapComplete(void *pMap) { m_impl.MapComplete(AsMap(pMap)); } + + virtual void *AnchorReference(const Mark &mark, void *pNode) { + return CheckType(m_impl.AnchorReference(mark, AsNode(pNode))); + } + + private: + Impl &m_impl; + + // Static check for pointer to T + template + static T *CheckType(U *p) { + return p; + } + + static Node *AsNode(void *pNode) { return static_cast(pNode); } + static Sequence *AsSequence(void *pSeq) { + return static_cast(pSeq); + } + static Map *AsMap(void *pMap) { return static_cast(pMap); } +}; + +void *BuildGraphOfNextDocument(Parser &parser, + GraphBuilderInterface &graphBuilder); + +template +typename Impl::Node *BuildGraphOfNextDocument(Parser &parser, Impl &impl) { + GraphBuilder graphBuilder(impl); + return static_cast( + BuildGraphOfNextDocument(parser, graphBuilder)); +} +} + +#endif // GRAPHBUILDER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/dll.h b/phonelibs/yaml-cpp/include/yaml-cpp/dll.h new file mode 100644 index 0000000000..a32c06b2e3 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/dll.h @@ -0,0 +1,33 @@ +#ifndef DLL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define DLL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +// The following ifdef block is the standard way of creating macros which make +// exporting from a DLL simpler. All files within this DLL are compiled with the +// yaml_cpp_EXPORTS symbol defined on the command line. This symbol should not +// be defined on any project that uses this DLL. This way any other project +// whose source files include this file see YAML_CPP_API functions as being +// imported from a DLL, whereas this DLL sees symbols defined with this macro as +// being exported. +#undef YAML_CPP_API + +#ifdef YAML_CPP_DLL // Using or Building YAML-CPP DLL (definition defined + // manually) +#ifdef yaml_cpp_EXPORTS // Building YAML-CPP DLL (definition created by CMake + // or defined manually) +// #pragma message( "Defining YAML_CPP_API for DLL export" ) +#define YAML_CPP_API __declspec(dllexport) +#else // yaml_cpp_EXPORTS +// #pragma message( "Defining YAML_CPP_API for DLL import" ) +#define YAML_CPP_API __declspec(dllimport) +#endif // yaml_cpp_EXPORTS +#else // YAML_CPP_DLL +#define YAML_CPP_API +#endif // YAML_CPP_DLL + +#endif // DLL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/emitfromevents.h b/phonelibs/yaml-cpp/include/yaml-cpp/emitfromevents.h new file mode 100644 index 0000000000..f14b051ab0 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/emitfromevents.h @@ -0,0 +1,57 @@ +#ifndef EMITFROMEVENTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define EMITFROMEVENTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include + +#include "yaml-cpp/anchor.h" +#include "yaml-cpp/emitterstyle.h" +#include "yaml-cpp/eventhandler.h" + +namespace YAML { +struct Mark; +} // namespace YAML + +namespace YAML { +class Emitter; + +class EmitFromEvents : public EventHandler { + public: + EmitFromEvents(Emitter& emitter); + + virtual void OnDocumentStart(const Mark& mark); + virtual void OnDocumentEnd(); + + virtual void OnNull(const Mark& mark, anchor_t anchor); + virtual void OnAlias(const Mark& mark, anchor_t anchor); + virtual void OnScalar(const Mark& mark, const std::string& tag, + anchor_t anchor, const std::string& value); + + virtual void OnSequenceStart(const Mark& mark, const std::string& tag, + anchor_t anchor, EmitterStyle::value style); + virtual void OnSequenceEnd(); + + virtual void OnMapStart(const Mark& mark, const std::string& tag, + anchor_t anchor, EmitterStyle::value style); + virtual void OnMapEnd(); + + private: + void BeginNode(); + void EmitProps(const std::string& tag, anchor_t anchor); + + private: + Emitter& m_emitter; + + struct State { + enum value { WaitingForSequenceEntry, WaitingForKey, WaitingForValue }; + }; + std::stack m_stateStack; +}; +} + +#endif // EMITFROMEVENTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/emitter.h b/phonelibs/yaml-cpp/include/yaml-cpp/emitter.h new file mode 100644 index 0000000000..ef92cc4035 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/emitter.h @@ -0,0 +1,254 @@ +#ifndef EMITTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define EMITTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include +#include +#include +#include + +#include "yaml-cpp/binary.h" +#include "yaml-cpp/dll.h" +#include "yaml-cpp/emitterdef.h" +#include "yaml-cpp/emittermanip.h" +#include "yaml-cpp/noncopyable.h" +#include "yaml-cpp/null.h" +#include "yaml-cpp/ostream_wrapper.h" + +namespace YAML { +class Binary; +struct _Null; +} // namespace YAML + +namespace YAML { +class EmitterState; + +class YAML_CPP_API Emitter : private noncopyable { + public: + Emitter(); + explicit Emitter(std::ostream& stream); + ~Emitter(); + + // output + const char* c_str() const; + std::size_t size() const; + + // state checking + bool good() const; + const std::string GetLastError() const; + + // global setters + bool SetOutputCharset(EMITTER_MANIP value); + bool SetStringFormat(EMITTER_MANIP value); + bool SetBoolFormat(EMITTER_MANIP value); + bool SetIntBase(EMITTER_MANIP value); + bool SetSeqFormat(EMITTER_MANIP value); + bool SetMapFormat(EMITTER_MANIP value); + bool SetIndent(std::size_t n); + bool SetPreCommentIndent(std::size_t n); + bool SetPostCommentIndent(std::size_t n); + bool SetFloatPrecision(std::size_t n); + bool SetDoublePrecision(std::size_t n); + + // local setters + Emitter& SetLocalValue(EMITTER_MANIP value); + Emitter& SetLocalIndent(const _Indent& indent); + Emitter& SetLocalPrecision(const _Precision& precision); + + // overloads of write + Emitter& Write(const std::string& str); + Emitter& Write(bool b); + Emitter& Write(char ch); + Emitter& Write(const _Alias& alias); + Emitter& Write(const _Anchor& anchor); + Emitter& Write(const _Tag& tag); + Emitter& Write(const _Comment& comment); + Emitter& Write(const _Null& n); + Emitter& Write(const Binary& binary); + + template + Emitter& WriteIntegralType(T value); + + template + Emitter& WriteStreamable(T value); + + private: + template + void SetStreamablePrecision(std::stringstream&) {} + std::size_t GetFloatPrecision() const; + std::size_t GetDoublePrecision() const; + + void PrepareIntegralStream(std::stringstream& stream) const; + void StartedScalar(); + + private: + void EmitBeginDoc(); + void EmitEndDoc(); + void EmitBeginSeq(); + void EmitEndSeq(); + void EmitBeginMap(); + void EmitEndMap(); + void EmitNewline(); + void EmitKindTag(); + void EmitTag(bool verbatim, const _Tag& tag); + + void PrepareNode(EmitterNodeType::value child); + void PrepareTopNode(EmitterNodeType::value child); + void FlowSeqPrepareNode(EmitterNodeType::value child); + void BlockSeqPrepareNode(EmitterNodeType::value child); + + void FlowMapPrepareNode(EmitterNodeType::value child); + + void FlowMapPrepareLongKey(EmitterNodeType::value child); + void FlowMapPrepareLongKeyValue(EmitterNodeType::value child); + void FlowMapPrepareSimpleKey(EmitterNodeType::value child); + void FlowMapPrepareSimpleKeyValue(EmitterNodeType::value child); + + void BlockMapPrepareNode(EmitterNodeType::value child); + + void BlockMapPrepareLongKey(EmitterNodeType::value child); + void BlockMapPrepareLongKeyValue(EmitterNodeType::value child); + void BlockMapPrepareSimpleKey(EmitterNodeType::value child); + void BlockMapPrepareSimpleKeyValue(EmitterNodeType::value child); + + void SpaceOrIndentTo(bool requireSpace, std::size_t indent); + + const char* ComputeFullBoolName(bool b) const; + bool CanEmitNewline() const; + + private: + std::unique_ptr m_pState; + ostream_wrapper m_stream; +}; + +template +inline Emitter& Emitter::WriteIntegralType(T value) { + if (!good()) + return *this; + + PrepareNode(EmitterNodeType::Scalar); + + std::stringstream stream; + PrepareIntegralStream(stream); + stream << value; + m_stream << stream.str(); + + StartedScalar(); + + return *this; +} + +template +inline Emitter& Emitter::WriteStreamable(T value) { + if (!good()) + return *this; + + PrepareNode(EmitterNodeType::Scalar); + + std::stringstream stream; + SetStreamablePrecision(stream); + stream << value; + m_stream << stream.str(); + + StartedScalar(); + + return *this; +} + +template <> +inline void Emitter::SetStreamablePrecision(std::stringstream& stream) { + stream.precision(static_cast(GetFloatPrecision())); +} + +template <> +inline void Emitter::SetStreamablePrecision(std::stringstream& stream) { + stream.precision(static_cast(GetDoublePrecision())); +} + +// overloads of insertion +inline Emitter& operator<<(Emitter& emitter, const std::string& v) { + return emitter.Write(v); +} +inline Emitter& operator<<(Emitter& emitter, bool v) { + return emitter.Write(v); +} +inline Emitter& operator<<(Emitter& emitter, char v) { + return emitter.Write(v); +} +inline Emitter& operator<<(Emitter& emitter, unsigned char v) { + return emitter.Write(static_cast(v)); +} +inline Emitter& operator<<(Emitter& emitter, const _Alias& v) { + return emitter.Write(v); +} +inline Emitter& operator<<(Emitter& emitter, const _Anchor& v) { + return emitter.Write(v); +} +inline Emitter& operator<<(Emitter& emitter, const _Tag& v) { + return emitter.Write(v); +} +inline Emitter& operator<<(Emitter& emitter, const _Comment& v) { + return emitter.Write(v); +} +inline Emitter& operator<<(Emitter& emitter, const _Null& v) { + return emitter.Write(v); +} +inline Emitter& operator<<(Emitter& emitter, const Binary& b) { + return emitter.Write(b); +} + +inline Emitter& operator<<(Emitter& emitter, const char* v) { + return emitter.Write(std::string(v)); +} + +inline Emitter& operator<<(Emitter& emitter, int v) { + return emitter.WriteIntegralType(v); +} +inline Emitter& operator<<(Emitter& emitter, unsigned int v) { + return emitter.WriteIntegralType(v); +} +inline Emitter& operator<<(Emitter& emitter, short v) { + return emitter.WriteIntegralType(v); +} +inline Emitter& operator<<(Emitter& emitter, unsigned short v) { + return emitter.WriteIntegralType(v); +} +inline Emitter& operator<<(Emitter& emitter, long v) { + return emitter.WriteIntegralType(v); +} +inline Emitter& operator<<(Emitter& emitter, unsigned long v) { + return emitter.WriteIntegralType(v); +} +inline Emitter& operator<<(Emitter& emitter, long long v) { + return emitter.WriteIntegralType(v); +} +inline Emitter& operator<<(Emitter& emitter, unsigned long long v) { + return emitter.WriteIntegralType(v); +} + +inline Emitter& operator<<(Emitter& emitter, float v) { + return emitter.WriteStreamable(v); +} +inline Emitter& operator<<(Emitter& emitter, double v) { + return emitter.WriteStreamable(v); +} + +inline Emitter& operator<<(Emitter& emitter, EMITTER_MANIP value) { + return emitter.SetLocalValue(value); +} + +inline Emitter& operator<<(Emitter& emitter, _Indent indent) { + return emitter.SetLocalIndent(indent); +} + +inline Emitter& operator<<(Emitter& emitter, _Precision precision) { + return emitter.SetLocalPrecision(precision); +} +} + +#endif // EMITTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/emitterdef.h b/phonelibs/yaml-cpp/include/yaml-cpp/emitterdef.h new file mode 100644 index 0000000000..0b426957fa --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/emitterdef.h @@ -0,0 +1,16 @@ +#ifndef EMITTERDEF_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define EMITTERDEF_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +namespace YAML { +struct EmitterNodeType { + enum value { NoType, Property, Scalar, FlowSeq, BlockSeq, FlowMap, BlockMap }; +}; +} + +#endif // EMITTERDEF_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/emittermanip.h b/phonelibs/yaml-cpp/include/yaml-cpp/emittermanip.h new file mode 100644 index 0000000000..89f7256714 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/emittermanip.h @@ -0,0 +1,137 @@ +#ifndef EMITTERMANIP_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define EMITTERMANIP_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include + +namespace YAML { +enum EMITTER_MANIP { + // general manipulators + Auto, + TagByKind, + Newline, + + // output character set + EmitNonAscii, + EscapeNonAscii, + + // string manipulators + // Auto, // duplicate + SingleQuoted, + DoubleQuoted, + Literal, + + // bool manipulators + YesNoBool, // yes, no + TrueFalseBool, // true, false + OnOffBool, // on, off + UpperCase, // TRUE, N + LowerCase, // f, yes + CamelCase, // No, Off + LongBool, // yes, On + ShortBool, // y, t + + // int manipulators + Dec, + Hex, + Oct, + + // document manipulators + BeginDoc, + EndDoc, + + // sequence manipulators + BeginSeq, + EndSeq, + Flow, + Block, + + // map manipulators + BeginMap, + EndMap, + Key, + Value, + // Flow, // duplicate + // Block, // duplicate + // Auto, // duplicate + LongKey +}; + +struct _Indent { + _Indent(int value_) : value(value_) {} + int value; +}; + +inline _Indent Indent(int value) { return _Indent(value); } + +struct _Alias { + _Alias(const std::string& content_) : content(content_) {} + std::string content; +}; + +inline _Alias Alias(const std::string content) { return _Alias(content); } + +struct _Anchor { + _Anchor(const std::string& content_) : content(content_) {} + std::string content; +}; + +inline _Anchor Anchor(const std::string content) { return _Anchor(content); } + +struct _Tag { + struct Type { + enum value { Verbatim, PrimaryHandle, NamedHandle }; + }; + + explicit _Tag(const std::string& prefix_, const std::string& content_, + Type::value type_) + : prefix(prefix_), content(content_), type(type_) {} + std::string prefix; + std::string content; + Type::value type; +}; + +inline _Tag VerbatimTag(const std::string content) { + return _Tag("", content, _Tag::Type::Verbatim); +} + +inline _Tag LocalTag(const std::string content) { + return _Tag("", content, _Tag::Type::PrimaryHandle); +} + +inline _Tag LocalTag(const std::string& prefix, const std::string content) { + return _Tag(prefix, content, _Tag::Type::NamedHandle); +} + +inline _Tag SecondaryTag(const std::string content) { + return _Tag("", content, _Tag::Type::NamedHandle); +} + +struct _Comment { + _Comment(const std::string& content_) : content(content_) {} + std::string content; +}; + +inline _Comment Comment(const std::string content) { return _Comment(content); } + +struct _Precision { + _Precision(int floatPrecision_, int doublePrecision_) + : floatPrecision(floatPrecision_), doublePrecision(doublePrecision_) {} + + int floatPrecision; + int doublePrecision; +}; + +inline _Precision FloatPrecision(int n) { return _Precision(n, -1); } + +inline _Precision DoublePrecision(int n) { return _Precision(-1, n); } + +inline _Precision Precision(int n) { return _Precision(n, n); } +} + +#endif // EMITTERMANIP_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/emitterstyle.h b/phonelibs/yaml-cpp/include/yaml-cpp/emitterstyle.h new file mode 100644 index 0000000000..67bb3981b1 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/emitterstyle.h @@ -0,0 +1,16 @@ +#ifndef EMITTERSTYLE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define EMITTERSTYLE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +namespace YAML { +struct EmitterStyle { + enum value { Default, Block, Flow }; +}; +} + +#endif // EMITTERSTYLE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/eventhandler.h b/phonelibs/yaml-cpp/include/yaml-cpp/eventhandler.h new file mode 100644 index 0000000000..efe381c621 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/eventhandler.h @@ -0,0 +1,40 @@ +#ifndef EVENTHANDLER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define EVENTHANDLER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include + +#include "yaml-cpp/anchor.h" +#include "yaml-cpp/emitterstyle.h" + +namespace YAML { +struct Mark; + +class EventHandler { + public: + virtual ~EventHandler() {} + + virtual void OnDocumentStart(const Mark& mark) = 0; + virtual void OnDocumentEnd() = 0; + + virtual void OnNull(const Mark& mark, anchor_t anchor) = 0; + virtual void OnAlias(const Mark& mark, anchor_t anchor) = 0; + virtual void OnScalar(const Mark& mark, const std::string& tag, + anchor_t anchor, const std::string& value) = 0; + + virtual void OnSequenceStart(const Mark& mark, const std::string& tag, + anchor_t anchor, EmitterStyle::value style) = 0; + virtual void OnSequenceEnd() = 0; + + virtual void OnMapStart(const Mark& mark, const std::string& tag, + anchor_t anchor, EmitterStyle::value style) = 0; + virtual void OnMapEnd() = 0; +}; +} + +#endif // EVENTHANDLER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/exceptions.h b/phonelibs/yaml-cpp/include/yaml-cpp/exceptions.h new file mode 100644 index 0000000000..a0b7e3c72b --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/exceptions.h @@ -0,0 +1,257 @@ +#ifndef EXCEPTIONS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define EXCEPTIONS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include "yaml-cpp/mark.h" +#include "yaml-cpp/traits.h" +#include +#include +#include + +namespace YAML { +// error messages +namespace ErrorMsg { +const char* const YAML_DIRECTIVE_ARGS = + "YAML directives must have exactly one argument"; +const char* const YAML_VERSION = "bad YAML version: "; +const char* const YAML_MAJOR_VERSION = "YAML major version too large"; +const char* const REPEATED_YAML_DIRECTIVE = "repeated YAML directive"; +const char* const TAG_DIRECTIVE_ARGS = + "TAG directives must have exactly two arguments"; +const char* const REPEATED_TAG_DIRECTIVE = "repeated TAG directive"; +const char* const CHAR_IN_TAG_HANDLE = + "illegal character found while scanning tag handle"; +const char* const TAG_WITH_NO_SUFFIX = "tag handle with no suffix"; +const char* const END_OF_VERBATIM_TAG = "end of verbatim tag not found"; +const char* const END_OF_MAP = "end of map not found"; +const char* const END_OF_MAP_FLOW = "end of map flow not found"; +const char* const END_OF_SEQ = "end of sequence not found"; +const char* const END_OF_SEQ_FLOW = "end of sequence flow not found"; +const char* const MULTIPLE_TAGS = + "cannot assign multiple tags to the same node"; +const char* const MULTIPLE_ANCHORS = + "cannot assign multiple anchors to the same node"; +const char* const MULTIPLE_ALIASES = + "cannot assign multiple aliases to the same node"; +const char* const ALIAS_CONTENT = + "aliases can't have any content, *including* tags"; +const char* const INVALID_HEX = "bad character found while scanning hex number"; +const char* const INVALID_UNICODE = "invalid unicode: "; +const char* const INVALID_ESCAPE = "unknown escape character: "; +const char* const UNKNOWN_TOKEN = "unknown token"; +const char* const DOC_IN_SCALAR = "illegal document indicator in scalar"; +const char* const EOF_IN_SCALAR = "illegal EOF in scalar"; +const char* const CHAR_IN_SCALAR = "illegal character in scalar"; +const char* const TAB_IN_INDENTATION = + "illegal tab when looking for indentation"; +const char* const FLOW_END = "illegal flow end"; +const char* const BLOCK_ENTRY = "illegal block entry"; +const char* const MAP_KEY = "illegal map key"; +const char* const MAP_VALUE = "illegal map value"; +const char* const ALIAS_NOT_FOUND = "alias not found after *"; +const char* const ANCHOR_NOT_FOUND = "anchor not found after &"; +const char* const CHAR_IN_ALIAS = + "illegal character found while scanning alias"; +const char* const CHAR_IN_ANCHOR = + "illegal character found while scanning anchor"; +const char* const ZERO_INDENT_IN_BLOCK = + "cannot set zero indentation for a block scalar"; +const char* const CHAR_IN_BLOCK = "unexpected character in block scalar"; +const char* const AMBIGUOUS_ANCHOR = + "cannot assign the same alias to multiple nodes"; +const char* const UNKNOWN_ANCHOR = "the referenced anchor is not defined"; + +const char* const INVALID_NODE = + "invalid node; this may result from using a map iterator as a sequence " + "iterator, or vice-versa"; +const char* const INVALID_SCALAR = "invalid scalar"; +const char* const KEY_NOT_FOUND = "key not found"; +const char* const BAD_CONVERSION = "bad conversion"; +const char* const BAD_DEREFERENCE = "bad dereference"; +const char* const BAD_SUBSCRIPT = "operator[] call on a scalar"; +const char* const BAD_PUSHBACK = "appending to a non-sequence"; +const char* const BAD_INSERT = "inserting in a non-convertible-to-map"; + +const char* const UNMATCHED_GROUP_TAG = "unmatched group tag"; +const char* const UNEXPECTED_END_SEQ = "unexpected end sequence token"; +const char* const UNEXPECTED_END_MAP = "unexpected end map token"; +const char* const SINGLE_QUOTED_CHAR = + "invalid character in single-quoted string"; +const char* const INVALID_ANCHOR = "invalid anchor"; +const char* const INVALID_ALIAS = "invalid alias"; +const char* const INVALID_TAG = "invalid tag"; +const char* const BAD_FILE = "bad file"; + +template +inline const std::string KEY_NOT_FOUND_WITH_KEY( + const T&, typename disable_if>::type* = 0) { + return KEY_NOT_FOUND; +} + +inline const std::string KEY_NOT_FOUND_WITH_KEY(const std::string& key) { + std::stringstream stream; + stream << KEY_NOT_FOUND << ": " << key; + return stream.str(); +} + +template +inline const std::string KEY_NOT_FOUND_WITH_KEY( + const T& key, typename enable_if>::type* = 0) { + std::stringstream stream; + stream << KEY_NOT_FOUND << ": " << key; + return stream.str(); +} +} + +class YAML_CPP_API Exception : public std::runtime_error { + public: + Exception(const Mark& mark_, const std::string& msg_) + : std::runtime_error(build_what(mark_, msg_)), mark(mark_), msg(msg_) {} + virtual ~Exception() noexcept; + + Exception(const Exception&) = default; + + Mark mark; + std::string msg; + + private: + static const std::string build_what(const Mark& mark, + const std::string& msg) { + if (mark.is_null()) { + return msg.c_str(); + } + + std::stringstream output; + output << "yaml-cpp: error at line " << mark.line + 1 << ", column " + << mark.column + 1 << ": " << msg; + return output.str(); + } +}; + +class YAML_CPP_API ParserException : public Exception { + public: + ParserException(const Mark& mark_, const std::string& msg_) + : Exception(mark_, msg_) {} + ParserException(const ParserException&) = default; + virtual ~ParserException() noexcept; +}; + +class YAML_CPP_API RepresentationException : public Exception { + public: + RepresentationException(const Mark& mark_, const std::string& msg_) + : Exception(mark_, msg_) {} + RepresentationException(const RepresentationException&) = default; + virtual ~RepresentationException() noexcept; +}; + +// representation exceptions +class YAML_CPP_API InvalidScalar : public RepresentationException { + public: + InvalidScalar(const Mark& mark_) + : RepresentationException(mark_, ErrorMsg::INVALID_SCALAR) {} + InvalidScalar(const InvalidScalar&) = default; + virtual ~InvalidScalar() noexcept; +}; + +class YAML_CPP_API KeyNotFound : public RepresentationException { + public: + template + KeyNotFound(const Mark& mark_, const T& key_) + : RepresentationException(mark_, ErrorMsg::KEY_NOT_FOUND_WITH_KEY(key_)) { + } + KeyNotFound(const KeyNotFound&) = default; + virtual ~KeyNotFound() noexcept; +}; + +template +class YAML_CPP_API TypedKeyNotFound : public KeyNotFound { + public: + TypedKeyNotFound(const Mark& mark_, const T& key_) + : KeyNotFound(mark_, key_), key(key_) {} + virtual ~TypedKeyNotFound() noexcept {} + + T key; +}; + +template +inline TypedKeyNotFound MakeTypedKeyNotFound(const Mark& mark, + const T& key) { + return TypedKeyNotFound(mark, key); +} + +class YAML_CPP_API InvalidNode : public RepresentationException { + public: + InvalidNode() + : RepresentationException(Mark::null_mark(), ErrorMsg::INVALID_NODE) {} + InvalidNode(const InvalidNode&) = default; + virtual ~InvalidNode() noexcept; +}; + +class YAML_CPP_API BadConversion : public RepresentationException { + public: + explicit BadConversion(const Mark& mark_) + : RepresentationException(mark_, ErrorMsg::BAD_CONVERSION) {} + BadConversion(const BadConversion&) = default; + virtual ~BadConversion() noexcept; +}; + +template +class TypedBadConversion : public BadConversion { + public: + explicit TypedBadConversion(const Mark& mark_) : BadConversion(mark_) {} +}; + +class YAML_CPP_API BadDereference : public RepresentationException { + public: + BadDereference() + : RepresentationException(Mark::null_mark(), ErrorMsg::BAD_DEREFERENCE) {} + BadDereference(const BadDereference&) = default; + virtual ~BadDereference() noexcept; +}; + +class YAML_CPP_API BadSubscript : public RepresentationException { + public: + BadSubscript() + : RepresentationException(Mark::null_mark(), ErrorMsg::BAD_SUBSCRIPT) {} + BadSubscript(const BadSubscript&) = default; + virtual ~BadSubscript() noexcept; +}; + +class YAML_CPP_API BadPushback : public RepresentationException { + public: + BadPushback() + : RepresentationException(Mark::null_mark(), ErrorMsg::BAD_PUSHBACK) {} + BadPushback(const BadPushback&) = default; + virtual ~BadPushback() noexcept; +}; + +class YAML_CPP_API BadInsert : public RepresentationException { + public: + BadInsert() + : RepresentationException(Mark::null_mark(), ErrorMsg::BAD_INSERT) {} + BadInsert(const BadInsert&) = default; + virtual ~BadInsert() noexcept; +}; + +class YAML_CPP_API EmitterException : public Exception { + public: + EmitterException(const std::string& msg_) + : Exception(Mark::null_mark(), msg_) {} + EmitterException(const EmitterException&) = default; + virtual ~EmitterException() noexcept; +}; + +class YAML_CPP_API BadFile : public Exception { + public: + BadFile() : Exception(Mark::null_mark(), ErrorMsg::BAD_FILE) {} + BadFile(const BadFile&) = default; + virtual ~BadFile() noexcept; +}; +} + +#endif // EXCEPTIONS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/mark.h b/phonelibs/yaml-cpp/include/yaml-cpp/mark.h new file mode 100644 index 0000000000..bf94b4f41f --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/mark.h @@ -0,0 +1,29 @@ +#ifndef MARK_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define MARK_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include "yaml-cpp/dll.h" + +namespace YAML { +struct YAML_CPP_API Mark { + Mark() : pos(0), line(0), column(0) {} + + static const Mark null_mark() { return Mark(-1, -1, -1); } + + bool is_null() const { return pos == -1 && line == -1 && column == -1; } + + int pos; + int line, column; + + private: + Mark(int pos_, int line_, int column_) + : pos(pos_), line(line_), column(column_) {} +}; +} + +#endif // MARK_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/node/convert.h b/phonelibs/yaml-cpp/include/yaml-cpp/node/convert.h new file mode 100644 index 0000000000..45a878ab0c --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/node/convert.h @@ -0,0 +1,331 @@ +#ifndef NODE_CONVERT_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define NODE_CONVERT_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include +#include +#include +#include +#include +#include + +#include "yaml-cpp/binary.h" +#include "yaml-cpp/node/impl.h" +#include "yaml-cpp/node/iterator.h" +#include "yaml-cpp/node/node.h" +#include "yaml-cpp/node/type.h" +#include "yaml-cpp/null.h" + +namespace YAML { +class Binary; +struct _Null; +template +struct convert; +} // namespace YAML + +namespace YAML { +namespace conversion { +inline bool IsInfinity(const std::string& input) { + return input == ".inf" || input == ".Inf" || input == ".INF" || + input == "+.inf" || input == "+.Inf" || input == "+.INF"; +} + +inline bool IsNegativeInfinity(const std::string& input) { + return input == "-.inf" || input == "-.Inf" || input == "-.INF"; +} + +inline bool IsNaN(const std::string& input) { + return input == ".nan" || input == ".NaN" || input == ".NAN"; +} +} + +// Node +template <> +struct convert { + static Node encode(const Node& rhs) { return rhs; } + + static bool decode(const Node& node, Node& rhs) { + rhs.reset(node); + return true; + } +}; + +// std::string +template <> +struct convert { + static Node encode(const std::string& rhs) { return Node(rhs); } + + static bool decode(const Node& node, std::string& rhs) { + if (!node.IsScalar()) + return false; + rhs = node.Scalar(); + return true; + } +}; + +// C-strings can only be encoded +template <> +struct convert { + static Node encode(const char*& rhs) { return Node(rhs); } +}; + +template +struct convert { + static Node encode(const char(&rhs)[N]) { return Node(rhs); } +}; + +template <> +struct convert<_Null> { + static Node encode(const _Null& /* rhs */) { return Node(); } + + static bool decode(const Node& node, _Null& /* rhs */) { + return node.IsNull(); + } +}; + +#define YAML_DEFINE_CONVERT_STREAMABLE(type, negative_op) \ + template <> \ + struct convert { \ + static Node encode(const type& rhs) { \ + std::stringstream stream; \ + stream.precision(std::numeric_limits::digits10 + 1); \ + stream << rhs; \ + return Node(stream.str()); \ + } \ + \ + static bool decode(const Node& node, type& rhs) { \ + if (node.Type() != NodeType::Scalar) \ + return false; \ + const std::string& input = node.Scalar(); \ + std::stringstream stream(input); \ + stream.unsetf(std::ios::dec); \ + if ((stream >> std::noskipws >> rhs) && (stream >> std::ws).eof()) \ + return true; \ + if (std::numeric_limits::has_infinity) { \ + if (conversion::IsInfinity(input)) { \ + rhs = std::numeric_limits::infinity(); \ + return true; \ + } else if (conversion::IsNegativeInfinity(input)) { \ + rhs = negative_op std::numeric_limits::infinity(); \ + return true; \ + } \ + } \ + \ + if (std::numeric_limits::has_quiet_NaN && \ + conversion::IsNaN(input)) { \ + rhs = std::numeric_limits::quiet_NaN(); \ + return true; \ + } \ + \ + return false; \ + } \ + } + +#define YAML_DEFINE_CONVERT_STREAMABLE_SIGNED(type) \ + YAML_DEFINE_CONVERT_STREAMABLE(type, -) + +#define YAML_DEFINE_CONVERT_STREAMABLE_UNSIGNED(type) \ + YAML_DEFINE_CONVERT_STREAMABLE(type, +) + +YAML_DEFINE_CONVERT_STREAMABLE_SIGNED(int); +YAML_DEFINE_CONVERT_STREAMABLE_SIGNED(short); +YAML_DEFINE_CONVERT_STREAMABLE_SIGNED(long); +YAML_DEFINE_CONVERT_STREAMABLE_SIGNED(long long); +YAML_DEFINE_CONVERT_STREAMABLE_UNSIGNED(unsigned); +YAML_DEFINE_CONVERT_STREAMABLE_UNSIGNED(unsigned short); +YAML_DEFINE_CONVERT_STREAMABLE_UNSIGNED(unsigned long); +YAML_DEFINE_CONVERT_STREAMABLE_UNSIGNED(unsigned long long); + +YAML_DEFINE_CONVERT_STREAMABLE_SIGNED(char); +YAML_DEFINE_CONVERT_STREAMABLE_SIGNED(signed char); +YAML_DEFINE_CONVERT_STREAMABLE_UNSIGNED(unsigned char); + +YAML_DEFINE_CONVERT_STREAMABLE_SIGNED(float); +YAML_DEFINE_CONVERT_STREAMABLE_SIGNED(double); +YAML_DEFINE_CONVERT_STREAMABLE_SIGNED(long double); + +#undef YAML_DEFINE_CONVERT_STREAMABLE_SIGNED +#undef YAML_DEFINE_CONVERT_STREAMABLE_UNSIGNED +#undef YAML_DEFINE_CONVERT_STREAMABLE + +// bool +template <> +struct convert { + static Node encode(bool rhs) { return rhs ? Node("true") : Node("false"); } + + YAML_CPP_API static bool decode(const Node& node, bool& rhs); +}; + +// std::map +template +struct convert> { + static Node encode(const std::map& rhs) { + Node node(NodeType::Map); + for (typename std::map::const_iterator it = rhs.begin(); + it != rhs.end(); ++it) + node.force_insert(it->first, it->second); + return node; + } + + static bool decode(const Node& node, std::map& rhs) { + if (!node.IsMap()) + return false; + + rhs.clear(); + for (const_iterator it = node.begin(); it != node.end(); ++it) +#if defined(__GNUC__) && __GNUC__ < 4 + // workaround for GCC 3: + rhs[it->first.template as()] = it->second.template as(); +#else + rhs[it->first.as()] = it->second.as(); +#endif + return true; + } +}; + +// std::vector +template +struct convert> { + static Node encode(const std::vector& rhs) { + Node node(NodeType::Sequence); + for (typename std::vector::const_iterator it = rhs.begin(); + it != rhs.end(); ++it) + node.push_back(*it); + return node; + } + + static bool decode(const Node& node, std::vector& rhs) { + if (!node.IsSequence()) + return false; + + rhs.clear(); + for (const_iterator it = node.begin(); it != node.end(); ++it) +#if defined(__GNUC__) && __GNUC__ < 4 + // workaround for GCC 3: + rhs.push_back(it->template as()); +#else + rhs.push_back(it->as()); +#endif + return true; + } +}; + +// std::list +template +struct convert> { + static Node encode(const std::list& rhs) { + Node node(NodeType::Sequence); + for (typename std::list::const_iterator it = rhs.begin(); + it != rhs.end(); ++it) + node.push_back(*it); + return node; + } + + static bool decode(const Node& node, std::list& rhs) { + if (!node.IsSequence()) + return false; + + rhs.clear(); + for (const_iterator it = node.begin(); it != node.end(); ++it) +#if defined(__GNUC__) && __GNUC__ < 4 + // workaround for GCC 3: + rhs.push_back(it->template as()); +#else + rhs.push_back(it->as()); +#endif + return true; + } +}; + +// std::array +template +struct convert> { + static Node encode(const std::array& rhs) { + Node node(NodeType::Sequence); + for (const auto& element : rhs) { + node.push_back(element); + } + return node; + } + + static bool decode(const Node& node, std::array& rhs) { + if (!isNodeValid(node)) { + return false; + } + + for (auto i = 0u; i < node.size(); ++i) { +#if defined(__GNUC__) && __GNUC__ < 4 + // workaround for GCC 3: + rhs[i] = node[i].template as(); +#else + rhs[i] = node[i].as(); +#endif + } + return true; + } + + private: + static bool isNodeValid(const Node& node) { + return node.IsSequence() && node.size() == N; + } +}; + +// std::pair +template +struct convert> { + static Node encode(const std::pair& rhs) { + Node node(NodeType::Sequence); + node.push_back(rhs.first); + node.push_back(rhs.second); + return node; + } + + static bool decode(const Node& node, std::pair& rhs) { + if (!node.IsSequence()) + return false; + if (node.size() != 2) + return false; + +#if defined(__GNUC__) && __GNUC__ < 4 + // workaround for GCC 3: + rhs.first = node[0].template as(); +#else + rhs.first = node[0].as(); +#endif +#if defined(__GNUC__) && __GNUC__ < 4 + // workaround for GCC 3: + rhs.second = node[1].template as(); +#else + rhs.second = node[1].as(); +#endif + return true; + } +}; + +// binary +template <> +struct convert { + static Node encode(const Binary& rhs) { + return Node(EncodeBase64(rhs.data(), rhs.size())); + } + + static bool decode(const Node& node, Binary& rhs) { + if (!node.IsScalar()) + return false; + + std::vector data = DecodeBase64(node.Scalar()); + if (data.empty() && !node.Scalar().empty()) + return false; + + rhs.swap(data); + return true; + } +}; +} + +#endif // NODE_CONVERT_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/bool_type.h b/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/bool_type.h new file mode 100644 index 0000000000..2c80705c9a --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/bool_type.h @@ -0,0 +1,26 @@ +#ifndef NODE_DETAIL_BOOL_TYPE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define NODE_DETAIL_BOOL_TYPE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +namespace YAML { +namespace detail { +struct unspecified_bool { + struct NOT_ALLOWED; + static void true_value(NOT_ALLOWED*) {} +}; +typedef void (*unspecified_bool_type)(unspecified_bool::NOT_ALLOWED*); +} +} + +#define YAML_CPP_OPERATOR_BOOL() \ + operator YAML::detail::unspecified_bool_type() const { \ + return this->operator!() ? 0 \ + : &YAML::detail::unspecified_bool::true_value; \ + } + +#endif // NODE_DETAIL_BOOL_TYPE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/impl.h b/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/impl.h new file mode 100644 index 0000000000..59318264ad --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/impl.h @@ -0,0 +1,185 @@ +#ifndef NODE_DETAIL_IMPL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define NODE_DETAIL_IMPL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include "yaml-cpp/node/detail/node.h" +#include "yaml-cpp/node/detail/node_data.h" +#include + +namespace YAML { +namespace detail { +template +struct get_idx { + static node* get(const std::vector& /* sequence */, + const Key& /* key */, shared_memory_holder /* pMemory */) { + return 0; + } +}; + +template +struct get_idx::value && + !std::is_same::value>::type> { + static node* get(const std::vector& sequence, const Key& key, + shared_memory_holder /* pMemory */) { + return key < sequence.size() ? sequence[key] : 0; + } + + static node* get(std::vector& sequence, const Key& key, + shared_memory_holder pMemory) { + if (key > sequence.size() || (key > 0 && !sequence[key-1]->is_defined())) + return 0; + if (key == sequence.size()) + sequence.push_back(&pMemory->create_node()); + return sequence[key]; + } +}; + +template +struct get_idx::value>::type> { + static node* get(const std::vector& sequence, const Key& key, + shared_memory_holder pMemory) { + return key >= 0 ? get_idx::get( + sequence, static_cast(key), pMemory) + : 0; + } + static node* get(std::vector& sequence, const Key& key, + shared_memory_holder pMemory) { + return key >= 0 ? get_idx::get( + sequence, static_cast(key), pMemory) + : 0; + } +}; + +template +inline bool node::equals(const T& rhs, shared_memory_holder pMemory) { + T lhs; + if (convert::decode(Node(*this, pMemory), lhs)) { + return lhs == rhs; + } + return false; +} + +inline bool node::equals(const char* rhs, shared_memory_holder pMemory) { + return equals(rhs, pMemory); +} + +// indexing +template +inline node* node_data::get(const Key& key, + shared_memory_holder pMemory) const { + switch (m_type) { + case NodeType::Map: + break; + case NodeType::Undefined: + case NodeType::Null: + return NULL; + case NodeType::Sequence: + if (node* pNode = get_idx::get(m_sequence, key, pMemory)) + return pNode; + return NULL; + case NodeType::Scalar: + throw BadSubscript(); + } + + for (node_map::const_iterator it = m_map.begin(); it != m_map.end(); ++it) { + if (it->first->equals(key, pMemory)) { + return it->second; + } + } + + return NULL; +} + +template +inline node& node_data::get(const Key& key, shared_memory_holder pMemory) { + switch (m_type) { + case NodeType::Map: + break; + case NodeType::Undefined: + case NodeType::Null: + case NodeType::Sequence: + if (node* pNode = get_idx::get(m_sequence, key, pMemory)) { + m_type = NodeType::Sequence; + return *pNode; + } + + convert_to_map(pMemory); + break; + case NodeType::Scalar: + throw BadSubscript(); + } + + for (node_map::const_iterator it = m_map.begin(); it != m_map.end(); ++it) { + if (it->first->equals(key, pMemory)) { + return *it->second; + } + } + + node& k = convert_to_node(key, pMemory); + node& v = pMemory->create_node(); + insert_map_pair(k, v); + return v; +} + +template +inline bool node_data::remove(const Key& key, shared_memory_holder pMemory) { + if (m_type != NodeType::Map) + return false; + + kv_pairs::iterator it = m_undefinedPairs.begin(); + while (it != m_undefinedPairs.end()) { + kv_pairs::iterator jt = std::next(it); + if (it->first->equals(key, pMemory)) + m_undefinedPairs.erase(it); + it = jt; + } + + for (node_map::iterator it = m_map.begin(); it != m_map.end(); ++it) { + if (it->first->equals(key, pMemory)) { + m_map.erase(it); + return true; + } + } + + return false; +} + +// map +template +inline void node_data::force_insert(const Key& key, const Value& value, + shared_memory_holder pMemory) { + switch (m_type) { + case NodeType::Map: + break; + case NodeType::Undefined: + case NodeType::Null: + case NodeType::Sequence: + convert_to_map(pMemory); + break; + case NodeType::Scalar: + throw BadInsert(); + } + + node& k = convert_to_node(key, pMemory); + node& v = convert_to_node(value, pMemory); + insert_map_pair(k, v); +} + +template +inline node& node_data::convert_to_node(const T& rhs, + shared_memory_holder pMemory) { + Node value = convert::encode(rhs); + value.EnsureNodeExists(); + pMemory->merge(*value.m_pMemory); + return *value.m_pNode; +} +} +} + +#endif // NODE_DETAIL_IMPL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/iterator.h b/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/iterator.h new file mode 100644 index 0000000000..65f8152498 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/iterator.h @@ -0,0 +1,91 @@ +#ifndef VALUE_DETAIL_ITERATOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define VALUE_DETAIL_ITERATOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include "yaml-cpp/dll.h" +#include "yaml-cpp/node/ptr.h" +#include "yaml-cpp/node/detail/node_iterator.h" +#include +#include + +namespace YAML { +namespace detail { +struct iterator_value; + +template +class iterator_base : public std::iterator { + + private: + template + friend class iterator_base; + struct enabler {}; + typedef node_iterator base_type; + + struct proxy { + explicit proxy(const V& x) : m_ref(x) {} + V* operator->() { return std::addressof(m_ref); } + operator V*() { return std::addressof(m_ref); } + + V m_ref; + }; + + public: + typedef typename iterator_base::value_type value_type; + + public: + iterator_base() : m_iterator(), m_pMemory() {} + explicit iterator_base(base_type rhs, shared_memory_holder pMemory) + : m_iterator(rhs), m_pMemory(pMemory) {} + + template + iterator_base(const iterator_base& rhs, + typename std::enable_if::value, + enabler>::type = enabler()) + : m_iterator(rhs.m_iterator), m_pMemory(rhs.m_pMemory) {} + + iterator_base& operator++() { + ++m_iterator; + return *this; + } + + iterator_base operator++(int) { + iterator_base iterator_pre(*this); + ++(*this); + return iterator_pre; + } + + template + bool operator==(const iterator_base& rhs) const { + return m_iterator == rhs.m_iterator; + } + + template + bool operator!=(const iterator_base& rhs) const { + return m_iterator != rhs.m_iterator; + } + + value_type operator*() const { + const typename base_type::value_type& v = *m_iterator; + if (v.pNode) + return value_type(Node(*v, m_pMemory)); + if (v.first && v.second) + return value_type(Node(*v.first, m_pMemory), Node(*v.second, m_pMemory)); + return value_type(); + } + + proxy operator->() const { return proxy(**this); } + + private: + base_type m_iterator; + shared_memory_holder m_pMemory; +}; +} +} + +#endif // VALUE_DETAIL_ITERATOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/iterator_fwd.h b/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/iterator_fwd.h new file mode 100644 index 0000000000..5f1ffe7436 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/iterator_fwd.h @@ -0,0 +1,27 @@ +#ifndef VALUE_DETAIL_ITERATOR_FWD_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define VALUE_DETAIL_ITERATOR_FWD_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include "yaml-cpp/dll.h" +#include +#include +#include + +namespace YAML { + +namespace detail { +struct iterator_value; +template +class iterator_base; +} + +typedef detail::iterator_base iterator; +typedef detail::iterator_base const_iterator; +} + +#endif // VALUE_DETAIL_ITERATOR_FWD_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/memory.h b/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/memory.h new file mode 100644 index 0000000000..8f2bc2657a --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/memory.h @@ -0,0 +1,46 @@ +#ifndef VALUE_DETAIL_MEMORY_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define VALUE_DETAIL_MEMORY_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include + +#include "yaml-cpp/dll.h" +#include "yaml-cpp/node/ptr.h" + +namespace YAML { +namespace detail { +class node; +} // namespace detail +} // namespace YAML + +namespace YAML { +namespace detail { +class YAML_CPP_API memory { + public: + node& create_node(); + void merge(const memory& rhs); + + private: + typedef std::set Nodes; + Nodes m_nodes; +}; + +class YAML_CPP_API memory_holder { + public: + memory_holder() : m_pMemory(new memory) {} + + node& create_node() { return m_pMemory->create_node(); } + void merge(memory_holder& rhs); + + private: + shared_memory m_pMemory; +}; +} +} + +#endif // VALUE_DETAIL_MEMORY_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/node.h b/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/node.h new file mode 100644 index 0000000000..3154a527c3 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/node.h @@ -0,0 +1,169 @@ +#ifndef NODE_DETAIL_NODE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define NODE_DETAIL_NODE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include "yaml-cpp/emitterstyle.h" +#include "yaml-cpp/dll.h" +#include "yaml-cpp/node/type.h" +#include "yaml-cpp/node/ptr.h" +#include "yaml-cpp/node/detail/node_ref.h" +#include + +namespace YAML { +namespace detail { +class node { + public: + node() : m_pRef(new node_ref) {} + node(const node&) = delete; + node& operator=(const node&) = delete; + + bool is(const node& rhs) const { return m_pRef == rhs.m_pRef; } + const node_ref* ref() const { return m_pRef.get(); } + + bool is_defined() const { return m_pRef->is_defined(); } + const Mark& mark() const { return m_pRef->mark(); } + NodeType::value type() const { return m_pRef->type(); } + + const std::string& scalar() const { return m_pRef->scalar(); } + const std::string& tag() const { return m_pRef->tag(); } + EmitterStyle::value style() const { return m_pRef->style(); } + + template + bool equals(const T& rhs, shared_memory_holder pMemory); + bool equals(const char* rhs, shared_memory_holder pMemory); + + void mark_defined() { + if (is_defined()) + return; + + m_pRef->mark_defined(); + for (nodes::iterator it = m_dependencies.begin(); + it != m_dependencies.end(); ++it) + (*it)->mark_defined(); + m_dependencies.clear(); + } + + void add_dependency(node& rhs) { + if (is_defined()) + rhs.mark_defined(); + else + m_dependencies.insert(&rhs); + } + + void set_ref(const node& rhs) { + if (rhs.is_defined()) + mark_defined(); + m_pRef = rhs.m_pRef; + } + void set_data(const node& rhs) { + if (rhs.is_defined()) + mark_defined(); + m_pRef->set_data(*rhs.m_pRef); + } + + void set_mark(const Mark& mark) { m_pRef->set_mark(mark); } + + void set_type(NodeType::value type) { + if (type != NodeType::Undefined) + mark_defined(); + m_pRef->set_type(type); + } + void set_null() { + mark_defined(); + m_pRef->set_null(); + } + void set_scalar(const std::string& scalar) { + mark_defined(); + m_pRef->set_scalar(scalar); + } + void set_tag(const std::string& tag) { + mark_defined(); + m_pRef->set_tag(tag); + } + + // style + void set_style(EmitterStyle::value style) { + mark_defined(); + m_pRef->set_style(style); + } + + // size/iterator + std::size_t size() const { return m_pRef->size(); } + + const_node_iterator begin() const { + return static_cast(*m_pRef).begin(); + } + node_iterator begin() { return m_pRef->begin(); } + + const_node_iterator end() const { + return static_cast(*m_pRef).end(); + } + node_iterator end() { return m_pRef->end(); } + + // sequence + void push_back(node& node, shared_memory_holder pMemory) { + m_pRef->push_back(node, pMemory); + node.add_dependency(*this); + } + void insert(node& key, node& value, shared_memory_holder pMemory) { + m_pRef->insert(key, value, pMemory); + key.add_dependency(*this); + value.add_dependency(*this); + } + + // indexing + template + node* get(const Key& key, shared_memory_holder pMemory) const { + // NOTE: this returns a non-const node so that the top-level Node can wrap + // it, and returns a pointer so that it can be NULL (if there is no such + // key). + return static_cast(*m_pRef).get(key, pMemory); + } + template + node& get(const Key& key, shared_memory_holder pMemory) { + node& value = m_pRef->get(key, pMemory); + value.add_dependency(*this); + return value; + } + template + bool remove(const Key& key, shared_memory_holder pMemory) { + return m_pRef->remove(key, pMemory); + } + + node* get(node& key, shared_memory_holder pMemory) const { + // NOTE: this returns a non-const node so that the top-level Node can wrap + // it, and returns a pointer so that it can be NULL (if there is no such + // key). + return static_cast(*m_pRef).get(key, pMemory); + } + node& get(node& key, shared_memory_holder pMemory) { + node& value = m_pRef->get(key, pMemory); + key.add_dependency(*this); + value.add_dependency(*this); + return value; + } + bool remove(node& key, shared_memory_holder pMemory) { + return m_pRef->remove(key, pMemory); + } + + // map + template + void force_insert(const Key& key, const Value& value, + shared_memory_holder pMemory) { + m_pRef->force_insert(key, value, pMemory); + } + + private: + shared_node_ref m_pRef; + typedef std::set nodes; + nodes m_dependencies; +}; +} +} + +#endif // NODE_DETAIL_NODE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/node_data.h b/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/node_data.h new file mode 100644 index 0000000000..50bcd74352 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/node_data.h @@ -0,0 +1,127 @@ +#ifndef VALUE_DETAIL_NODE_DATA_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define VALUE_DETAIL_NODE_DATA_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include +#include +#include +#include +#include + +#include "yaml-cpp/dll.h" +#include "yaml-cpp/node/detail/node_iterator.h" +#include "yaml-cpp/node/iterator.h" +#include "yaml-cpp/node/ptr.h" +#include "yaml-cpp/node/type.h" + +namespace YAML { +namespace detail { +class node; +} // namespace detail +} // namespace YAML + +namespace YAML { +namespace detail { +class YAML_CPP_API node_data { + public: + node_data(); + node_data(const node_data&) = delete; + node_data& operator=(const node_data&) = delete; + + void mark_defined(); + void set_mark(const Mark& mark); + void set_type(NodeType::value type); + void set_tag(const std::string& tag); + void set_null(); + void set_scalar(const std::string& scalar); + void set_style(EmitterStyle::value style); + + bool is_defined() const { return m_isDefined; } + const Mark& mark() const { return m_mark; } + NodeType::value type() const { + return m_isDefined ? m_type : NodeType::Undefined; + } + const std::string& scalar() const { return m_scalar; } + const std::string& tag() const { return m_tag; } + EmitterStyle::value style() const { return m_style; } + + // size/iterator + std::size_t size() const; + + const_node_iterator begin() const; + node_iterator begin(); + + const_node_iterator end() const; + node_iterator end(); + + // sequence + void push_back(node& node, shared_memory_holder pMemory); + void insert(node& key, node& value, shared_memory_holder pMemory); + + // indexing + template + node* get(const Key& key, shared_memory_holder pMemory) const; + template + node& get(const Key& key, shared_memory_holder pMemory); + template + bool remove(const Key& key, shared_memory_holder pMemory); + + node* get(node& key, shared_memory_holder pMemory) const; + node& get(node& key, shared_memory_holder pMemory); + bool remove(node& key, shared_memory_holder pMemory); + + // map + template + void force_insert(const Key& key, const Value& value, + shared_memory_holder pMemory); + + public: + static std::string empty_scalar; + + private: + void compute_seq_size() const; + void compute_map_size() const; + + void reset_sequence(); + void reset_map(); + + void insert_map_pair(node& key, node& value); + void convert_to_map(shared_memory_holder pMemory); + void convert_sequence_to_map(shared_memory_holder pMemory); + + template + static node& convert_to_node(const T& rhs, shared_memory_holder pMemory); + + private: + bool m_isDefined; + Mark m_mark; + NodeType::value m_type; + std::string m_tag; + EmitterStyle::value m_style; + + // scalar + std::string m_scalar; + + // sequence + typedef std::vector node_seq; + node_seq m_sequence; + + mutable std::size_t m_seqSize; + + // map + typedef std::vector> node_map; + node_map m_map; + + typedef std::pair kv_pair; + typedef std::list kv_pairs; + mutable kv_pairs m_undefinedPairs; +}; +} +} + +#endif // VALUE_DETAIL_NODE_DATA_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/node_iterator.h b/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/node_iterator.h new file mode 100644 index 0000000000..4337df4167 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/node_iterator.h @@ -0,0 +1,180 @@ +#ifndef VALUE_DETAIL_NODE_ITERATOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define VALUE_DETAIL_NODE_ITERATOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include "yaml-cpp/dll.h" +#include "yaml-cpp/node/ptr.h" +#include +#include +#include +#include +#include +#include + +namespace YAML { +namespace detail { +struct iterator_type { + enum value { None, Sequence, Map }; +}; + +template +struct node_iterator_value : public std::pair { + typedef std::pair kv; + + node_iterator_value() : kv(), pNode(0) {} + explicit node_iterator_value(V& rhs) : kv(), pNode(&rhs) {} + explicit node_iterator_value(V& key, V& value) : kv(&key, &value), pNode(0) {} + + V& operator*() const { return *pNode; } + V& operator->() const { return *pNode; } + + V* pNode; +}; + +typedef std::vector node_seq; +typedef std::vector> node_map; + +template +struct node_iterator_type { + typedef node_seq::iterator seq; + typedef node_map::iterator map; +}; + +template +struct node_iterator_type { + typedef node_seq::const_iterator seq; + typedef node_map::const_iterator map; +}; + +template +class node_iterator_base + : public std::iterator, + std::ptrdiff_t, node_iterator_value*, + node_iterator_value> { + private: + struct enabler {}; + + struct proxy { + explicit proxy(const node_iterator_value& x) : m_ref(x) {} + node_iterator_value* operator->() { return std::addressof(m_ref); } + operator node_iterator_value*() { return std::addressof(m_ref); } + + node_iterator_value m_ref; + }; + + public: + typedef typename node_iterator_type::seq SeqIter; + typedef typename node_iterator_type::map MapIter; + typedef node_iterator_value value_type; + + node_iterator_base() + : m_type(iterator_type::None), m_seqIt(), m_mapIt(), m_mapEnd() {} + explicit node_iterator_base(SeqIter seqIt) + : m_type(iterator_type::Sequence), + m_seqIt(seqIt), + m_mapIt(), + m_mapEnd() {} + explicit node_iterator_base(MapIter mapIt, MapIter mapEnd) + : m_type(iterator_type::Map), + m_seqIt(), + m_mapIt(mapIt), + m_mapEnd(mapEnd) { + m_mapIt = increment_until_defined(m_mapIt); + } + + template + node_iterator_base(const node_iterator_base& rhs, + typename std::enable_if::value, + enabler>::type = enabler()) + : m_type(rhs.m_type), + m_seqIt(rhs.m_seqIt), + m_mapIt(rhs.m_mapIt), + m_mapEnd(rhs.m_mapEnd) {} + + template + friend class node_iterator_base; + + template + bool operator==(const node_iterator_base& rhs) const { + if (m_type != rhs.m_type) + return false; + + switch (m_type) { + case iterator_type::None: + return true; + case iterator_type::Sequence: + return m_seqIt == rhs.m_seqIt; + case iterator_type::Map: + return m_mapIt == rhs.m_mapIt; + } + return true; + } + + template + bool operator!=(const node_iterator_base& rhs) const { + return !(*this == rhs); + } + + node_iterator_base& operator++() { + switch (m_type) { + case iterator_type::None: + break; + case iterator_type::Sequence: + ++m_seqIt; + break; + case iterator_type::Map: + ++m_mapIt; + m_mapIt = increment_until_defined(m_mapIt); + break; + } + return *this; + } + + node_iterator_base operator++(int) { + node_iterator_base iterator_pre(*this); + ++(*this); + return iterator_pre; + } + + value_type operator*() const { + switch (m_type) { + case iterator_type::None: + return value_type(); + case iterator_type::Sequence: + return value_type(**m_seqIt); + case iterator_type::Map: + return value_type(*m_mapIt->first, *m_mapIt->second); + } + return value_type(); + } + + proxy operator->() const { return proxy(**this); } + + MapIter increment_until_defined(MapIter it) { + while (it != m_mapEnd && !is_defined(it)) + ++it; + return it; + } + + bool is_defined(MapIter it) const { + return it->first->is_defined() && it->second->is_defined(); + } + + private: + typename iterator_type::value m_type; + + SeqIter m_seqIt; + MapIter m_mapIt, m_mapEnd; +}; + +typedef node_iterator_base node_iterator; +typedef node_iterator_base const_node_iterator; +} +} + +#endif // VALUE_DETAIL_NODE_ITERATOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/node_ref.h b/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/node_ref.h new file mode 100644 index 0000000000..d8a94f8b80 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/node/detail/node_ref.h @@ -0,0 +1,98 @@ +#ifndef VALUE_DETAIL_NODE_REF_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define VALUE_DETAIL_NODE_REF_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include "yaml-cpp/dll.h" +#include "yaml-cpp/node/type.h" +#include "yaml-cpp/node/ptr.h" +#include "yaml-cpp/node/detail/node_data.h" + +namespace YAML { +namespace detail { +class node_ref { + public: + node_ref() : m_pData(new node_data) {} + node_ref(const node_ref&) = delete; + node_ref& operator=(const node_ref&) = delete; + + bool is_defined() const { return m_pData->is_defined(); } + const Mark& mark() const { return m_pData->mark(); } + NodeType::value type() const { return m_pData->type(); } + const std::string& scalar() const { return m_pData->scalar(); } + const std::string& tag() const { return m_pData->tag(); } + EmitterStyle::value style() const { return m_pData->style(); } + + void mark_defined() { m_pData->mark_defined(); } + void set_data(const node_ref& rhs) { m_pData = rhs.m_pData; } + + void set_mark(const Mark& mark) { m_pData->set_mark(mark); } + void set_type(NodeType::value type) { m_pData->set_type(type); } + void set_tag(const std::string& tag) { m_pData->set_tag(tag); } + void set_null() { m_pData->set_null(); } + void set_scalar(const std::string& scalar) { m_pData->set_scalar(scalar); } + void set_style(EmitterStyle::value style) { m_pData->set_style(style); } + + // size/iterator + std::size_t size() const { return m_pData->size(); } + + const_node_iterator begin() const { + return static_cast(*m_pData).begin(); + } + node_iterator begin() { return m_pData->begin(); } + + const_node_iterator end() const { + return static_cast(*m_pData).end(); + } + node_iterator end() { return m_pData->end(); } + + // sequence + void push_back(node& node, shared_memory_holder pMemory) { + m_pData->push_back(node, pMemory); + } + void insert(node& key, node& value, shared_memory_holder pMemory) { + m_pData->insert(key, value, pMemory); + } + + // indexing + template + node* get(const Key& key, shared_memory_holder pMemory) const { + return static_cast(*m_pData).get(key, pMemory); + } + template + node& get(const Key& key, shared_memory_holder pMemory) { + return m_pData->get(key, pMemory); + } + template + bool remove(const Key& key, shared_memory_holder pMemory) { + return m_pData->remove(key, pMemory); + } + + node* get(node& key, shared_memory_holder pMemory) const { + return static_cast(*m_pData).get(key, pMemory); + } + node& get(node& key, shared_memory_holder pMemory) { + return m_pData->get(key, pMemory); + } + bool remove(node& key, shared_memory_holder pMemory) { + return m_pData->remove(key, pMemory); + } + + // map + template + void force_insert(const Key& key, const Value& value, + shared_memory_holder pMemory) { + m_pData->force_insert(key, value, pMemory); + } + + private: + shared_node_data m_pData; +}; +} +} + +#endif // VALUE_DETAIL_NODE_REF_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/node/emit.h b/phonelibs/yaml-cpp/include/yaml-cpp/node/emit.h new file mode 100644 index 0000000000..032268c5d0 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/node/emit.h @@ -0,0 +1,32 @@ +#ifndef NODE_EMIT_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define NODE_EMIT_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include +#include + +#include "yaml-cpp/dll.h" + +namespace YAML { +class Emitter; +class Node; + +/** + * Emits the node to the given {@link Emitter}. If there is an error in writing, + * {@link Emitter#good} will return false. + */ +YAML_CPP_API Emitter& operator<<(Emitter& out, const Node& node); + +/** Emits the node to the given output stream. */ +YAML_CPP_API std::ostream& operator<<(std::ostream& out, const Node& node); + +/** Converts the node to a YAML string. */ +YAML_CPP_API std::string Dump(const Node& node); +} // namespace YAML + +#endif // NODE_EMIT_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/node/impl.h b/phonelibs/yaml-cpp/include/yaml-cpp/node/impl.h new file mode 100644 index 0000000000..20c487a687 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/node/impl.h @@ -0,0 +1,448 @@ +#ifndef NODE_IMPL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define NODE_IMPL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include "yaml-cpp/node/node.h" +#include "yaml-cpp/node/iterator.h" +#include "yaml-cpp/node/detail/memory.h" +#include "yaml-cpp/node/detail/node.h" +#include "yaml-cpp/exceptions.h" +#include + +namespace YAML { +inline Node::Node() : m_isValid(true), m_pNode(NULL) {} + +inline Node::Node(NodeType::value type) + : m_isValid(true), + m_pMemory(new detail::memory_holder), + m_pNode(&m_pMemory->create_node()) { + m_pNode->set_type(type); +} + +template +inline Node::Node(const T& rhs) + : m_isValid(true), + m_pMemory(new detail::memory_holder), + m_pNode(&m_pMemory->create_node()) { + Assign(rhs); +} + +inline Node::Node(const detail::iterator_value& rhs) + : m_isValid(rhs.m_isValid), + m_pMemory(rhs.m_pMemory), + m_pNode(rhs.m_pNode) {} + +inline Node::Node(const Node& rhs) + : m_isValid(rhs.m_isValid), + m_pMemory(rhs.m_pMemory), + m_pNode(rhs.m_pNode) {} + +inline Node::Node(Zombie) : m_isValid(false), m_pNode(NULL) {} + +inline Node::Node(detail::node& node, detail::shared_memory_holder pMemory) + : m_isValid(true), m_pMemory(pMemory), m_pNode(&node) {} + +inline Node::~Node() {} + +inline void Node::EnsureNodeExists() const { + if (!m_isValid) + throw InvalidNode(); + if (!m_pNode) { + m_pMemory.reset(new detail::memory_holder); + m_pNode = &m_pMemory->create_node(); + m_pNode->set_null(); + } +} + +inline bool Node::IsDefined() const { + if (!m_isValid) { + return false; + } + return m_pNode ? m_pNode->is_defined() : true; +} + +inline Mark Node::Mark() const { + if (!m_isValid) { + throw InvalidNode(); + } + return m_pNode ? m_pNode->mark() : Mark::null_mark(); +} + +inline NodeType::value Node::Type() const { + if (!m_isValid) + throw InvalidNode(); + return m_pNode ? m_pNode->type() : NodeType::Null; +} + +// access + +// template helpers +template +struct as_if { + explicit as_if(const Node& node_) : node(node_) {} + const Node& node; + + T operator()(const S& fallback) const { + if (!node.m_pNode) + return fallback; + + T t; + if (convert::decode(node, t)) + return t; + return fallback; + } +}; + +template +struct as_if { + explicit as_if(const Node& node_) : node(node_) {} + const Node& node; + + std::string operator()(const S& fallback) const { + if (node.Type() != NodeType::Scalar) + return fallback; + return node.Scalar(); + } +}; + +template +struct as_if { + explicit as_if(const Node& node_) : node(node_) {} + const Node& node; + + T operator()() const { + if (!node.m_pNode) + throw TypedBadConversion(node.Mark()); + + T t; + if (convert::decode(node, t)) + return t; + throw TypedBadConversion(node.Mark()); + } +}; + +template <> +struct as_if { + explicit as_if(const Node& node_) : node(node_) {} + const Node& node; + + std::string operator()() const { + if (node.Type() != NodeType::Scalar) + throw TypedBadConversion(node.Mark()); + return node.Scalar(); + } +}; + +// access functions +template +inline T Node::as() const { + if (!m_isValid) + throw InvalidNode(); + return as_if(*this)(); +} + +template +inline T Node::as(const S& fallback) const { + if (!m_isValid) + return fallback; + return as_if(*this)(fallback); +} + +inline const std::string& Node::Scalar() const { + if (!m_isValid) + throw InvalidNode(); + return m_pNode ? m_pNode->scalar() : detail::node_data::empty_scalar; +} + +inline const std::string& Node::Tag() const { + if (!m_isValid) + throw InvalidNode(); + return m_pNode ? m_pNode->tag() : detail::node_data::empty_scalar; +} + +inline void Node::SetTag(const std::string& tag) { + if (!m_isValid) + throw InvalidNode(); + EnsureNodeExists(); + m_pNode->set_tag(tag); +} + +inline EmitterStyle::value Node::Style() const { + if (!m_isValid) + throw InvalidNode(); + return m_pNode ? m_pNode->style() : EmitterStyle::Default; +} + +inline void Node::SetStyle(EmitterStyle::value style) { + if (!m_isValid) + throw InvalidNode(); + EnsureNodeExists(); + m_pNode->set_style(style); +} + +// assignment +inline bool Node::is(const Node& rhs) const { + if (!m_isValid || !rhs.m_isValid) + throw InvalidNode(); + if (!m_pNode || !rhs.m_pNode) + return false; + return m_pNode->is(*rhs.m_pNode); +} + +template +inline Node& Node::operator=(const T& rhs) { + if (!m_isValid) + throw InvalidNode(); + Assign(rhs); + return *this; +} + +inline void Node::reset(const YAML::Node& rhs) { + if (!m_isValid || !rhs.m_isValid) + throw InvalidNode(); + m_pMemory = rhs.m_pMemory; + m_pNode = rhs.m_pNode; +} + +template +inline void Node::Assign(const T& rhs) { + if (!m_isValid) + throw InvalidNode(); + AssignData(convert::encode(rhs)); +} + +template <> +inline void Node::Assign(const std::string& rhs) { + if (!m_isValid) + throw InvalidNode(); + EnsureNodeExists(); + m_pNode->set_scalar(rhs); +} + +inline void Node::Assign(const char* rhs) { + if (!m_isValid) + throw InvalidNode(); + EnsureNodeExists(); + m_pNode->set_scalar(rhs); +} + +inline void Node::Assign(char* rhs) { + if (!m_isValid) + throw InvalidNode(); + EnsureNodeExists(); + m_pNode->set_scalar(rhs); +} + +inline Node& Node::operator=(const Node& rhs) { + if (!m_isValid || !rhs.m_isValid) + throw InvalidNode(); + if (is(rhs)) + return *this; + AssignNode(rhs); + return *this; +} + +inline void Node::AssignData(const Node& rhs) { + if (!m_isValid || !rhs.m_isValid) + throw InvalidNode(); + EnsureNodeExists(); + rhs.EnsureNodeExists(); + + m_pNode->set_data(*rhs.m_pNode); + m_pMemory->merge(*rhs.m_pMemory); +} + +inline void Node::AssignNode(const Node& rhs) { + if (!m_isValid || !rhs.m_isValid) + throw InvalidNode(); + rhs.EnsureNodeExists(); + + if (!m_pNode) { + m_pNode = rhs.m_pNode; + m_pMemory = rhs.m_pMemory; + return; + } + + m_pNode->set_ref(*rhs.m_pNode); + m_pMemory->merge(*rhs.m_pMemory); + m_pNode = rhs.m_pNode; +} + +// size/iterator +inline std::size_t Node::size() const { + if (!m_isValid) + throw InvalidNode(); + return m_pNode ? m_pNode->size() : 0; +} + +inline const_iterator Node::begin() const { + if (!m_isValid) + return const_iterator(); + return m_pNode ? const_iterator(m_pNode->begin(), m_pMemory) + : const_iterator(); +} + +inline iterator Node::begin() { + if (!m_isValid) + return iterator(); + return m_pNode ? iterator(m_pNode->begin(), m_pMemory) : iterator(); +} + +inline const_iterator Node::end() const { + if (!m_isValid) + return const_iterator(); + return m_pNode ? const_iterator(m_pNode->end(), m_pMemory) : const_iterator(); +} + +inline iterator Node::end() { + if (!m_isValid) + return iterator(); + return m_pNode ? iterator(m_pNode->end(), m_pMemory) : iterator(); +} + +// sequence +template +inline void Node::push_back(const T& rhs) { + if (!m_isValid) + throw InvalidNode(); + push_back(Node(rhs)); +} + +inline void Node::push_back(const Node& rhs) { + if (!m_isValid || !rhs.m_isValid) + throw InvalidNode(); + EnsureNodeExists(); + rhs.EnsureNodeExists(); + + m_pNode->push_back(*rhs.m_pNode, m_pMemory); + m_pMemory->merge(*rhs.m_pMemory); +} + +// helpers for indexing +namespace detail { +template +struct to_value_t { + explicit to_value_t(const T& t_) : t(t_) {} + const T& t; + typedef const T& return_type; + + const T& operator()() const { return t; } +}; + +template <> +struct to_value_t { + explicit to_value_t(const char* t_) : t(t_) {} + const char* t; + typedef std::string return_type; + + const std::string operator()() const { return t; } +}; + +template <> +struct to_value_t { + explicit to_value_t(char* t_) : t(t_) {} + const char* t; + typedef std::string return_type; + + const std::string operator()() const { return t; } +}; + +template +struct to_value_t { + explicit to_value_t(const char* t_) : t(t_) {} + const char* t; + typedef std::string return_type; + + const std::string operator()() const { return t; } +}; + +// converts C-strings to std::strings so they can be copied +template +inline typename to_value_t::return_type to_value(const T& t) { + return to_value_t(t)(); +} +} + +// indexing +template +inline const Node Node::operator[](const Key& key) const { + if (!m_isValid) + throw InvalidNode(); + EnsureNodeExists(); + detail::node* value = static_cast(*m_pNode) + .get(detail::to_value(key), m_pMemory); + if (!value) { + return Node(ZombieNode); + } + return Node(*value, m_pMemory); +} + +template +inline Node Node::operator[](const Key& key) { + if (!m_isValid) + throw InvalidNode(); + EnsureNodeExists(); + detail::node& value = m_pNode->get(detail::to_value(key), m_pMemory); + return Node(value, m_pMemory); +} + +template +inline bool Node::remove(const Key& key) { + if (!m_isValid) + throw InvalidNode(); + EnsureNodeExists(); + return m_pNode->remove(detail::to_value(key), m_pMemory); +} + +inline const Node Node::operator[](const Node& key) const { + if (!m_isValid || !key.m_isValid) + throw InvalidNode(); + EnsureNodeExists(); + key.EnsureNodeExists(); + m_pMemory->merge(*key.m_pMemory); + detail::node* value = + static_cast(*m_pNode).get(*key.m_pNode, m_pMemory); + if (!value) { + return Node(ZombieNode); + } + return Node(*value, m_pMemory); +} + +inline Node Node::operator[](const Node& key) { + if (!m_isValid || !key.m_isValid) + throw InvalidNode(); + EnsureNodeExists(); + key.EnsureNodeExists(); + m_pMemory->merge(*key.m_pMemory); + detail::node& value = m_pNode->get(*key.m_pNode, m_pMemory); + return Node(value, m_pMemory); +} + +inline bool Node::remove(const Node& key) { + if (!m_isValid || !key.m_isValid) + throw InvalidNode(); + EnsureNodeExists(); + key.EnsureNodeExists(); + return m_pNode->remove(*key.m_pNode, m_pMemory); +} + +// map +template +inline void Node::force_insert(const Key& key, const Value& value) { + if (!m_isValid) + throw InvalidNode(); + EnsureNodeExists(); + m_pNode->force_insert(detail::to_value(key), detail::to_value(value), + m_pMemory); +} + +// free functions +inline bool operator==(const Node& lhs, const Node& rhs) { return lhs.is(rhs); } +} + +#endif // NODE_IMPL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/node/iterator.h b/phonelibs/yaml-cpp/include/yaml-cpp/node/iterator.h new file mode 100644 index 0000000000..366a9c807f --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/node/iterator.h @@ -0,0 +1,31 @@ +#ifndef VALUE_ITERATOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define VALUE_ITERATOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include "yaml-cpp/dll.h" +#include "yaml-cpp/node/node.h" +#include "yaml-cpp/node/detail/iterator_fwd.h" +#include "yaml-cpp/node/detail/iterator.h" +#include +#include +#include + +namespace YAML { +namespace detail { +struct iterator_value : public Node, std::pair { + iterator_value() {} + explicit iterator_value(const Node& rhs) + : Node(rhs), + std::pair(Node(Node::ZombieNode), Node(Node::ZombieNode)) {} + explicit iterator_value(const Node& key, const Node& value) + : Node(Node::ZombieNode), std::pair(key, value) {} +}; +} +} + +#endif // VALUE_ITERATOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/node/node.h b/phonelibs/yaml-cpp/include/yaml-cpp/node/node.h new file mode 100644 index 0000000000..1ded7d27b7 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/node/node.h @@ -0,0 +1,145 @@ +#ifndef NODE_NODE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define NODE_NODE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include + +#include "yaml-cpp/dll.h" +#include "yaml-cpp/emitterstyle.h" +#include "yaml-cpp/mark.h" +#include "yaml-cpp/node/detail/bool_type.h" +#include "yaml-cpp/node/detail/iterator_fwd.h" +#include "yaml-cpp/node/ptr.h" +#include "yaml-cpp/node/type.h" + +namespace YAML { +namespace detail { +class node; +class node_data; +struct iterator_value; +} // namespace detail +} // namespace YAML + +namespace YAML { +class YAML_CPP_API Node { + public: + friend class NodeBuilder; + friend class NodeEvents; + friend struct detail::iterator_value; + friend class detail::node; + friend class detail::node_data; + template + friend class detail::iterator_base; + template + friend struct as_if; + + typedef YAML::iterator iterator; + typedef YAML::const_iterator const_iterator; + + Node(); + explicit Node(NodeType::value type); + template + explicit Node(const T& rhs); + explicit Node(const detail::iterator_value& rhs); + Node(const Node& rhs); + ~Node(); + + YAML::Mark Mark() const; + NodeType::value Type() const; + bool IsDefined() const; + bool IsNull() const { return Type() == NodeType::Null; } + bool IsScalar() const { return Type() == NodeType::Scalar; } + bool IsSequence() const { return Type() == NodeType::Sequence; } + bool IsMap() const { return Type() == NodeType::Map; } + + // bool conversions + YAML_CPP_OPERATOR_BOOL() + bool operator!() const { return !IsDefined(); } + + // access + template + T as() const; + template + T as(const S& fallback) const; + const std::string& Scalar() const; + + const std::string& Tag() const; + void SetTag(const std::string& tag); + + // style + // WARNING: This API might change in future releases. + EmitterStyle::value Style() const; + void SetStyle(EmitterStyle::value style); + + // assignment + bool is(const Node& rhs) const; + template + Node& operator=(const T& rhs); + Node& operator=(const Node& rhs); + void reset(const Node& rhs = Node()); + + // size/iterator + std::size_t size() const; + + const_iterator begin() const; + iterator begin(); + + const_iterator end() const; + iterator end(); + + // sequence + template + void push_back(const T& rhs); + void push_back(const Node& rhs); + + // indexing + template + const Node operator[](const Key& key) const; + template + Node operator[](const Key& key); + template + bool remove(const Key& key); + + const Node operator[](const Node& key) const; + Node operator[](const Node& key); + bool remove(const Node& key); + + // map + template + void force_insert(const Key& key, const Value& value); + + private: + enum Zombie { ZombieNode }; + explicit Node(Zombie); + explicit Node(detail::node& node, detail::shared_memory_holder pMemory); + + void EnsureNodeExists() const; + + template + void Assign(const T& rhs); + void Assign(const char* rhs); + void Assign(char* rhs); + + void AssignData(const Node& rhs); + void AssignNode(const Node& rhs); + + private: + bool m_isValid; + mutable detail::shared_memory_holder m_pMemory; + mutable detail::node* m_pNode; +}; + +YAML_CPP_API bool operator==(const Node& lhs, const Node& rhs); + +YAML_CPP_API Node Clone(const Node& node); + +template +struct convert; +} + +#endif // NODE_NODE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/node/parse.h b/phonelibs/yaml-cpp/include/yaml-cpp/node/parse.h new file mode 100644 index 0000000000..7745fd7245 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/node/parse.h @@ -0,0 +1,78 @@ +#ifndef VALUE_PARSE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define VALUE_PARSE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include +#include +#include + +#include "yaml-cpp/dll.h" + +namespace YAML { +class Node; + +/** + * Loads the input string as a single YAML document. + * + * @throws {@link ParserException} if it is malformed. + */ +YAML_CPP_API Node Load(const std::string& input); + +/** + * Loads the input string as a single YAML document. + * + * @throws {@link ParserException} if it is malformed. + */ +YAML_CPP_API Node Load(const char* input); + +/** + * Loads the input stream as a single YAML document. + * + * @throws {@link ParserException} if it is malformed. + */ +YAML_CPP_API Node Load(std::istream& input); + +/** + * Loads the input file as a single YAML document. + * + * @throws {@link ParserException} if it is malformed. + * @throws {@link BadFile} if the file cannot be loaded. + */ +YAML_CPP_API Node LoadFile(const std::string& filename); + +/** + * Loads the input string as a list of YAML documents. + * + * @throws {@link ParserException} if it is malformed. + */ +YAML_CPP_API std::vector LoadAll(const std::string& input); + +/** + * Loads the input string as a list of YAML documents. + * + * @throws {@link ParserException} if it is malformed. + */ +YAML_CPP_API std::vector LoadAll(const char* input); + +/** + * Loads the input stream as a list of YAML documents. + * + * @throws {@link ParserException} if it is malformed. + */ +YAML_CPP_API std::vector LoadAll(std::istream& input); + +/** + * Loads the input file as a list of YAML documents. + * + * @throws {@link ParserException} if it is malformed. + * @throws {@link BadFile} if the file cannot be loaded. + */ +YAML_CPP_API std::vector LoadAllFromFile(const std::string& filename); +} // namespace YAML + +#endif // VALUE_PARSE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/node/ptr.h b/phonelibs/yaml-cpp/include/yaml-cpp/node/ptr.h new file mode 100644 index 0000000000..ce085dd5cd --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/node/ptr.h @@ -0,0 +1,29 @@ +#ifndef VALUE_PTR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define VALUE_PTR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include "yaml-cpp/dll.h" +#include + +namespace YAML { +namespace detail { +class node; +class node_ref; +class node_data; +class memory; +class memory_holder; + +typedef std::shared_ptr shared_node; +typedef std::shared_ptr shared_node_ref; +typedef std::shared_ptr shared_node_data; +typedef std::shared_ptr shared_memory_holder; +typedef std::shared_ptr shared_memory; +} +} + +#endif // VALUE_PTR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/node/type.h b/phonelibs/yaml-cpp/include/yaml-cpp/node/type.h new file mode 100644 index 0000000000..9d55ca9662 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/node/type.h @@ -0,0 +1,16 @@ +#ifndef VALUE_TYPE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define VALUE_TYPE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +namespace YAML { +struct NodeType { + enum value { Undefined, Null, Scalar, Sequence, Map }; +}; +} + +#endif // VALUE_TYPE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/noncopyable.h b/phonelibs/yaml-cpp/include/yaml-cpp/noncopyable.h new file mode 100644 index 0000000000..a261040739 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/noncopyable.h @@ -0,0 +1,25 @@ +#ifndef NONCOPYABLE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define NONCOPYABLE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include "yaml-cpp/dll.h" + +namespace YAML { +// this is basically boost::noncopyable +class YAML_CPP_API noncopyable { + protected: + noncopyable() {} + ~noncopyable() {} + + private: + noncopyable(const noncopyable&); + const noncopyable& operator=(const noncopyable&); +}; +} + +#endif // NONCOPYABLE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/null.h b/phonelibs/yaml-cpp/include/yaml-cpp/null.h new file mode 100644 index 0000000000..b9521d488a --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/null.h @@ -0,0 +1,26 @@ +#ifndef NULL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define NULL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include "yaml-cpp/dll.h" +#include + +namespace YAML { +class Node; + +struct YAML_CPP_API _Null {}; +inline bool operator==(const _Null&, const _Null&) { return true; } +inline bool operator!=(const _Null&, const _Null&) { return false; } + +YAML_CPP_API bool IsNull(const Node& node); // old API only +YAML_CPP_API bool IsNullString(const std::string& str); + +extern YAML_CPP_API _Null Null; +} + +#endif // NULL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/ostream_wrapper.h b/phonelibs/yaml-cpp/include/yaml-cpp/ostream_wrapper.h new file mode 100644 index 0000000000..09d45f39b7 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/ostream_wrapper.h @@ -0,0 +1,72 @@ +#ifndef OSTREAM_WRAPPER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define OSTREAM_WRAPPER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include +#include + +#include "yaml-cpp/dll.h" + +namespace YAML { +class YAML_CPP_API ostream_wrapper { + public: + ostream_wrapper(); + explicit ostream_wrapper(std::ostream& stream); + ~ostream_wrapper(); + + void write(const std::string& str); + void write(const char* str, std::size_t size); + + void set_comment() { m_comment = true; } + + const char* str() const { + if (m_pStream) { + return 0; + } else { + m_buffer[m_pos] = '\0'; + return &m_buffer[0]; + } + } + + std::size_t row() const { return m_row; } + std::size_t col() const { return m_col; } + std::size_t pos() const { return m_pos; } + bool comment() const { return m_comment; } + + private: + void update_pos(char ch); + + private: + mutable std::vector m_buffer; + std::ostream* const m_pStream; + + std::size_t m_pos; + std::size_t m_row, m_col; + bool m_comment; +}; + +template +inline ostream_wrapper& operator<<(ostream_wrapper& stream, + const char(&str)[N]) { + stream.write(str, N - 1); + return stream; +} + +inline ostream_wrapper& operator<<(ostream_wrapper& stream, + const std::string& str) { + stream.write(str); + return stream; +} + +inline ostream_wrapper& operator<<(ostream_wrapper& stream, char ch) { + stream.write(&ch, 1); + return stream; +} +} + +#endif // OSTREAM_WRAPPER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/parser.h b/phonelibs/yaml-cpp/include/yaml-cpp/parser.h new file mode 100644 index 0000000000..ceac22d026 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/parser.h @@ -0,0 +1,86 @@ +#ifndef PARSER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define PARSER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include +#include + +#include "yaml-cpp/dll.h" +#include "yaml-cpp/noncopyable.h" + +namespace YAML { +class EventHandler; +class Node; +class Scanner; +struct Directives; +struct Token; + +/** + * A parser turns a stream of bytes into one stream of "events" per YAML + * document in the input stream. + */ +class YAML_CPP_API Parser : private noncopyable { + public: + /** Constructs an empty parser (with no input. */ + Parser(); + + /** + * Constructs a parser from the given input stream. The input stream must + * live as long as the parser. + */ + explicit Parser(std::istream& in); + + ~Parser(); + + /** Evaluates to true if the parser has some valid input to be read. */ + explicit operator bool() const; + + /** + * Resets the parser with the given input stream. Any existing state is + * erased. + */ + void Load(std::istream& in); + + /** + * Handles the next document by calling events on the {@code eventHandler}. + * + * @throw a ParserException on error. + * @return false if there are no more documents + */ + bool HandleNextDocument(EventHandler& eventHandler); + + void PrintTokens(std::ostream& out); + + private: + /** + * Reads any directives that are next in the queue, setting the internal + * {@code m_pDirectives} state. + */ + void ParseDirectives(); + + void HandleDirective(const Token& token); + + /** + * Handles a "YAML" directive, which should be of the form 'major.minor' (like + * a version number). + */ + void HandleYamlDirective(const Token& token); + + /** + * Handles a "TAG" directive, which should be of the form 'handle prefix', + * where 'handle' is converted to 'prefix' in the file. + */ + void HandleTagDirective(const Token& token); + + private: + std::unique_ptr m_pScanner; + std::unique_ptr m_pDirectives; +}; +} + +#endif // PARSER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/stlemitter.h b/phonelibs/yaml-cpp/include/yaml-cpp/stlemitter.h new file mode 100644 index 0000000000..06780c861f --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/stlemitter.h @@ -0,0 +1,51 @@ +#ifndef STLEMITTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define STLEMITTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include +#include +#include +#include + +namespace YAML { +template +inline Emitter& EmitSeq(Emitter& emitter, const Seq& seq) { + emitter << BeginSeq; + for (typename Seq::const_iterator it = seq.begin(); it != seq.end(); ++it) + emitter << *it; + emitter << EndSeq; + return emitter; +} + +template +inline Emitter& operator<<(Emitter& emitter, const std::vector& v) { + return EmitSeq(emitter, v); +} + +template +inline Emitter& operator<<(Emitter& emitter, const std::list& v) { + return EmitSeq(emitter, v); +} + +template +inline Emitter& operator<<(Emitter& emitter, const std::set& v) { + return EmitSeq(emitter, v); +} + +template +inline Emitter& operator<<(Emitter& emitter, const std::map& m) { + typedef typename std::map map; + emitter << BeginMap; + for (typename map::const_iterator it = m.begin(); it != m.end(); ++it) + emitter << Key << it->first << Value << it->second; + emitter << EndMap; + return emitter; +} +} + +#endif // STLEMITTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/traits.h b/phonelibs/yaml-cpp/include/yaml-cpp/traits.h new file mode 100644 index 0000000000..f33d0e1f63 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/traits.h @@ -0,0 +1,103 @@ +#ifndef TRAITS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define TRAITS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +namespace YAML { +template +struct is_numeric { + enum { value = false }; +}; + +template <> +struct is_numeric { + enum { value = true }; +}; +template <> +struct is_numeric { + enum { value = true }; +}; +template <> +struct is_numeric { + enum { value = true }; +}; +template <> +struct is_numeric { + enum { value = true }; +}; +template <> +struct is_numeric { + enum { value = true }; +}; +template <> +struct is_numeric { + enum { value = true }; +}; +template <> +struct is_numeric { + enum { value = true }; +}; +template <> +struct is_numeric { + enum { value = true }; +}; +#if defined(_MSC_VER) && (_MSC_VER < 1310) +template <> +struct is_numeric<__int64> { + enum { value = true }; +}; +template <> +struct is_numeric { + enum { value = true }; +}; +#else +template <> +struct is_numeric { + enum { value = true }; +}; +template <> +struct is_numeric { + enum { value = true }; +}; +#endif +template <> +struct is_numeric { + enum { value = true }; +}; +template <> +struct is_numeric { + enum { value = true }; +}; +template <> +struct is_numeric { + enum { value = true }; +}; + +template +struct enable_if_c { + typedef T type; +}; + +template +struct enable_if_c {}; + +template +struct enable_if : public enable_if_c {}; + +template +struct disable_if_c { + typedef T type; +}; + +template +struct disable_if_c {}; + +template +struct disable_if : public disable_if_c {}; +} + +#endif // TRAITS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/include/yaml-cpp/yaml.h b/phonelibs/yaml-cpp/include/yaml-cpp/yaml.h new file mode 100644 index 0000000000..7f515efb96 --- /dev/null +++ b/phonelibs/yaml-cpp/include/yaml-cpp/yaml.h @@ -0,0 +1,24 @@ +#ifndef YAML_H_62B23520_7C8E_11DE_8A39_0800200C9A66 +#define YAML_H_62B23520_7C8E_11DE_8A39_0800200C9A66 + +#if defined(_MSC_VER) || \ + (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ + (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 +#pragma once +#endif + +#include "yaml-cpp/parser.h" +#include "yaml-cpp/emitter.h" +#include "yaml-cpp/emitterstyle.h" +#include "yaml-cpp/stlemitter.h" +#include "yaml-cpp/exceptions.h" + +#include "yaml-cpp/node/node.h" +#include "yaml-cpp/node/impl.h" +#include "yaml-cpp/node/convert.h" +#include "yaml-cpp/node/iterator.h" +#include "yaml-cpp/node/detail/impl.h" +#include "yaml-cpp/node/parse.h" +#include "yaml-cpp/node/emit.h" + +#endif // YAML_H_62B23520_7C8E_11DE_8A39_0800200C9A66 diff --git a/phonelibs/yaml-cpp/lib/libyaml-cpp.a b/phonelibs/yaml-cpp/lib/libyaml-cpp.a new file mode 100644 index 0000000000..c039175107 Binary files /dev/null and b/phonelibs/yaml-cpp/lib/libyaml-cpp.a differ diff --git a/phonelibs/zmq/aarch64-linux/bin/curve_keygen b/phonelibs/zmq/aarch64-linux/bin/curve_keygen deleted file mode 100755 index 3d76817f73..0000000000 Binary files a/phonelibs/zmq/aarch64-linux/bin/curve_keygen and /dev/null differ diff --git a/phonelibs/zmq/aarch64-linux/include/czmq.h b/phonelibs/zmq/aarch64-linux/include/czmq.h deleted file mode 100644 index dbf1fe5e40..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/czmq.h +++ /dev/null @@ -1,39 +0,0 @@ -/* ========================================================================= - CZMQ - a high-level binding in C for ZeroMQ - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= - - "Tell them I was a writer. - A maker of software. - A humanist. A father. - And many things. - But above all, a writer. - Thank You. :) - - Pieter Hintjens -*/ - -#ifndef __CZMQ_H_INCLUDED__ -#define __CZMQ_H_INCLUDED__ - -// These are signatures for handler functions that customize the -// behavior of CZMQ containers. These are shared between all CZMQ -// container types. - -// -- destroy an item -typedef void (czmq_destructor) (void **item); -// -- duplicate an item -typedef void *(czmq_duplicator) (const void *item); -// - compare two items, for sorting -typedef int (czmq_comparator) (const void *item1, const void *item2); - -// Include the project library file -#include "czmq_library.h" - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/czmq_library.h b/phonelibs/zmq/aarch64-linux/include/czmq_library.h deleted file mode 100644 index 89dc4eb917..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/czmq_library.h +++ /dev/null @@ -1,178 +0,0 @@ -/* ========================================================================= - czmq - generated layer of public API - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - -################################################################################ -# THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY # -# Read the zproject/README.md for information about making permanent changes. # -################################################################################ - ========================================================================= -*/ - -#ifndef CZMQ_LIBRARY_H_INCLUDED -#define CZMQ_LIBRARY_H_INCLUDED - -// Set up environment for the application -#include "czmq_prelude.h" - -// External dependencies -#include - -// CZMQ version macros for compile-time API detection -#define CZMQ_VERSION_MAJOR 4 -#define CZMQ_VERSION_MINOR 0 -#define CZMQ_VERSION_PATCH 2 - -#define CZMQ_MAKE_VERSION(major, minor, patch) \ - ((major) * 10000 + (minor) * 100 + (patch)) -#define CZMQ_VERSION \ - CZMQ_MAKE_VERSION(CZMQ_VERSION_MAJOR, CZMQ_VERSION_MINOR, CZMQ_VERSION_PATCH) - -#if defined (__WINDOWS__) -# if defined CZMQ_STATIC -# define CZMQ_EXPORT -# elif defined CZMQ_INTERNAL_BUILD -# if defined DLL_EXPORT -# define CZMQ_EXPORT __declspec(dllexport) -# else -# define CZMQ_EXPORT -# endif -# elif defined CZMQ_EXPORTS -# define CZMQ_EXPORT __declspec(dllexport) -# else -# define CZMQ_EXPORT __declspec(dllimport) -# endif -# define CZMQ_PRIVATE -#else -# define CZMQ_EXPORT -# if (defined __GNUC__ && __GNUC__ >= 4) || defined __INTEL_COMPILER -# define CZMQ_PRIVATE __attribute__ ((visibility ("hidden"))) -# else -# define CZMQ_PRIVATE -# endif -#endif - -// Opaque class structures to allow forward references -// These classes are stable or legacy and built in all releases -typedef struct _zactor_t zactor_t; -#define ZACTOR_T_DEFINED -typedef struct _zarmour_t zarmour_t; -#define ZARMOUR_T_DEFINED -typedef struct _zcert_t zcert_t; -#define ZCERT_T_DEFINED -typedef struct _zcertstore_t zcertstore_t; -#define ZCERTSTORE_T_DEFINED -typedef struct _zchunk_t zchunk_t; -#define ZCHUNK_T_DEFINED -typedef struct _zclock_t zclock_t; -#define ZCLOCK_T_DEFINED -typedef struct _zconfig_t zconfig_t; -#define ZCONFIG_T_DEFINED -typedef struct _zdigest_t zdigest_t; -#define ZDIGEST_T_DEFINED -typedef struct _zdir_t zdir_t; -#define ZDIR_T_DEFINED -typedef struct _zdir_patch_t zdir_patch_t; -#define ZDIR_PATCH_T_DEFINED -typedef struct _zfile_t zfile_t; -#define ZFILE_T_DEFINED -typedef struct _zframe_t zframe_t; -#define ZFRAME_T_DEFINED -typedef struct _zhash_t zhash_t; -#define ZHASH_T_DEFINED -typedef struct _zhashx_t zhashx_t; -#define ZHASHX_T_DEFINED -typedef struct _ziflist_t ziflist_t; -#define ZIFLIST_T_DEFINED -typedef struct _zlist_t zlist_t; -#define ZLIST_T_DEFINED -typedef struct _zlistx_t zlistx_t; -#define ZLISTX_T_DEFINED -typedef struct _zloop_t zloop_t; -#define ZLOOP_T_DEFINED -typedef struct _zmsg_t zmsg_t; -#define ZMSG_T_DEFINED -typedef struct _zpoller_t zpoller_t; -#define ZPOLLER_T_DEFINED -typedef struct _zsock_t zsock_t; -#define ZSOCK_T_DEFINED -typedef struct _zstr_t zstr_t; -#define ZSTR_T_DEFINED -typedef struct _zuuid_t zuuid_t; -#define ZUUID_T_DEFINED -typedef struct _zauth_t zauth_t; -#define ZAUTH_T_DEFINED -typedef struct _zbeacon_t zbeacon_t; -#define ZBEACON_T_DEFINED -typedef struct _zgossip_t zgossip_t; -#define ZGOSSIP_T_DEFINED -typedef struct _zmonitor_t zmonitor_t; -#define ZMONITOR_T_DEFINED -typedef struct _zproxy_t zproxy_t; -#define ZPROXY_T_DEFINED -typedef struct _zrex_t zrex_t; -#define ZREX_T_DEFINED -typedef struct _zsys_t zsys_t; -#define ZSYS_T_DEFINED -// Draft classes are by default not built in stable releases -#ifdef CZMQ_BUILD_DRAFT_API -typedef struct _zproc_t zproc_t; -#define ZPROC_T_DEFINED -typedef struct _ztimerset_t ztimerset_t; -#define ZTIMERSET_T_DEFINED -typedef struct _ztrie_t ztrie_t; -#define ZTRIE_T_DEFINED -#endif // CZMQ_BUILD_DRAFT_API - - -// Public classes, each with its own header file -#include "zactor.h" -#include "zarmour.h" -#include "zcert.h" -#include "zcertstore.h" -#include "zchunk.h" -#include "zclock.h" -#include "zconfig.h" -#include "zdigest.h" -#include "zdir.h" -#include "zdir_patch.h" -#include "zfile.h" -#include "zframe.h" -#include "zhash.h" -#include "zhashx.h" -#include "ziflist.h" -#include "zlist.h" -#include "zlistx.h" -#include "zloop.h" -#include "zmsg.h" -#include "zpoller.h" -#include "zsock.h" -#include "zstr.h" -#include "zuuid.h" -#include "zauth.h" -#include "zbeacon.h" -#include "zgossip.h" -#include "zmonitor.h" -#include "zproxy.h" -#include "zrex.h" -#include "zsys.h" -#ifdef CZMQ_BUILD_DRAFT_API -#include "zproc.h" -#include "ztimerset.h" -#include "ztrie.h" -#endif // CZMQ_BUILD_DRAFT_API - -#endif -/* -################################################################################ -# THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY # -# Read the zproject/README.md for information about making permanent changes. # -################################################################################ -*/ diff --git a/phonelibs/zmq/aarch64-linux/include/czmq_prelude.h b/phonelibs/zmq/aarch64-linux/include/czmq_prelude.h deleted file mode 100644 index 534f47023c..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/czmq_prelude.h +++ /dev/null @@ -1,647 +0,0 @@ -/* ========================================================================= - czmq_prelude.h - CZMQ environment - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __CZMQ_PRELUDE_H_INCLUDED__ -#define __CZMQ_PRELUDE_H_INCLUDED__ - -//- Establish the compiler and computer system ------------------------------ -/* - * Defines zero or more of these symbols, for use in any non-portable - * code: - * - * __WINDOWS__ Microsoft C/C++ with Windows calls - * __MSDOS__ System is MS-DOS (set if __WINDOWS__ set) - * __VMS__ System is VAX/VMS or Alpha/OpenVMS - * __UNIX__ System is UNIX - * __OS2__ System is OS/2 - * - * __IS_32BIT__ OS/compiler is 32 bits - * __IS_64BIT__ OS/compiler is 64 bits - * - * When __UNIX__ is defined, we also define exactly one of these: - * - * __UTYPE_AUX Apple AUX - * __UTYPE_BEOS BeOS - * __UTYPE_BSDOS BSD/OS - * __UTYPE_DECALPHA Digital UNIX (Alpha) - * __UTYPE_IBMAIX IBM RS/6000 AIX - * __UTYPE_FREEBSD FreeBSD - * __UTYPE_HPUX HP/UX - * __UTYPE_ANDROID Android - * __UTYPE_LINUX Linux - * __UTYPE_GNU GNU/Hurd - * __UTYPE_MIPS MIPS (BSD 4.3/System V mixture) - * __UTYPE_NETBSD NetBSD - * __UTYPE_NEXT NeXT - * __UTYPE_OPENBSD OpenBSD - * __UTYPE_OSX Apple Macintosh OS X - * __UTYPE_IOS Apple iOS - * __UTYPE_QNX QNX - * __UTYPE_IRIX Silicon Graphics IRIX - * __UTYPE_SINIX SINIX-N (Siemens-Nixdorf Unix) - * __UTYPE_SUNOS SunOS - * __UTYPE_SUNSOLARIS Sun Solaris - * __UTYPE_UNIXWARE SCO UnixWare - * ... these are the ones I know about so far. - * __UTYPE_GENERIC Any other UNIX - * - * When __VMS__ is defined, we may define one or more of these: - * - * __VMS_XOPEN Supports XOPEN functions - */ - -#if (defined (__64BIT__) || defined (__x86_64__)) -# define __IS_64BIT__ // May have 64-bit OS/compiler -#else -# define __IS_32BIT__ // Else assume 32-bit OS/compiler -#endif - -#if (defined WIN32 || defined _WIN32) -# undef __WINDOWS__ -# define __WINDOWS__ -# undef __MSDOS__ -# define __MSDOS__ -#endif - -#if (defined WINDOWS || defined _WINDOWS || defined __WINDOWS__) -# undef __WINDOWS__ -# define __WINDOWS__ -# undef __MSDOS__ -# define __MSDOS__ -// Stop cheeky warnings about "deprecated" functions like fopen -# if _MSC_VER >= 1500 -# undef _CRT_SECURE_NO_DEPRECATE -# define _CRT_SECURE_NO_DEPRECATE -# pragma warning(disable: 4996) -# endif -#endif - -// MSDOS Microsoft C -// _MSC_VER Microsoft C -#if (defined (MSDOS) || defined (_MSC_VER)) -# undef __MSDOS__ -# define __MSDOS__ -# if (defined (_DEBUG) && !defined (DEBUG)) -# define DEBUG -# endif -#endif - -#if (defined (__EMX__) && defined (__i386__)) -# undef __OS2__ -# define __OS2__ -#endif - -// VMS VAX C (VAX/VMS) -// __VMS Dec C (Alpha/OpenVMS) -// __vax__ gcc -#if (defined (VMS) || defined (__VMS) || defined (__vax__)) -# undef __VMS__ -# define __VMS__ -# if (__VMS_VER >= 70000000) -# define __VMS_XOPEN -# endif -#endif - -// Try to define a __UTYPE_xxx symbol... -// unix SunOS at least -// __unix__ gcc -// _POSIX_SOURCE is various UNIX systems, maybe also VAX/VMS -#if (defined (unix) || defined (__unix__) || defined (_POSIX_SOURCE)) -# if (!defined (__VMS__)) -# undef __UNIX__ -# define __UNIX__ -# if (defined (__alpha)) // Digital UNIX is 64-bit -# undef __IS_32BIT__ -# define __IS_64BIT__ -# define __UTYPE_DECALPHA -# endif -# endif -#endif - -#if (defined (_AUX)) -# define __UTYPE_AUX -# define __UNIX__ -#elif (defined (__BEOS__)) -# define __UTYPE_BEOS -# define __UNIX__ -#elif (defined (__hpux)) -# define __UTYPE_HPUX -# define __UNIX__ -# define _INCLUDE_HPUX_SOURCE -# define _INCLUDE_XOPEN_SOURCE -# define _INCLUDE_POSIX_SOURCE -#elif (defined (_AIX) || defined (AIX)) -# define __UTYPE_IBMAIX -# define __UNIX__ -#elif (defined (BSD) || defined (bsd)) -# define __UTYPE_BSDOS -# define __UNIX__ -#elif (defined (__ANDROID__)) -# define __UTYPE_ANDROID -# define __UNIX__ -#elif (defined (LINUX) || defined (linux) || defined (__linux__)) -# define __UTYPE_LINUX -# define __UNIX__ -# ifndef __NO_CTYPE -# define __NO_CTYPE // Suppress warnings on tolower() -# endif -# ifndef _DEFAULT_SOURCE -# define _DEFAULT_SOURCE // Include stuff from 4.3 BSD Unix -# endif -#elif (defined (__GNU__)) -# define __UTYPE_GNU -# define __UNIX__ -#elif (defined (Mips)) -# define __UTYPE_MIPS -# define __UNIX__ -#elif (defined (FreeBSD) || defined (__FreeBSD__)) -# define __UTYPE_FREEBSD -# define __UNIX__ -#elif (defined (NetBSD) || defined (__NetBSD__)) -# define __UTYPE_NETBSD -# define __UNIX__ -#elif (defined (OpenBSD) || defined (__OpenBSD__)) -# define __UTYPE_OPENBSD -# define __UNIX__ -#elif (defined (APPLE) || defined (__APPLE__)) -# include -# define __UNIX__ -# if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR -# define __UTYPE_IOS -# else -# define __UTYPE_OSX -# endif -#elif (defined (NeXT)) -# define __UTYPE_NEXT -# define __UNIX__ -#elif (defined (__QNX__)) -# define __UTYPE_QNX -# define __UNIX__ -#elif (defined (sgi)) -# define __UTYPE_IRIX -# define __UNIX__ -#elif (defined (sinix)) -# define __UTYPE_SINIX -# define __UNIX__ -#elif (defined (SOLARIS) || defined (__SVR4)) || defined (SVR4) -# define __UTYPE_SUNSOLARIS -# define __UNIX__ -#elif (defined (SUNOS) || defined (SUN) || defined (sun)) -# define __UTYPE_SUNOS -# define __UNIX__ -#elif (defined (__USLC__) || defined (UnixWare)) -# define __UTYPE_UNIXWARE -# define __UNIX__ -#elif (defined (__CYGWIN__)) -# define __UTYPE_CYGWIN -# define __UNIX__ -#elif (defined (__UNIX__)) -# define __UTYPE_GENERIC -#endif - -//- Always include ZeroMQ headers ------------------------------------------- - -#include "zmq.h" -#if (ZMQ_VERSION < ZMQ_MAKE_VERSION (4, 2, 0)) -# include "zmq_utils.h" -#endif - -//- Standard ANSI include files --------------------------------------------- - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -//- System-specific include files ------------------------------------------- - -#if (defined (__MSDOS__)) -# if (defined (__WINDOWS__)) -# if (_WIN32_WINNT < 0x0600) -# undef _WIN32_WINNT -# define _WIN32_WINNT 0x0600 -# endif -# if (!defined (FD_SETSIZE)) -# define FD_SETSIZE 1024 // Max. filehandles/sockets -# endif -# include -# include -# include -# include -# include // For getnameinfo () -# include // For GetAdaptersAddresses () -# endif -# include -# include -# include -# include -# include -# include -# include -# include -#endif - -#if (defined (__UNIX__)) -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include // Let CZMQ build with libzmq/3.x -# include // Must come before arpa/inet.h -# if (!defined (__UTYPE_ANDROID)) && (!defined (__UTYPE_IBMAIX)) \ - && (!defined (__UTYPE_HPUX)) -# include -# endif -# if defined (__UTYPE_SUNSOLARIS) || defined (__UTYPE_SUNOS) -# include -# endif -# if (!defined (__UTYPE_BEOS)) -# include -# if (!defined (TCP_NODELAY)) -# include -# endif -# endif -# if (defined (__UTYPE_IBMAIX) || defined(__UTYPE_QNX)) -# include -# endif -# if (defined (__UTYPE_BEOS)) -# include -# endif -# if ((defined (_XOPEN_REALTIME) && (_XOPEN_REALTIME >= 1)) \ - || (defined (_POSIX_VERSION) && (_POSIX_VERSION >= 199309L))) -# include -# endif -# if (defined (__UTYPE_OSX) || defined (__UTYPE_IOS)) -# include -# include // For monotonic clocks -# endif -# if (defined (__UTYPE_OSX)) -# include // For _NSGetEnviron() -# endif -# if (defined (__UTYPE_ANDROID)) -# include -# endif -# if (defined (__UTYPE_LINUX) && defined (HAVE_LIBSYSTEMD)) -# include -# endif -#endif - -#if (defined (__VMS__)) -# if (!defined (vaxc)) -# include // Not provided by Vax C -# endif -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -#endif - -#if (defined (__OS2__)) -# include // Required near top -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include // Must come before arpa/inet.h -# include -# include -# if (!defined (TCP_NODELAY)) -# include -# endif -#endif - -// Add missing defines for non-POSIX systems -#ifndef S_IRUSR -# define S_IRUSR S_IREAD -#endif -#ifndef S_IWUSR -# define S_IWUSR S_IWRITE -#endif -#ifndef S_ISDIR -# define S_ISDIR(m) (((m) & S_IFDIR) != 0) -#endif -#ifndef S_ISREG -# define S_ISREG(m) (((m) & S_IFREG) != 0) -#endif - - -//- Check compiler data type sizes ------------------------------------------ - -#if (UCHAR_MAX != 0xFF) -# error "Cannot compile: must change definition of 'byte'." -#endif -#if (USHRT_MAX != 0xFFFFU) -# error "Cannot compile: must change definition of 'dbyte'." -#endif -#if (UINT_MAX != 0xFFFFFFFFU) -# error "Cannot compile: must change definition of 'qbyte'." -#endif - -//- Data types -------------------------------------------------------------- - -typedef unsigned char byte; // Single unsigned byte = 8 bits -typedef unsigned short dbyte; // Double byte = 16 bits -typedef unsigned int qbyte; // Quad byte = 32 bits -typedef struct sockaddr_in inaddr_t; // Internet socket address structure -typedef struct sockaddr_in6 in6addr_t; // Internet 6 socket address structure - -// Common structure to hold inaddr_t and in6addr_t with length -typedef struct { - union { - inaddr_t __addr; // IPv4 address - in6addr_t __addr6; // IPv6 address - } __inaddr_u; -#define ipv4addr __inaddr_u.__addr -#define ipv6addr __inaddr_u.__addr6 - int inaddrlen; -} inaddr_storage_t; - -//- Inevitable macros ------------------------------------------------------- - -#define streq(s1,s2) (!strcmp ((s1), (s2))) -#define strneq(s1,s2) (strcmp ((s1), (s2))) - -// Provide random number from 0..(num-1) -// Note that (at least in Solaris) while rand() returns an int limited by -// RAND_MAX, random() returns a 32-bit value all filled with random bits. -#if (defined (__WINDOWS__)) || (defined (__UTYPE_IBMAIX)) \ - || (defined (__UTYPE_HPUX)) || (defined (__UTYPE_SUNOS)) || (defined (__UTYPE_SOLARIS)) -# define randof(num) (int) ((float) (num) * rand () / (RAND_MAX + 1.0)) -#else -# if defined(RAND_MAX) -# define randof(num) (int) ((float) (num) * (random () % RAND_MAX) / (RAND_MAX + 1.0)) -# else -# define randof(num) (int) ((float) (num) * (uint32_t)random () / (UINT32_MAX + 1.0)) -# endif -#endif - -// Windows MSVS doesn't have stdbool -#if (defined (_MSC_VER)) -# if (!defined (__cplusplus) && (!defined (true))) -# define true 1 -# define false 0 - typedef char bool; -# endif -#else -# include -#endif - -//- A number of POSIX and C99 keywords and data types ----------------------- -// CZMQ uses uint for array indices; equivalent to unsigned int, but more -// convenient in code. We define it in czmq_prelude.h on systems that do -// not define it by default. - -#if (defined (__WINDOWS__)) -# if (!defined (__cplusplus) && (!defined (inline))) -# define inline __inline -# endif -# define strtoull _strtoui64 -# define atoll _atoi64 -# define srandom srand -# define TIMEZONE _timezone -# if (!defined (__MINGW32__)) -# define snprintf _snprintf -# define vsnprintf _vsnprintf -# endif - typedef unsigned long ulong; - typedef unsigned int uint; -# if (!defined (__MINGW32__)) - typedef int mode_t; -# if !defined (_SSIZE_T_DEFINED) -typedef intptr_t ssize_t; -# define _SSIZE_T_DEFINED -# endif -# endif -# if ((!defined (__MINGW32__) \ - || (defined (__MINGW32__) && defined (__IS_64BIT__))) \ - && !defined (ZMQ_DEFINED_STDINT)) - typedef __int8 int8_t; - typedef __int16 int16_t; - typedef __int32 int32_t; - typedef __int64 int64_t; - typedef unsigned __int8 uint8_t; - typedef unsigned __int16 uint16_t; - typedef unsigned __int32 uint32_t; - typedef unsigned __int64 uint64_t; -# endif - typedef uint32_t in_addr_t; -# if (!defined (PRId8)) -# define PRId8 "d" -# endif -# if (!defined (PRId16)) -# define PRId16 "d" -# endif -# if (!defined (PRId32)) -# define PRId32 "d" -# endif -# if (!defined (PRId64)) -# define PRId64 "I64d" -# endif -# if (!defined (PRIu8)) -# define PRIu8 "u" -# endif -# if (!defined (PRIu16)) -# define PRIu16 "u" -# endif -# if (!defined (PRIu32)) -# define PRIu32 "u" -# endif -# if (!defined (PRIu64)) -# define PRIu64 "I64u" -# endif -# if (!defined (va_copy)) - // MSVC does not support C99's va_copy so we use a regular assignment -# define va_copy(dest,src) (dest) = (src) -# endif -#elif (defined (__UTYPE_OSX)) - typedef unsigned long ulong; - typedef unsigned int uint; - // This fixes header-order dependence problem with some Linux versions -#elif (defined (__UTYPE_LINUX)) -# if (__STDC_VERSION__ >= 199901L && !defined (__USE_MISC)) - typedef unsigned int uint; -# endif -#endif - -//- Non-portable declaration specifiers ------------------------------------- - -// For thread-local storage -#if defined (__WINDOWS__) -# define CZMQ_THREADLS __declspec(thread) -#else -# define CZMQ_THREADLS __thread -#endif - -// Replacement for malloc() which asserts if we run out of heap, and -// which zeroes the allocated block. -static inline void * -safe_malloc (size_t size, const char *file, unsigned line) -{ -// printf ("%s:%u %08d\n", file, line, (int) size); - void *mem = calloc (1, size); - if (mem == NULL) { - fprintf (stderr, "FATAL ERROR at %s:%u\n", file, line); - fprintf (stderr, "OUT OF MEMORY (malloc returned NULL)\n"); - fflush (stderr); - abort (); - } - return mem; -} - -// Define _ZMALLOC_DEBUG if you need to trace memory leaks using e.g. mtrace, -// otherwise all allocations will claim to come from czmq_prelude.h. For best -// results, compile all classes so you see dangling object allocations. -// _ZMALLOC_PEDANTIC does the same thing, but its intention is to propagate -// out of memory condition back up the call stack. -#if defined (_ZMALLOC_DEBUG) || defined (_ZMALLOC_PEDANTIC) -# define zmalloc(size) calloc(1,(size)) -#else -# define zmalloc(size) safe_malloc((size), __FILE__, __LINE__) -#endif - -// GCC supports validating format strings for functions that act like printf -#if defined (__GNUC__) && (__GNUC__ >= 2) -# define CHECK_PRINTF(a) __attribute__((format (printf, a, a + 1))) -#else -# define CHECK_PRINTF(a) -#endif - -// Lets us write code that compiles both on Windows and normal platforms -#if !defined (__WINDOWS__) -typedef int SOCKET; -# define closesocket close -# define INVALID_SOCKET -1 -# define SOCKET_ERROR -1 -# define O_BINARY 0 -#endif - -//- Include non-portable header files based on platform.h ------------------- - -#if defined (HAVE_LINUX_WIRELESS_H) -# include -// This would normally come from net/if.h -unsigned int if_nametoindex (const char *ifname); -#else -# if defined (HAVE_NET_IF_H) -# include -# endif -# if defined (HAVE_NET_IF_MEDIA_H) -# include -# endif -#endif - -#if defined (__WINDOWS__) && !defined (HAVE_UUID) -# define HAVE_UUID 1 -#endif -#if defined (__UTYPE_OSX) && !defined (HAVE_UUID) -# define HAVE_UUID 1 -#endif -#if defined (HAVE_UUID) -# if defined (__UTYPE_FREEBSD) || defined (__UTYPE_NETBSD) -# include -# elif defined __UTYPE_HPUX -# include -# elif defined (__UNIX__) -# include -# endif -#endif - -// ZMQ compatibility macros - -#if ZMQ_VERSION_MAJOR == 4 -# define ZMQ_POLL_MSEC 1 // zmq_poll is msec - -#elif ZMQ_VERSION_MAJOR == 3 -# define ZMQ_POLL_MSEC 1 // zmq_poll is msec -# if ZMQ_VERSION_MINOR < 2 -# define zmq_ctx_new zmq_init -# endif -# define zmq_ctx_term zmq_term - -#elif ZMQ_VERSION_MAJOR == 2 -# define ZMQ_POLL_MSEC 1000 // zmq_poll is usec -# define zmq_sendmsg zmq_send // Smooth out 2.x changes -# define zmq_recvmsg zmq_recv -# define zmq_ctx_new zmq_init -# define zmq_ctx_term zmq_term -# define zmq_msg_send(m,s,f) zmq_sendmsg ((s),(m),(f)) -# define zmq_msg_recv(m,s,f) zmq_recvmsg ((s),(m),(f)) - // Older libzmq APIs may be missing some aspects of libzmq v3.0 -# ifndef ZMQ_ROUTER -# define ZMQ_ROUTER ZMQ_XREP -# endif -# ifndef ZMQ_DEALER -# define ZMQ_DEALER ZMQ_XREQ -# endif -# ifndef ZMQ_DONTWAIT -# define ZMQ_DONTWAIT ZMQ_NOBLOCK -# endif -# ifndef ZMQ_XSUB -# error "please upgrade your libzmq from http://zeromq.org" -# endif -# if ZMQ_VERSION_MINOR == 0 \ - || (ZMQ_VERSION_MINOR == 1 && ZMQ_VERSION_PATCH < 7) -# error "CZMQ requires at least libzmq/2.1.7 stable" -# endif -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zactor.h b/phonelibs/zmq/aarch64-linux/include/zactor.h deleted file mode 100644 index c865c65daf..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zactor.h +++ /dev/null @@ -1,76 +0,0 @@ -/* ========================================================================= - zactor - actor - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZACTOR_H_INCLUDED__ -#define __ZACTOR_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zactor.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Actors get a pipe and arguments from caller -typedef void (zactor_fn) ( - zsock_t *pipe, void *args); - -// Create a new actor passing arbitrary arguments reference. -CZMQ_EXPORT zactor_t * - zactor_new (zactor_fn task, void *args); - -// Destroy an actor. -CZMQ_EXPORT void - zactor_destroy (zactor_t **self_p); - -// Send a zmsg message to the actor, take ownership of the message -// and destroy when it has been sent. -CZMQ_EXPORT int - zactor_send (zactor_t *self, zmsg_t **msg_p); - -// Receive a zmsg message from the actor. Returns NULL if the actor -// was interrupted before the message could be received, or if there -// was a timeout on the actor. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zmsg_t * - zactor_recv (zactor_t *self); - -// Probe the supplied object, and report if it looks like a zactor_t. -CZMQ_EXPORT bool - zactor_is (void *self); - -// Probe the supplied reference. If it looks like a zactor_t instance, -// return the underlying libzmq actor handle; else if it looks like -// a libzmq actor handle, return the supplied value. -CZMQ_EXPORT void * - zactor_resolve (void *self); - -// Return the actor's zsock handle. Use this when you absolutely need -// to work with the zsock instance rather than the actor. -CZMQ_EXPORT zsock_t * - zactor_sock (zactor_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zactor_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zarmour.h b/phonelibs/zmq/aarch64-linux/include/zarmour.h deleted file mode 100644 index c7f299f7af..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zarmour.h +++ /dev/null @@ -1,114 +0,0 @@ -/* ========================================================================= - zarmour - armoured text encoding and decoding - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZARMOUR_H_INCLUDED__ -#define __ZARMOUR_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zarmour.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -#define ZARMOUR_MODE_BASE64_STD 0 // Standard base 64 -#define ZARMOUR_MODE_BASE64_URL 1 // URL and filename friendly base 64 -#define ZARMOUR_MODE_BASE32_STD 2 // Standard base 32 -#define ZARMOUR_MODE_BASE32_HEX 3 // Extended hex base 32 -#define ZARMOUR_MODE_BASE16 4 // Standard base 16 -#define ZARMOUR_MODE_Z85 5 // Z85 from ZeroMQ RFC 32 - -// Create a new zarmour -CZMQ_EXPORT zarmour_t * - zarmour_new (void); - -// Destroy the zarmour -CZMQ_EXPORT void - zarmour_destroy (zarmour_t **self_p); - -// Encode a stream of bytes into an armoured string. Returns the armoured -// string, or NULL if there was insufficient memory available to allocate -// a new string. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zarmour_encode (zarmour_t *self, const byte *data, size_t size); - -// Decode an armoured string into a chunk. The decoded output is -// null-terminated, so it may be treated as a string, if that's what -// it was prior to encoding. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zchunk_t * - zarmour_decode (zarmour_t *self, const char *data); - -// Get the mode property. -CZMQ_EXPORT int - zarmour_mode (zarmour_t *self); - -// Get printable string for mode. -CZMQ_EXPORT const char * - zarmour_mode_str (zarmour_t *self); - -// Set the mode property. -CZMQ_EXPORT void - zarmour_set_mode (zarmour_t *self, int mode); - -// Return true if padding is turned on. -CZMQ_EXPORT bool - zarmour_pad (zarmour_t *self); - -// Turn padding on or off. Default is on. -CZMQ_EXPORT void - zarmour_set_pad (zarmour_t *self, bool pad); - -// Get the padding character. -CZMQ_EXPORT char - zarmour_pad_char (zarmour_t *self); - -// Set the padding character. -CZMQ_EXPORT void - zarmour_set_pad_char (zarmour_t *self, char pad_char); - -// Return if splitting output into lines is turned on. Default is off. -CZMQ_EXPORT bool - zarmour_line_breaks (zarmour_t *self); - -// Turn splitting output into lines on or off. -CZMQ_EXPORT void - zarmour_set_line_breaks (zarmour_t *self, bool line_breaks); - -// Get the line length used for splitting lines. -CZMQ_EXPORT size_t - zarmour_line_length (zarmour_t *self); - -// Set the line length used for splitting lines. -CZMQ_EXPORT void - zarmour_set_line_length (zarmour_t *self, size_t line_length); - -// Print properties of object -CZMQ_EXPORT void - zarmour_print (zarmour_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zarmour_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zauth.h b/phonelibs/zmq/aarch64-linux/include/zauth.h deleted file mode 100644 index 3e0e59ecab..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zauth.h +++ /dev/null @@ -1,100 +0,0 @@ -/* ========================================================================= - zauth - authentication for ZeroMQ security mechanisms - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZAUTH_H_INCLUDED__ -#define __ZAUTH_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -#define CURVE_ALLOW_ANY "*" - -// CZMQ v3 API (for use with zsock, not zsocket, which is deprecated). -// -// Create new zauth actor instance. This installs authentication on all -// zsock sockets. Until you add policies, all incoming NULL connections are -// allowed (classic ZeroMQ behaviour), and all PLAIN and CURVE connections -// are denied: -// -// zactor_t *auth = zactor_new (zauth, NULL); -// -// Destroy zauth instance. This removes authentication and allows all -// connections to pass, without authentication: -// -// zactor_destroy (&auth); -// -// Note that all zauth commands are synchronous, so your application always -// waits for a signal from the actor after each command. -// -// Enable verbose logging of commands and activity. Verbose logging can help -// debug non-trivial authentication policies: -// -// zstr_send (auth, "VERBOSE"); -// zsock_wait (auth); -// -// Allow (whitelist) a list of IP addresses. For NULL, all clients from -// these addresses will be accepted. For PLAIN and CURVE, they will be -// allowed to continue with authentication. You can call this method -// multiple times to whitelist more IP addresses. If you whitelist one -// or more addresses, any non-whitelisted addresses are treated as -// blacklisted: -// -// zstr_sendx (auth, "ALLOW", "127.0.0.1", "127.0.0.2", NULL); -// zsock_wait (auth); -// -// Deny (blacklist) a list of IP addresses. For all security mechanisms, -// this rejects the connection without any further authentication. Use -// either a whitelist, or a blacklist, not not both. If you define both -// a whitelist and a blacklist, only the whitelist takes effect: -// -// zstr_sendx (auth, "DENY", "192.168.0.1", "192.168.0.2", NULL); -// zsock_wait (auth); -// -// Configure PLAIN authentication using a plain-text password file. You can -// modify the password file at any time; zauth will reload it automatically -// if modified externally: -// -// zstr_sendx (auth, "PLAIN", filename, NULL); -// zsock_wait (auth); -// -// Configure CURVE authentication, using a directory that holds all public -// client certificates, i.e. their public keys. The certificates must be in -// zcert_save format. You can add and remove certificates in that directory -// at any time. To allow all client keys without checking, specify -// CURVE_ALLOW_ANY for the directory name: -// -// zstr_sendx (auth, "CURVE", directory, NULL); -// zsock_wait (auth); -// -// Configure GSSAPI authentication, using an underlying mechanism (usually -// Kerberos) to establish a secure context and perform mutual authentication: -// -// zstr_sendx (auth, "GSSAPI", NULL); -// zsock_wait (auth); -// -// This is the zauth constructor as a zactor_fn: -CZMQ_EXPORT void - zauth (zsock_t *pipe, void *certstore); - -// Selftest -CZMQ_EXPORT void - zauth_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zbeacon.h b/phonelibs/zmq/aarch64-linux/include/zbeacon.h deleted file mode 100644 index 78917e9577..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zbeacon.h +++ /dev/null @@ -1,86 +0,0 @@ -/* ========================================================================= - zbeacon - LAN discovery and presence - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZBEACON_H_INCLUDED__ -#define __ZBEACON_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// Create new zbeacon actor instance: -// -// zactor_t *beacon = zactor_new (zbeacon, NULL); -// -// Destroy zbeacon instance: -// -// zactor_destroy (&beacon); -// -// Enable verbose logging of commands and activity: -// -// zstr_send (beacon, "VERBOSE"); -// -// Configure beacon to run on specified UDP port, and return the name of -// the host, which can be used as endpoint for incoming connections. To -// force the beacon to operate on a given interface, set the environment -// variable ZSYS_INTERFACE, or call zsys_set_interface() before creating -// the beacon. If the system does not support UDP broadcasts (lacking a -// workable interface), returns an empty hostname: -// -// // Pictures: 's' = C string, 'i' = int -// zsock_send (beacon, "si", "CONFIGURE", port_number); -// char *hostname = zstr_recv (beacon); -// -// Start broadcasting a beacon at a specified interval in msec. The beacon -// data can be at most UDP_FRAME_MAX bytes; this constant is defined in -// zsys.h to be 255: -// -// // Pictures: 'b' = byte * data + size_t size -// zsock_send (beacon, "sbi", "PUBLISH", data, size, interval); -// -// Stop broadcasting the beacon: -// -// zstr_sendx (beacon, "SILENCE", NULL); -// -// Start listening to beacons from peers. The filter is used to do a prefix -// match on received beacons, to remove junk. Note that any received data -// that is identical to our broadcast beacon_data is discarded in any case. -// If the filter size is zero, we get all peer beacons: -// -// zsock_send (beacon, "sb", "SUBSCRIBE", filter_data, filter_size); -// -// Stop listening to other peers -// -// zstr_sendx (beacon, "UNSUBSCRIBE", NULL); -// -// Receive next beacon from a peer. Received beacons are always a 2-frame -// message containing the ipaddress of the sender, and then the binary -// beacon data as published by the sender: -// -// zmsg_t *msg = zmsg_recv (beacon); -// -// This is the zbeacon constructor as a zactor_fn: -CZMQ_EXPORT void - zbeacon (zsock_t *pipe, void *unused); - -// Self test of this class -CZMQ_EXPORT void - zbeacon_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zcert.h b/phonelibs/zmq/aarch64-linux/include/zcert.h deleted file mode 100644 index 3161bc0596..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zcert.h +++ /dev/null @@ -1,128 +0,0 @@ -/* ========================================================================= - zcert - work with CURVE security certificates - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZCERT_H_INCLUDED__ -#define __ZCERT_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zcert.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// Create and initialize a new certificate in memory -CZMQ_EXPORT zcert_t * - zcert_new (void); - -// Accepts public/secret key pair from caller -CZMQ_EXPORT zcert_t * - zcert_new_from (const byte *public_key, const byte *secret_key); - -// Load certificate from file -CZMQ_EXPORT zcert_t * - zcert_load (const char *filename); - -// Destroy a certificate in memory -CZMQ_EXPORT void - zcert_destroy (zcert_t **self_p); - -// Return public part of key pair as 32-byte binary string -CZMQ_EXPORT const byte * - zcert_public_key (zcert_t *self); - -// Return secret part of key pair as 32-byte binary string -CZMQ_EXPORT const byte * - zcert_secret_key (zcert_t *self); - -// Return public part of key pair as Z85 armored string -CZMQ_EXPORT const char * - zcert_public_txt (zcert_t *self); - -// Return secret part of key pair as Z85 armored string -CZMQ_EXPORT const char * - zcert_secret_txt (zcert_t *self); - -// Set certificate metadata from formatted string. -CZMQ_EXPORT void - zcert_set_meta (zcert_t *self, const char *name, const char *format, ...) CHECK_PRINTF (3); - -// Get metadata value from certificate; if the metadata value doesn't -// exist, returns NULL. -CZMQ_EXPORT const char * - zcert_meta (zcert_t *self, const char *name); - -// Get list of metadata fields from certificate. Caller is responsible for -// destroying list. Caller should not modify the values of list items. -CZMQ_EXPORT zlist_t * - zcert_meta_keys (zcert_t *self); - -// Save full certificate (public + secret) to file for persistent storage -// This creates one public file and one secret file (filename + "_secret"). -CZMQ_EXPORT int - zcert_save (zcert_t *self, const char *filename); - -// Save public certificate only to file for persistent storage -CZMQ_EXPORT int - zcert_save_public (zcert_t *self, const char *filename); - -// Save secret certificate only to file for persistent storage -CZMQ_EXPORT int - zcert_save_secret (zcert_t *self, const char *filename); - -// Apply certificate to socket, i.e. use for CURVE security on socket. -// If certificate was loaded from public file, the secret key will be -// undefined, and this certificate will not work successfully. -CZMQ_EXPORT void - zcert_apply (zcert_t *self, void *socket); - -// Return copy of certificate; if certificate is NULL or we exhausted -// heap memory, returns NULL. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zcert_t * - zcert_dup (zcert_t *self); - -// Return true if two certificates have the same keys -CZMQ_EXPORT bool - zcert_eq (zcert_t *self, zcert_t *compare); - -// Print certificate contents to stdout -CZMQ_EXPORT void - zcert_print (zcert_t *self); - -// Self test of this class -CZMQ_EXPORT void - zcert_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Unset certificate metadata. -CZMQ_EXPORT void - zcert_unset_meta (zcert_t *self, const char *name); - -#endif // CZMQ_BUILD_DRAFT_API -// @end - - -#ifdef __cplusplus -} -#endif - -// Deprecated method aliases -#define zcert_dump(s) zcert_print(s) - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zcertstore.h b/phonelibs/zmq/aarch64-linux/include/zcertstore.h deleted file mode 100644 index 689b228ac1..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zcertstore.h +++ /dev/null @@ -1,92 +0,0 @@ -/* ========================================================================= - zcertstore - work with CURVE security certificate stores - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZCERTSTORE_H_INCLUDED__ -#define __ZCERTSTORE_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zcertstore.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// Create a new certificate store from a disk directory, loading and -// indexing all certificates in that location. The directory itself may be -// absent, and created later, or modified at any time. The certificate store -// is automatically refreshed on any zcertstore_lookup() call. If the -// location is specified as NULL, creates a pure-memory store, which you -// can work with by inserting certificates at runtime. -CZMQ_EXPORT zcertstore_t * - zcertstore_new (const char *location); - -// Destroy a certificate store object in memory. Does not affect anything -// stored on disk. -CZMQ_EXPORT void - zcertstore_destroy (zcertstore_t **self_p); - -// Look up certificate by public key, returns zcert_t object if found, -// else returns NULL. The public key is provided in Z85 text format. -CZMQ_EXPORT zcert_t * - zcertstore_lookup (zcertstore_t *self, const char *public_key); - -// Insert certificate into certificate store in memory. Note that this -// does not save the certificate to disk. To do that, use zcert_save() -// directly on the certificate. Takes ownership of zcert_t object. -CZMQ_EXPORT void - zcertstore_insert (zcertstore_t *self, zcert_t **cert_p); - -// Print list of certificates in store to logging facility -CZMQ_EXPORT void - zcertstore_print (zcertstore_t *self); - -// Self test of this class -CZMQ_EXPORT void - zcertstore_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// Loaders retrieve certificates from an arbitrary source. -typedef void (zcertstore_loader) ( - zcertstore_t *self); - -// Destructor for loader state. -typedef void (zcertstore_destructor) ( - void **self_p); - -// *** Draft method, for development use, may change without warning *** -// Override the default disk loader with a custom loader fn. -CZMQ_EXPORT void - zcertstore_set_loader (zcertstore_t *self, zcertstore_loader loader, zcertstore_destructor destructor, void *state); - -// *** Draft method, for development use, may change without warning *** -// Empty certificate hashtable. This wrapper exists to be friendly to bindings, -// which don't usually have access to struct internals. -CZMQ_EXPORT void - zcertstore_empty (zcertstore_t *self); - -#endif // CZMQ_BUILD_DRAFT_API -// @end - - -#ifdef __cplusplus -} -#endif - -// Deprecated method aliases -#define zcertstore_dump(s) zcertstore_print(s) - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zchunk.h b/phonelibs/zmq/aarch64-linux/include/zchunk.h deleted file mode 100644 index 56f29b161a..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zchunk.h +++ /dev/null @@ -1,163 +0,0 @@ -/* ========================================================================= - zchunk - work with memory chunks - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZCHUNK_H_INCLUDED__ -#define __ZCHUNK_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zchunk.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Create a new chunk of the specified size. If you specify the data, it -// is copied into the chunk. If you do not specify the data, the chunk is -// allocated and left empty, and you can then add data using zchunk_append. -CZMQ_EXPORT zchunk_t * - zchunk_new (const void *data, size_t size); - -// Destroy a chunk -CZMQ_EXPORT void - zchunk_destroy (zchunk_t **self_p); - -// Resizes chunk max_size as requested; chunk_cur size is set to zero -CZMQ_EXPORT void - zchunk_resize (zchunk_t *self, size_t size); - -// Return chunk cur size -CZMQ_EXPORT size_t - zchunk_size (zchunk_t *self); - -// Return chunk max size -CZMQ_EXPORT size_t - zchunk_max_size (zchunk_t *self); - -// Return chunk data -CZMQ_EXPORT byte * - zchunk_data (zchunk_t *self); - -// Set chunk data from user-supplied data; truncate if too large. Data may -// be null. Returns actual size of chunk -CZMQ_EXPORT size_t - zchunk_set (zchunk_t *self, const void *data, size_t size); - -// Fill chunk data from user-supplied octet -CZMQ_EXPORT size_t - zchunk_fill (zchunk_t *self, byte filler, size_t size); - -// Append user-supplied data to chunk, return resulting chunk size. If the -// data would exceeded the available space, it is truncated. If you want to -// grow the chunk to accommodate new data, use the zchunk_extend method. -CZMQ_EXPORT size_t - zchunk_append (zchunk_t *self, const void *data, size_t size); - -// Append user-supplied data to chunk, return resulting chunk size. If the -// data would exceeded the available space, the chunk grows in size. -CZMQ_EXPORT size_t - zchunk_extend (zchunk_t *self, const void *data, size_t size); - -// Copy as much data from 'source' into the chunk as possible; returns the -// new size of chunk. If all data from 'source' is used, returns exhausted -// on the source chunk. Source can be consumed as many times as needed until -// it is exhausted. If source was already exhausted, does not change chunk. -CZMQ_EXPORT size_t - zchunk_consume (zchunk_t *self, zchunk_t *source); - -// Returns true if the chunk was exhausted by consume methods, or if the -// chunk has a size of zero. -CZMQ_EXPORT bool - zchunk_exhausted (zchunk_t *self); - -// Read chunk from an open file descriptor -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zchunk_t * - zchunk_read (FILE *handle, size_t bytes); - -// Write chunk to an open file descriptor -CZMQ_EXPORT int - zchunk_write (zchunk_t *self, FILE *handle); - -// Try to slurp an entire file into a chunk. Will read up to maxsize of -// the file. If maxsize is 0, will attempt to read the entire file and -// fail with an assertion if that cannot fit into memory. Returns a new -// chunk containing the file data, or NULL if the file could not be read. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zchunk_t * - zchunk_slurp (const char *filename, size_t maxsize); - -// Create copy of chunk, as new chunk object. Returns a fresh zchunk_t -// object, or null if there was not enough heap memory. If chunk is null, -// returns null. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zchunk_t * - zchunk_dup (zchunk_t *self); - -// Return chunk data encoded as printable hex string. Caller must free -// string when finished with it. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zchunk_strhex (zchunk_t *self); - -// Return chunk data copied into freshly allocated string -// Caller must free string when finished with it. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zchunk_strdup (zchunk_t *self); - -// Return TRUE if chunk body is equal to string, excluding terminator -CZMQ_EXPORT bool - zchunk_streq (zchunk_t *self, const char *string); - -// Transform zchunk into a zframe that can be sent in a message. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zchunk_pack (zchunk_t *self); - -// Transform a zframe into a zchunk. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zchunk_t * - zchunk_unpack (zframe_t *frame); - -// Calculate SHA1 digest for chunk, using zdigest class. -CZMQ_EXPORT const char * - zchunk_digest (zchunk_t *self); - -// Dump chunk to FILE stream, for debugging and tracing. -CZMQ_EXPORT void - zchunk_fprint (zchunk_t *self, FILE *file); - -// Dump message to stderr, for debugging and tracing. -// See zchunk_fprint for details -CZMQ_EXPORT void - zchunk_print (zchunk_t *self); - -// Probe the supplied object, and report if it looks like a zchunk_t. -CZMQ_EXPORT bool - zchunk_is (void *self); - -// Self test of this class. -CZMQ_EXPORT void - zchunk_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/phonelibs/zmq/aarch64-linux/include/zclock.h b/phonelibs/zmq/aarch64-linux/include/zclock.h deleted file mode 100644 index eb064162c4..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zclock.h +++ /dev/null @@ -1,73 +0,0 @@ -/* ========================================================================= - zclock - millisecond clocks and delays - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZCLOCK_H_INCLUDED__ -#define __ZCLOCK_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zclock.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Sleep for a number of milliseconds -CZMQ_EXPORT void - zclock_sleep (int msecs); - -// Return current system clock as milliseconds. Note that this clock can -// jump backwards (if the system clock is changed) so is unsafe to use for -// timers and time offsets. Use zclock_mono for that instead. -CZMQ_EXPORT int64_t - zclock_time (void); - -// Return current monotonic clock in milliseconds. Use this when you compute -// time offsets. The monotonic clock is not affected by system changes and -// so will never be reset backwards, unlike a system clock. -CZMQ_EXPORT int64_t - zclock_mono (void); - -// Return current monotonic clock in microseconds. Use this when you compute -// time offsets. The monotonic clock is not affected by system changes and -// so will never be reset backwards, unlike a system clock. -CZMQ_EXPORT int64_t - zclock_usecs (void); - -// Return formatted date/time as fresh string. Free using zstr_free(). -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zclock_timestr (void); - -// Self test of this class. -CZMQ_EXPORT void - zclock_test (bool verbose); - -// @end - - -// DEPRECATED in favor of zsys logging, see issue #519 -// Print formatted string to stdout, prefixed by date/time and -// terminated with a newline. -CZMQ_EXPORT void - zclock_log (const char *format, ...); - -// Compiler hints -CZMQ_EXPORT void zclock_log (const char *format, ...) CHECK_PRINTF (1); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zconfig.h b/phonelibs/zmq/aarch64-linux/include/zconfig.h deleted file mode 100644 index df0c708493..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zconfig.h +++ /dev/null @@ -1,185 +0,0 @@ -/* ========================================================================= - zconfig - work with config files written in rfc.zeromq.org/spec:4/ZPL. - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZCONFIG_H_INCLUDED__ -#define __ZCONFIG_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zconfig.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// -typedef int (zconfig_fct) ( - zconfig_t *self, void *arg, int level); - -// Create new config item -CZMQ_EXPORT zconfig_t * - zconfig_new (const char *name, zconfig_t *parent); - -// Load a config tree from a specified ZPL text file; returns a zconfig_t -// reference for the root, if the file exists and is readable. Returns NULL -// if the file does not exist. -CZMQ_EXPORT zconfig_t * - zconfig_load (const char *filename); - -// Equivalent to zconfig_load, taking a format string instead of a fixed -// filename. -CZMQ_EXPORT zconfig_t * - zconfig_loadf (const char *format, ...) CHECK_PRINTF (1); - -// Destroy a config item and all its children -CZMQ_EXPORT void - zconfig_destroy (zconfig_t **self_p); - -// Return name of config item -CZMQ_EXPORT char * - zconfig_name (zconfig_t *self); - -// Return value of config item -CZMQ_EXPORT char * - zconfig_value (zconfig_t *self); - -// Insert or update configuration key with value -CZMQ_EXPORT void - zconfig_put (zconfig_t *self, const char *path, const char *value); - -// Equivalent to zconfig_put, accepting a format specifier and variable -// argument list, instead of a single string value. -CZMQ_EXPORT void - zconfig_putf (zconfig_t *self, const char *path, const char *format, ...) CHECK_PRINTF (3); - -// Get value for config item into a string value; leading slash is optional -// and ignored. -CZMQ_EXPORT char * - zconfig_get (zconfig_t *self, const char *path, const char *default_value); - -// Set config item name, name may be NULL -CZMQ_EXPORT void - zconfig_set_name (zconfig_t *self, const char *name); - -// Set new value for config item. The new value may be a string, a printf -// format, or NULL. Note that if string may possibly contain '%', or if it -// comes from an insecure source, you must use '%s' as the format, followed -// by the string. -CZMQ_EXPORT void - zconfig_set_value (zconfig_t *self, const char *format, ...) CHECK_PRINTF (2); - -// Find our first child, if any -CZMQ_EXPORT zconfig_t * - zconfig_child (zconfig_t *self); - -// Find our first sibling, if any -CZMQ_EXPORT zconfig_t * - zconfig_next (zconfig_t *self); - -// Find a config item along a path; leading slash is optional and ignored. -CZMQ_EXPORT zconfig_t * - zconfig_locate (zconfig_t *self, const char *path); - -// Locate the last config item at a specified depth -CZMQ_EXPORT zconfig_t * - zconfig_at_depth (zconfig_t *self, int level); - -// Execute a callback for each config item in the tree; returns zero if -// successful, else -1. -CZMQ_EXPORT int - zconfig_execute (zconfig_t *self, zconfig_fct handler, void *arg); - -// Add comment to config item before saving to disk. You can add as many -// comment lines as you like. If you use a null format, all comments are -// deleted. -CZMQ_EXPORT void - zconfig_set_comment (zconfig_t *self, const char *format, ...) CHECK_PRINTF (2); - -// Return comments of config item, as zlist. -CZMQ_EXPORT zlist_t * - zconfig_comments (zconfig_t *self); - -// Save a config tree to a specified ZPL text file, where a filename -// "-" means dump to standard output. -CZMQ_EXPORT int - zconfig_save (zconfig_t *self, const char *filename); - -// Equivalent to zconfig_save, taking a format string instead of a fixed -// filename. -CZMQ_EXPORT int - zconfig_savef (zconfig_t *self, const char *format, ...) CHECK_PRINTF (2); - -// Report filename used during zconfig_load, or NULL if none -CZMQ_EXPORT const char * - zconfig_filename (zconfig_t *self); - -// Reload config tree from same file that it was previously loaded from. -// Returns 0 if OK, -1 if there was an error (and then does not change -// existing data). -CZMQ_EXPORT int - zconfig_reload (zconfig_t **self_p); - -// Load a config tree from a memory chunk -CZMQ_EXPORT zconfig_t * - zconfig_chunk_load (zchunk_t *chunk); - -// Save a config tree to a new memory chunk -CZMQ_EXPORT zchunk_t * - zconfig_chunk_save (zconfig_t *self); - -// Load a config tree from a null-terminated string -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zconfig_t * - zconfig_str_load (const char *string); - -// Save a config tree to a new null terminated string -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zconfig_str_save (zconfig_t *self); - -// Return true if a configuration tree was loaded from a file and that -// file has changed in since the tree was loaded. -CZMQ_EXPORT bool - zconfig_has_changed (zconfig_t *self); - -// Print the config file to open stream -CZMQ_EXPORT void - zconfig_fprint (zconfig_t *self, FILE *file); - -// Print properties of object -CZMQ_EXPORT void - zconfig_print (zconfig_t *self); - -// Self test of this class -CZMQ_EXPORT void - zconfig_test (bool verbose); - -// @end - -// Self test of this class -CZMQ_EXPORT void - zconfig_test (bool verbose); - -// Compiler hints -CZMQ_EXPORT void zconfig_set_value (zconfig_t *self, const char *format, ...) CHECK_PRINTF (2); - -#ifdef __cplusplus -} -#endif - -// Deprecated method aliases -#define zconfig_dump(s) zconfig_print(s) -#define zconfig_resolve(s,p,d) zconfig_get((s),(p),(d)) - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zdigest.h b/phonelibs/zmq/aarch64-linux/include/zdigest.h deleted file mode 100644 index def9e86053..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zdigest.h +++ /dev/null @@ -1,65 +0,0 @@ -/* ========================================================================= - zdigest - provides hashing functions (SHA-1 at present) - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZDIGEST_H_INCLUDED__ -#define __ZDIGEST_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zdigest.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Constructor - creates new digest object, which you use to build up a -// digest by repeatedly calling zdigest_update() on chunks of data. -CZMQ_EXPORT zdigest_t * - zdigest_new (void); - -// Destroy a digest object -CZMQ_EXPORT void - zdigest_destroy (zdigest_t **self_p); - -// Add buffer into digest calculation -CZMQ_EXPORT void - zdigest_update (zdigest_t *self, const byte *buffer, size_t length); - -// Return final digest hash data. If built without crypto support, -// returns NULL. -CZMQ_EXPORT const byte * - zdigest_data (zdigest_t *self); - -// Return final digest hash size -CZMQ_EXPORT size_t - zdigest_size (zdigest_t *self); - -// Return digest as printable hex string; caller should not modify nor -// free this string. After calling this, you may not use zdigest_update() -// on the same digest. If built without crypto support, returns NULL. -CZMQ_EXPORT char * - zdigest_string (zdigest_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zdigest_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zdir.h b/phonelibs/zmq/aarch64-linux/include/zdir.h deleted file mode 100644 index 6c5551b57e..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zdir.h +++ /dev/null @@ -1,149 +0,0 @@ -/* ========================================================================= - zdir - work with file-system directories - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZDIR_H_INCLUDED__ -#define __ZDIR_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zdir.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Create a new directory item that loads in the full tree of the specified -// path, optionally located under some parent path. If parent is "-", then -// loads only the top-level directory, and does not use parent as a path. -CZMQ_EXPORT zdir_t * - zdir_new (const char *path, const char *parent); - -// Destroy a directory tree and all children it contains. -CZMQ_EXPORT void - zdir_destroy (zdir_t **self_p); - -// Return directory path -CZMQ_EXPORT const char * - zdir_path (zdir_t *self); - -// Return last modification time for directory. -CZMQ_EXPORT time_t - zdir_modified (zdir_t *self); - -// Return total hierarchy size, in bytes of data contained in all files -// in the directory tree. -CZMQ_EXPORT off_t - zdir_cursize (zdir_t *self); - -// Return directory count -CZMQ_EXPORT size_t - zdir_count (zdir_t *self); - -// Returns a sorted list of zfile objects; Each entry in the list is a pointer -// to a zfile_t item already allocated in the zdir tree. Do not destroy the -// original zdir tree until you are done with this list. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlist_t * - zdir_list (zdir_t *self); - -// Remove directory, optionally including all files that it contains, at -// all levels. If force is false, will only remove the directory if empty. -// If force is true, will remove all files and all subdirectories. -CZMQ_EXPORT void - zdir_remove (zdir_t *self, bool force); - -// Calculate differences between two versions of a directory tree. -// Returns a list of zdir_patch_t patches. Either older or newer may -// be null, indicating the directory is empty/absent. If alias is set, -// generates virtual filename (minus path, plus alias). -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlist_t * - zdir_diff (zdir_t *older, zdir_t *newer, const char *alias); - -// Return full contents of directory as a zdir_patch list. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlist_t * - zdir_resync (zdir_t *self, const char *alias); - -// Load directory cache; returns a hash table containing the SHA-1 digests -// of every file in the tree. The cache is saved between runs in .cache. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zhash_t * - zdir_cache (zdir_t *self); - -// Print contents of directory to open stream -CZMQ_EXPORT void - zdir_fprint (zdir_t *self, FILE *file, int indent); - -// Print contents of directory to stdout -CZMQ_EXPORT void - zdir_print (zdir_t *self, int indent); - -// Create a new zdir_watch actor instance: -// -// zactor_t *watch = zactor_new (zdir_watch, NULL); -// -// Destroy zdir_watch instance: -// -// zactor_destroy (&watch); -// -// Enable verbose logging of commands and activity: -// -// zstr_send (watch, "VERBOSE"); -// -// Subscribe to changes to a directory path: -// -// zsock_send (watch, "ss", "SUBSCRIBE", "directory_path"); -// -// Unsubscribe from changes to a directory path: -// -// zsock_send (watch, "ss", "UNSUBSCRIBE", "directory_path"); -// -// Receive directory changes: -// zsock_recv (watch, "sp", &path, &patches); -// -// // Delete the received data. -// free (path); -// zlist_destroy (&patches); -CZMQ_EXPORT void - zdir_watch (zsock_t *pipe, void *unused); - -// Self test of this class. -CZMQ_EXPORT void - zdir_test (bool verbose); - -// @end - - -// Returns a sorted array of zfile objects; returns a single block of memory, -// that you destroy by calling zstr_free(). Each entry in the array is a pointer -// to a zfile_t item already allocated in the zdir tree. The array ends with -// a null pointer. Do not destroy the original zdir tree until you are done -// with this array. -CZMQ_EXPORT zfile_t ** - zdir_flatten (zdir_t *self); - -// Free a provided string, and nullify the parent pointer. Safe to call on -// a null pointer. -CZMQ_EXPORT void - zdir_flatten_free (zfile_t ***files_p); - -#ifdef __cplusplus -} -#endif - -// Deprecated method aliases -#define zdir_dump(s,i) zdir_print(s,i) - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zdir_patch.h b/phonelibs/zmq/aarch64-linux/include/zdir_patch.h deleted file mode 100644 index 8d15b9aeb4..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zdir_patch.h +++ /dev/null @@ -1,82 +0,0 @@ -/* ========================================================================= - zdir_patch - work with directory patches - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZDIR_PATCH_H_INCLUDED__ -#define __ZDIR_PATCH_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// un-namespaced enumeration values -#define patch_create ZDIR_PATCH_CREATE -#define patch_delete ZDIR_PATCH_DELETE - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zdir_patch.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -#define ZDIR_PATCH_CREATE 1 // Creates a new file -#define ZDIR_PATCH_DELETE 2 // Delete a file - -// Create new patch -CZMQ_EXPORT zdir_patch_t * - zdir_patch_new (const char *path, zfile_t *file, int op, const char *alias); - -// Destroy a patch -CZMQ_EXPORT void - zdir_patch_destroy (zdir_patch_t **self_p); - -// Create copy of a patch. If the patch is null, or memory was exhausted, -// returns null. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zdir_patch_t * - zdir_patch_dup (zdir_patch_t *self); - -// Return patch file directory path -CZMQ_EXPORT const char * - zdir_patch_path (zdir_patch_t *self); - -// Return patch file item -CZMQ_EXPORT zfile_t * - zdir_patch_file (zdir_patch_t *self); - -// Return operation -CZMQ_EXPORT int - zdir_patch_op (zdir_patch_t *self); - -// Return patch virtual file path -CZMQ_EXPORT const char * - zdir_patch_vpath (zdir_patch_t *self); - -// Calculate hash digest for file (create only) -CZMQ_EXPORT void - zdir_patch_digest_set (zdir_patch_t *self); - -// Return hash digest for patch file -CZMQ_EXPORT const char * - zdir_patch_digest (zdir_patch_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zdir_patch_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zfile.h b/phonelibs/zmq/aarch64-linux/include/zfile.h deleted file mode 100644 index 75c35774b9..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zfile.h +++ /dev/null @@ -1,177 +0,0 @@ -/* ========================================================================= - zfile - helper functions for working with files. - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZFILE_H_INCLUDED__ -#define __ZFILE_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zfile.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// If file exists, populates properties. CZMQ supports portable symbolic -// links, which are files with the extension ".ln". A symbolic link is a -// text file containing one line, the filename of a target file. Reading -// data from the symbolic link actually reads from the target file. Path -// may be NULL, in which case it is not used. -CZMQ_EXPORT zfile_t * - zfile_new (const char *path, const char *name); - -// Destroy a file item -CZMQ_EXPORT void - zfile_destroy (zfile_t **self_p); - -// Duplicate a file item, returns a newly constructed item. If the file -// is null, or memory was exhausted, returns null. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zfile_t * - zfile_dup (zfile_t *self); - -// Return file name, remove path if provided -CZMQ_EXPORT const char * - zfile_filename (zfile_t *self, const char *path); - -// Refresh file properties from disk; this is not done automatically -// on access methods, otherwise it is not possible to compare directory -// snapshots. -CZMQ_EXPORT void - zfile_restat (zfile_t *self); - -// Return when the file was last modified. If you want this to reflect the -// current situation, call zfile_restat before checking this property. -CZMQ_EXPORT time_t - zfile_modified (zfile_t *self); - -// Return the last-known size of the file. If you want this to reflect the -// current situation, call zfile_restat before checking this property. -CZMQ_EXPORT off_t - zfile_cursize (zfile_t *self); - -// Return true if the file is a directory. If you want this to reflect -// any external changes, call zfile_restat before checking this property. -CZMQ_EXPORT bool - zfile_is_directory (zfile_t *self); - -// Return true if the file is a regular file. If you want this to reflect -// any external changes, call zfile_restat before checking this property. -CZMQ_EXPORT bool - zfile_is_regular (zfile_t *self); - -// Return true if the file is readable by this process. If you want this to -// reflect any external changes, call zfile_restat before checking this -// property. -CZMQ_EXPORT bool - zfile_is_readable (zfile_t *self); - -// Return true if the file is writeable by this process. If you want this -// to reflect any external changes, call zfile_restat before checking this -// property. -CZMQ_EXPORT bool - zfile_is_writeable (zfile_t *self); - -// Check if file has stopped changing and can be safely processed. -// Updates the file statistics from disk at every call. -CZMQ_EXPORT bool - zfile_is_stable (zfile_t *self); - -// Return true if the file was changed on disk since the zfile_t object -// was created, or the last zfile_restat() call made on it. -CZMQ_EXPORT bool - zfile_has_changed (zfile_t *self); - -// Remove the file from disk -CZMQ_EXPORT void - zfile_remove (zfile_t *self); - -// Open file for reading -// Returns 0 if OK, -1 if not found or not accessible -CZMQ_EXPORT int - zfile_input (zfile_t *self); - -// Open file for writing, creating directory if needed -// File is created if necessary; chunks can be written to file at any -// location. Returns 0 if OK, -1 if error. -CZMQ_EXPORT int - zfile_output (zfile_t *self); - -// Read chunk from file at specified position. If this was the last chunk, -// sets the eof property. Returns a null chunk in case of error. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zchunk_t * - zfile_read (zfile_t *self, size_t bytes, off_t offset); - -// Returns true if zfile_read() just read the last chunk in the file. -CZMQ_EXPORT bool - zfile_eof (zfile_t *self); - -// Write chunk to file at specified position -// Return 0 if OK, else -1 -CZMQ_EXPORT int - zfile_write (zfile_t *self, zchunk_t *chunk, off_t offset); - -// Read next line of text from file. Returns a pointer to the text line, -// or NULL if there was nothing more to read from the file. -CZMQ_EXPORT const char * - zfile_readln (zfile_t *self); - -// Close file, if open -CZMQ_EXPORT void - zfile_close (zfile_t *self); - -// Return file handle, if opened -CZMQ_EXPORT FILE * - zfile_handle (zfile_t *self); - -// Calculate SHA1 digest for file, using zdigest class. -CZMQ_EXPORT const char * - zfile_digest (zfile_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zfile_test (bool verbose); - -// @end - - -// @interface -// These methods are deprecated, and now moved to zsys class. -CZMQ_EXPORT bool - zfile_exists (const char *filename); -CZMQ_EXPORT ssize_t - zfile_size (const char *filename); -CZMQ_EXPORT mode_t - zfile_mode (const char *filename); -CZMQ_EXPORT int - zfile_delete (const char *filename); -CZMQ_EXPORT bool - zfile_stable (const char *filename); -CZMQ_EXPORT int - zfile_mkdir (const char *pathname); -CZMQ_EXPORT int - zfile_rmdir (const char *pathname); -CZMQ_EXPORT void - zfile_mode_private (void); -CZMQ_EXPORT void - zfile_mode_default (void); -// @end - -#ifdef __cplusplus -} -#endif - - -#endif // __ZFILE_H_INCLUDED__ diff --git a/phonelibs/zmq/aarch64-linux/include/zframe.h b/phonelibs/zmq/aarch64-linux/include/zframe.h deleted file mode 100644 index 728093c36c..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zframe.h +++ /dev/null @@ -1,176 +0,0 @@ -/* ========================================================================= - zframe - working with single message frames - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZFRAME_H_INCLUDED__ -#define __ZFRAME_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zframe.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -#define ZFRAME_MORE 1 // -#define ZFRAME_REUSE 2 // -#define ZFRAME_DONTWAIT 4 // - -// Create a new frame. If size is not null, allocates the frame data -// to the specified size. If additionally, data is not null, copies -// size octets from the specified data into the frame body. -CZMQ_EXPORT zframe_t * - zframe_new (const void *data, size_t size); - -// Create an empty (zero-sized) frame -CZMQ_EXPORT zframe_t * - zframe_new_empty (void); - -// Create a frame with a specified string content. -CZMQ_EXPORT zframe_t * - zframe_from (const char *string); - -// Receive frame from socket, returns zframe_t object or NULL if the recv -// was interrupted. Does a blocking recv, if you want to not block then use -// zpoller or zloop. -CZMQ_EXPORT zframe_t * - zframe_recv (void *source); - -// Destroy a frame -CZMQ_EXPORT void - zframe_destroy (zframe_t **self_p); - -// Send a frame to a socket, destroy frame after sending. -// Return -1 on error, 0 on success. -CZMQ_EXPORT int - zframe_send (zframe_t **self_p, void *dest, int flags); - -// Return number of bytes in frame data -CZMQ_EXPORT size_t - zframe_size (zframe_t *self); - -// Return address of frame data -CZMQ_EXPORT byte * - zframe_data (zframe_t *self); - -// Return meta data property for frame -// Caller must free string when finished with it. -CZMQ_EXPORT const char * - zframe_meta (zframe_t *self, const char *property); - -// Create a new frame that duplicates an existing frame. If frame is null, -// or memory was exhausted, returns null. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zframe_dup (zframe_t *self); - -// Return frame data encoded as printable hex string, useful for 0MQ UUIDs. -// Caller must free string when finished with it. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zframe_strhex (zframe_t *self); - -// Return frame data copied into freshly allocated string -// Caller must free string when finished with it. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zframe_strdup (zframe_t *self); - -// Return TRUE if frame body is equal to string, excluding terminator -CZMQ_EXPORT bool - zframe_streq (zframe_t *self, const char *string); - -// Return frame MORE indicator (1 or 0), set when reading frame from socket -// or by the zframe_set_more() method -CZMQ_EXPORT int - zframe_more (zframe_t *self); - -// Set frame MORE indicator (1 or 0). Note this is NOT used when sending -// frame to socket, you have to specify flag explicitly. -CZMQ_EXPORT void - zframe_set_more (zframe_t *self, int more); - -// Return TRUE if two frames have identical size and data -// If either frame is NULL, equality is always false. -CZMQ_EXPORT bool - zframe_eq (zframe_t *self, zframe_t *other); - -// Set new contents for frame -CZMQ_EXPORT void - zframe_reset (zframe_t *self, const void *data, size_t size); - -// Send message to zsys log sink (may be stdout, or system facility as -// configured by zsys_set_logstream). Prefix shows before frame, if not null. -CZMQ_EXPORT void - zframe_print (zframe_t *self, const char *prefix); - -// Probe the supplied object, and report if it looks like a zframe_t. -CZMQ_EXPORT bool - zframe_is (void *self); - -// Self test of this class. -CZMQ_EXPORT void - zframe_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Return frame routing ID, if the frame came from a ZMQ_SERVER socket. -// Else returns zero. -CZMQ_EXPORT uint32_t - zframe_routing_id (zframe_t *self); - -// *** Draft method, for development use, may change without warning *** -// Set routing ID on frame. This is used if/when the frame is sent to a -// ZMQ_SERVER socket. -CZMQ_EXPORT void - zframe_set_routing_id (zframe_t *self, uint32_t routing_id); - -// *** Draft method, for development use, may change without warning *** -// Return frame group of radio-dish pattern. -CZMQ_EXPORT const char * - zframe_group (zframe_t *self); - -// *** Draft method, for development use, may change without warning *** -// Set group on frame. This is used if/when the frame is sent to a -// ZMQ_RADIO socket. -// Return -1 on error, 0 on success. -CZMQ_EXPORT int - zframe_set_group (zframe_t *self, const char *group); - -#endif // CZMQ_BUILD_DRAFT_API -// @end - - -// DEPRECATED as poor style -- callers should use zloop or zpoller -// Receive a new frame off the socket. Returns newly allocated frame, or -// NULL if there was no input waiting, or if the read was interrupted. -CZMQ_EXPORT zframe_t * - zframe_recv_nowait (void *source); - -// DEPRECATED as inconsistent; breaks principle that logging should all go -// to a single destination. -// Print contents of the frame to FILE stream. -CZMQ_EXPORT void - zframe_fprint (zframe_t *self, const char *prefix, FILE *file); - -// Deprecated method aliases -#define zframe_print_to_stream(s,p,F) zframe_fprint(s,p,F) - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zgossip.h b/phonelibs/zmq/aarch64-linux/include/zgossip.h deleted file mode 100644 index 647cb28c08..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zgossip.h +++ /dev/null @@ -1,95 +0,0 @@ -/* ========================================================================= - zgossip - zgossip server - - ** WARNING ************************************************************* - THIS SOURCE FILE IS 100% GENERATED. If you edit this file, you will lose - your changes at the next build cycle. This is great for temporary printf - statements. DO NOT MAKE ANY CHANGES YOU WISH TO KEEP. The correct places - for commits are: - - * The XML model used for this code generation: zgossip.xml, or - * The code generation script that built this file: zproto_server_c - ************************************************************************ - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef ZGOSSIP_H_INCLUDED -#define ZGOSSIP_H_INCLUDED - -#include "czmq.h" - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// To work with zgossip, use the CZMQ zactor API: -// -// Create new zgossip instance, passing logging prefix: -// -// zactor_t *zgossip = zactor_new (zgossip, "myname"); -// -// Destroy zgossip instance -// -// zactor_destroy (&zgossip); -// -// Enable verbose logging of commands and activity: -// -// zstr_send (zgossip, "VERBOSE"); -// -// Bind zgossip to specified endpoint. TCP endpoints may specify -// the port number as "*" to aquire an ephemeral port: -// -// zstr_sendx (zgossip, "BIND", endpoint, NULL); -// -// Return assigned port number, specifically when BIND was done using an -// an ephemeral port: -// -// zstr_sendx (zgossip, "PORT", NULL); -// char *command, *port_str; -// zstr_recvx (zgossip, &command, &port_str, NULL); -// assert (streq (command, "PORT")); -// -// Specify configuration file to load, overwriting any previous loaded -// configuration file or options: -// -// zstr_sendx (zgossip, "LOAD", filename, NULL); -// -// Set configuration path value: -// -// zstr_sendx (zgossip, "SET", path, value, NULL); -// -// Save configuration data to config file on disk: -// -// zstr_sendx (zgossip, "SAVE", filename, NULL); -// -// Send zmsg_t instance to zgossip: -// -// zactor_send (zgossip, &msg); -// -// Receive zmsg_t instance from zgossip: -// -// zmsg_t *msg = zactor_recv (zgossip); -// -// This is the zgossip constructor as a zactor_fn: -// -CZMQ_EXPORT void - zgossip (zsock_t *pipe, void *args); - -// Self test of this class -CZMQ_EXPORT void - zgossip_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zhash.h b/phonelibs/zmq/aarch64-linux/include/zhash.h deleted file mode 100644 index 138adf63ac..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zhash.h +++ /dev/null @@ -1,182 +0,0 @@ -/* ========================================================================= - zhash - generic type-free hash container (simple) - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZHASH_H_INCLUDED__ -#define __ZHASH_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zhash.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Callback function for zhash_freefn method -typedef void (zhash_free_fn) ( - void *data); - -// Create a new, empty hash container -CZMQ_EXPORT zhash_t * - zhash_new (void); - -// Unpack binary frame into a new hash table. Packed data must follow format -// defined by zhash_pack. Hash table is set to autofree. An empty frame -// unpacks to an empty hash table. -CZMQ_EXPORT zhash_t * - zhash_unpack (zframe_t *frame); - -// Destroy a hash container and all items in it -CZMQ_EXPORT void - zhash_destroy (zhash_t **self_p); - -// Insert item into hash table with specified key and item. -// If key is already present returns -1 and leaves existing item unchanged -// Returns 0 on success. -CZMQ_EXPORT int - zhash_insert (zhash_t *self, const char *key, void *item); - -// Update item into hash table with specified key and item. -// If key is already present, destroys old item and inserts new one. -// Use free_fn method to ensure deallocator is properly called on item. -CZMQ_EXPORT void - zhash_update (zhash_t *self, const char *key, void *item); - -// Remove an item specified by key from the hash table. If there was no such -// item, this function does nothing. -CZMQ_EXPORT void - zhash_delete (zhash_t *self, const char *key); - -// Return the item at the specified key, or null -CZMQ_EXPORT void * - zhash_lookup (zhash_t *self, const char *key); - -// Reindexes an item from an old key to a new key. If there was no such -// item, does nothing. Returns 0 if successful, else -1. -CZMQ_EXPORT int - zhash_rename (zhash_t *self, const char *old_key, const char *new_key); - -// Set a free function for the specified hash table item. When the item is -// destroyed, the free function, if any, is called on that item. -// Use this when hash items are dynamically allocated, to ensure that -// you don't have memory leaks. You can pass 'free' or NULL as a free_fn. -// Returns the item, or NULL if there is no such item. -CZMQ_EXPORT void * - zhash_freefn (zhash_t *self, const char *key, zhash_free_fn free_fn); - -// Return the number of keys/items in the hash table -CZMQ_EXPORT size_t - zhash_size (zhash_t *self); - -// Make copy of hash table; if supplied table is null, returns null. -// Does not copy items themselves. Rebuilds new table so may be slow on -// very large tables. NOTE: only works with item values that are strings -// since there's no other way to know how to duplicate the item value. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zhash_t * - zhash_dup (zhash_t *self); - -// Return keys for items in table -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlist_t * - zhash_keys (zhash_t *self); - -// Simple iterator; returns first item in hash table, in no given order, -// or NULL if the table is empty. This method is simpler to use than the -// foreach() method, which is deprecated. To access the key for this item -// use zhash_cursor(). NOTE: do NOT modify the table while iterating. -CZMQ_EXPORT void * - zhash_first (zhash_t *self); - -// Simple iterator; returns next item in hash table, in no given order, -// or NULL if the last item was already returned. Use this together with -// zhash_first() to process all items in a hash table. If you need the -// items in sorted order, use zhash_keys() and then zlist_sort(). To -// access the key for this item use zhash_cursor(). NOTE: do NOT modify -// the table while iterating. -CZMQ_EXPORT void * - zhash_next (zhash_t *self); - -// After a successful first/next method, returns the key for the item that -// was returned. This is a constant string that you may not modify or -// deallocate, and which lasts as long as the item in the hash. After an -// unsuccessful first/next, returns NULL. -CZMQ_EXPORT const char * - zhash_cursor (zhash_t *self); - -// Add a comment to hash table before saving to disk. You can add as many -// comment lines as you like. These comment lines are discarded when loading -// the file. If you use a null format, all comments are deleted. -CZMQ_EXPORT void - zhash_comment (zhash_t *self, const char *format, ...) CHECK_PRINTF (2); - -// Serialize hash table to a binary frame that can be sent in a message. -// The packed format is compatible with the 'dictionary' type defined in -// http://rfc.zeromq.org/spec:35/FILEMQ, and implemented by zproto: -// -// ; A list of name/value pairs -// dictionary = dict-count *( dict-name dict-value ) -// dict-count = number-4 -// dict-value = longstr -// dict-name = string -// -// ; Strings are always length + text contents -// longstr = number-4 *VCHAR -// string = number-1 *VCHAR -// -// ; Numbers are unsigned integers in network byte order -// number-1 = 1OCTET -// number-4 = 4OCTET -// -// Comments are not included in the packed data. Item values MUST be -// strings. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zhash_pack (zhash_t *self); - -// Save hash table to a text file in name=value format. Hash values must be -// printable strings; keys may not contain '=' character. Returns 0 if OK, -// else -1 if a file error occurred. -CZMQ_EXPORT int - zhash_save (zhash_t *self, const char *filename); - -// Load hash table from a text file in name=value format; hash table must -// already exist. Hash values must printable strings; keys may not contain -// '=' character. Returns 0 if OK, else -1 if a file was not readable. -CZMQ_EXPORT int - zhash_load (zhash_t *self, const char *filename); - -// When a hash table was loaded from a file by zhash_load, this method will -// reload the file if it has been modified since, and is "stable", i.e. not -// still changing. Returns 0 if OK, -1 if there was an error reloading the -// file. -CZMQ_EXPORT int - zhash_refresh (zhash_t *self); - -// Set hash for automatic value destruction -CZMQ_EXPORT void - zhash_autofree (zhash_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zhash_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zhashx.h b/phonelibs/zmq/aarch64-linux/include/zhashx.h deleted file mode 100644 index 360a773ee8..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zhashx.h +++ /dev/null @@ -1,277 +0,0 @@ -/* ========================================================================= - zhashx - extended generic type-free hash container - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZHASHX_H_INCLUDED__ -#define __ZHASHX_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zhashx.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// Destroy an item -typedef void (zhashx_destructor_fn) ( - void **item); - -// Duplicate an item -typedef void * (zhashx_duplicator_fn) ( - const void *item); - -// Compare two items, for sorting -typedef int (zhashx_comparator_fn) ( - const void *item1, const void *item2); - -// compare two items, for sorting -typedef void (zhashx_free_fn) ( - void *data); - -// compare two items, for sorting -typedef size_t (zhashx_hash_fn) ( - const void *key); - -// Serializes an item to a longstr. -// The caller takes ownership of the newly created object. -typedef char * (zhashx_serializer_fn) ( - const void *item); - -// Deserializes a longstr into an item. -// The caller takes ownership of the newly created object. -typedef void * (zhashx_deserializer_fn) ( - const char *item_str); - -// Create a new, empty hash container -CZMQ_EXPORT zhashx_t * - zhashx_new (void); - -// Unpack binary frame into a new hash table. Packed data must follow format -// defined by zhashx_pack. Hash table is set to autofree. An empty frame -// unpacks to an empty hash table. -CZMQ_EXPORT zhashx_t * - zhashx_unpack (zframe_t *frame); - -// Destroy a hash container and all items in it -CZMQ_EXPORT void - zhashx_destroy (zhashx_t **self_p); - -// Insert item into hash table with specified key and item. -// If key is already present returns -1 and leaves existing item unchanged -// Returns 0 on success. -CZMQ_EXPORT int - zhashx_insert (zhashx_t *self, const void *key, void *item); - -// Update or insert item into hash table with specified key and item. If the -// key is already present, destroys old item and inserts new one. If you set -// a container item destructor, this is called on the old value. If the key -// was not already present, inserts a new item. Sets the hash cursor to the -// new item. -CZMQ_EXPORT void - zhashx_update (zhashx_t *self, const void *key, void *item); - -// Remove an item specified by key from the hash table. If there was no such -// item, this function does nothing. -CZMQ_EXPORT void - zhashx_delete (zhashx_t *self, const void *key); - -// Delete all items from the hash table. If the key destructor is -// set, calls it on every key. If the item destructor is set, calls -// it on every item. -CZMQ_EXPORT void - zhashx_purge (zhashx_t *self); - -// Return the item at the specified key, or null -CZMQ_EXPORT void * - zhashx_lookup (zhashx_t *self, const void *key); - -// Reindexes an item from an old key to a new key. If there was no such -// item, does nothing. Returns 0 if successful, else -1. -CZMQ_EXPORT int - zhashx_rename (zhashx_t *self, const void *old_key, const void *new_key); - -// Set a free function for the specified hash table item. When the item is -// destroyed, the free function, if any, is called on that item. -// Use this when hash items are dynamically allocated, to ensure that -// you don't have memory leaks. You can pass 'free' or NULL as a free_fn. -// Returns the item, or NULL if there is no such item. -CZMQ_EXPORT void * - zhashx_freefn (zhashx_t *self, const void *key, zhashx_free_fn free_fn); - -// Return the number of keys/items in the hash table -CZMQ_EXPORT size_t - zhashx_size (zhashx_t *self); - -// Return a zlistx_t containing the keys for the items in the -// table. Uses the key_duplicator to duplicate all keys and sets the -// key_destructor as destructor for the list. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlistx_t * - zhashx_keys (zhashx_t *self); - -// Return a zlistx_t containing the values for the items in the -// table. Uses the duplicator to duplicate all items and sets the -// destructor as destructor for the list. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlistx_t * - zhashx_values (zhashx_t *self); - -// Simple iterator; returns first item in hash table, in no given order, -// or NULL if the table is empty. This method is simpler to use than the -// foreach() method, which is deprecated. To access the key for this item -// use zhashx_cursor(). NOTE: do NOT modify the table while iterating. -CZMQ_EXPORT void * - zhashx_first (zhashx_t *self); - -// Simple iterator; returns next item in hash table, in no given order, -// or NULL if the last item was already returned. Use this together with -// zhashx_first() to process all items in a hash table. If you need the -// items in sorted order, use zhashx_keys() and then zlistx_sort(). To -// access the key for this item use zhashx_cursor(). NOTE: do NOT modify -// the table while iterating. -CZMQ_EXPORT void * - zhashx_next (zhashx_t *self); - -// After a successful first/next method, returns the key for the item that -// was returned. This is a constant string that you may not modify or -// deallocate, and which lasts as long as the item in the hash. After an -// unsuccessful first/next, returns NULL. -CZMQ_EXPORT const void * - zhashx_cursor (zhashx_t *self); - -// Add a comment to hash table before saving to disk. You can add as many -// comment lines as you like. These comment lines are discarded when loading -// the file. If you use a null format, all comments are deleted. -CZMQ_EXPORT void - zhashx_comment (zhashx_t *self, const char *format, ...) CHECK_PRINTF (2); - -// Save hash table to a text file in name=value format. Hash values must be -// printable strings; keys may not contain '=' character. Returns 0 if OK, -// else -1 if a file error occurred. -CZMQ_EXPORT int - zhashx_save (zhashx_t *self, const char *filename); - -// Load hash table from a text file in name=value format; hash table must -// already exist. Hash values must printable strings; keys may not contain -// '=' character. Returns 0 if OK, else -1 if a file was not readable. -CZMQ_EXPORT int - zhashx_load (zhashx_t *self, const char *filename); - -// When a hash table was loaded from a file by zhashx_load, this method will -// reload the file if it has been modified since, and is "stable", i.e. not -// still changing. Returns 0 if OK, -1 if there was an error reloading the -// file. -CZMQ_EXPORT int - zhashx_refresh (zhashx_t *self); - -// Serialize hash table to a binary frame that can be sent in a message. -// The packed format is compatible with the 'dictionary' type defined in -// http://rfc.zeromq.org/spec:35/FILEMQ, and implemented by zproto: -// -// ; A list of name/value pairs -// dictionary = dict-count *( dict-name dict-value ) -// dict-count = number-4 -// dict-value = longstr -// dict-name = string -// -// ; Strings are always length + text contents -// longstr = number-4 *VCHAR -// string = number-1 *VCHAR -// -// ; Numbers are unsigned integers in network byte order -// number-1 = 1OCTET -// number-4 = 4OCTET -// -// Comments are not included in the packed data. Item values MUST be -// strings. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zhashx_pack (zhashx_t *self); - -// Make a copy of the list; items are duplicated if you set a duplicator -// for the list, otherwise not. Copying a null reference returns a null -// reference. Note that this method's behavior changed slightly for CZMQ -// v3.x, as it does not set nor respect autofree. It does however let you -// duplicate any hash table safely. The old behavior is in zhashx_dup_v2. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zhashx_t * - zhashx_dup (zhashx_t *self); - -// Set a user-defined deallocator for hash items; by default items are not -// freed when the hash is destroyed. -CZMQ_EXPORT void - zhashx_set_destructor (zhashx_t *self, zhashx_destructor_fn destructor); - -// Set a user-defined duplicator for hash items; by default items are not -// copied when the hash is duplicated. -CZMQ_EXPORT void - zhashx_set_duplicator (zhashx_t *self, zhashx_duplicator_fn duplicator); - -// Set a user-defined deallocator for keys; by default keys are freed -// when the hash is destroyed using free(). -CZMQ_EXPORT void - zhashx_set_key_destructor (zhashx_t *self, zhashx_destructor_fn destructor); - -// Set a user-defined duplicator for keys; by default keys are duplicated -// using strdup. -CZMQ_EXPORT void - zhashx_set_key_duplicator (zhashx_t *self, zhashx_duplicator_fn duplicator); - -// Set a user-defined comparator for keys; by default keys are -// compared using strcmp. -CZMQ_EXPORT void - zhashx_set_key_comparator (zhashx_t *self, zhashx_comparator_fn comparator); - -// Set a user-defined comparator for keys; by default keys are -// compared using strcmp. -CZMQ_EXPORT void - zhashx_set_key_hasher (zhashx_t *self, zhashx_hash_fn hasher); - -// Make copy of hash table; if supplied table is null, returns null. -// Does not copy items themselves. Rebuilds new table so may be slow on -// very large tables. NOTE: only works with item values that are strings -// since there's no other way to know how to duplicate the item value. -CZMQ_EXPORT zhashx_t * - zhashx_dup_v2 (zhashx_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zhashx_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Same as unpack but uses a user-defined deserializer function to convert -// a longstr back into item format. -CZMQ_EXPORT zhashx_t * - zhashx_unpack_own (zframe_t *frame, zhashx_deserializer_fn deserializer); - -// *** Draft method, for development use, may change without warning *** -// Same as pack but uses a user-defined serializer function to convert items -// into longstr. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zhashx_pack_own (zhashx_t *self, zhashx_serializer_fn serializer); - -#endif // CZMQ_BUILD_DRAFT_API -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/ziflist.h b/phonelibs/zmq/aarch64-linux/include/ziflist.h deleted file mode 100644 index cb2b144802..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/ziflist.h +++ /dev/null @@ -1,77 +0,0 @@ -/* ========================================================================= - ziflist - List of network interfaces available on system - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZIFLIST_H_INCLUDED__ -#define __ZIFLIST_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/ziflist.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Get a list of network interfaces currently defined on the system -CZMQ_EXPORT ziflist_t * - ziflist_new (void); - -// Destroy a ziflist instance -CZMQ_EXPORT void - ziflist_destroy (ziflist_t **self_p); - -// Reload network interfaces from system -CZMQ_EXPORT void - ziflist_reload (ziflist_t *self); - -// Return the number of network interfaces on system -CZMQ_EXPORT size_t - ziflist_size (ziflist_t *self); - -// Get first network interface, return NULL if there are none -CZMQ_EXPORT const char * - ziflist_first (ziflist_t *self); - -// Get next network interface, return NULL if we hit the last one -CZMQ_EXPORT const char * - ziflist_next (ziflist_t *self); - -// Return the current interface IP address as a printable string -CZMQ_EXPORT const char * - ziflist_address (ziflist_t *self); - -// Return the current interface broadcast address as a printable string -CZMQ_EXPORT const char * - ziflist_broadcast (ziflist_t *self); - -// Return the current interface network mask as a printable string -CZMQ_EXPORT const char * - ziflist_netmask (ziflist_t *self); - -// Return the list of interfaces. -CZMQ_EXPORT void - ziflist_print (ziflist_t *self); - -// Self test of this class. -CZMQ_EXPORT void - ziflist_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zlist.h b/phonelibs/zmq/aarch64-linux/include/zlist.h deleted file mode 100644 index 1dcd39b995..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zlist.h +++ /dev/null @@ -1,158 +0,0 @@ -/* ========================================================================= - zlist - simple generic list container - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZLIST_H_INCLUDED__ -#define __ZLIST_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zlist.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Comparison function e.g. for sorting and removing. -typedef int (zlist_compare_fn) ( - void *item1, void *item2); - -// Callback function for zlist_freefn method -typedef void (zlist_free_fn) ( - void *data); - -// Create a new list container -CZMQ_EXPORT zlist_t * - zlist_new (void); - -// Destroy a list container -CZMQ_EXPORT void - zlist_destroy (zlist_t **self_p); - -// Return the item at the head of list. If the list is empty, returns NULL. -// Leaves cursor pointing at the head item, or NULL if the list is empty. -CZMQ_EXPORT void * - zlist_first (zlist_t *self); - -// Return the next item. If the list is empty, returns NULL. To move to -// the start of the list call zlist_first (). Advances the cursor. -CZMQ_EXPORT void * - zlist_next (zlist_t *self); - -// Return the item at the tail of list. If the list is empty, returns NULL. -// Leaves cursor pointing at the tail item, or NULL if the list is empty. -CZMQ_EXPORT void * - zlist_last (zlist_t *self); - -// Return first item in the list, or null, leaves the cursor -CZMQ_EXPORT void * - zlist_head (zlist_t *self); - -// Return last item in the list, or null, leaves the cursor -CZMQ_EXPORT void * - zlist_tail (zlist_t *self); - -// Return the current item of list. If the list is empty, returns NULL. -// Leaves cursor pointing at the current item, or NULL if the list is empty. -CZMQ_EXPORT void * - zlist_item (zlist_t *self); - -// Append an item to the end of the list, return 0 if OK or -1 if this -// failed for some reason (out of memory). Note that if a duplicator has -// been set, this method will also duplicate the item. -CZMQ_EXPORT int - zlist_append (zlist_t *self, void *item); - -// Push an item to the start of the list, return 0 if OK or -1 if this -// failed for some reason (out of memory). Note that if a duplicator has -// been set, this method will also duplicate the item. -CZMQ_EXPORT int - zlist_push (zlist_t *self, void *item); - -// Pop the item off the start of the list, if any -CZMQ_EXPORT void * - zlist_pop (zlist_t *self); - -// Checks if an item already is present. Uses compare method to determine if -// items are equal. If the compare method is NULL the check will only compare -// pointers. Returns true if item is present else false. -CZMQ_EXPORT bool - zlist_exists (zlist_t *self, void *item); - -// Remove the specified item from the list if present -CZMQ_EXPORT void - zlist_remove (zlist_t *self, void *item); - -// Make a copy of list. If the list has autofree set, the copied list will -// duplicate all items, which must be strings. Otherwise, the list will hold -// pointers back to the items in the original list. If list is null, returns -// NULL. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlist_t * - zlist_dup (zlist_t *self); - -// Purge all items from list -CZMQ_EXPORT void - zlist_purge (zlist_t *self); - -// Return number of items in the list -CZMQ_EXPORT size_t - zlist_size (zlist_t *self); - -// Sort the list. If the compare function is null, sorts the list by -// ascending key value using a straight ASCII comparison. If you specify -// a compare function, this decides how items are sorted. The sort is not -// stable, so may reorder items with the same keys. The algorithm used is -// combsort, a compromise between performance and simplicity. -CZMQ_EXPORT void - zlist_sort (zlist_t *self, zlist_compare_fn compare); - -// Set list for automatic item destruction; item values MUST be strings. -// By default a list item refers to a value held elsewhere. When you set -// this, each time you append or push a list item, zlist will take a copy -// of the string value. Then, when you destroy the list, it will free all -// item values automatically. If you use any other technique to allocate -// list values, you must free them explicitly before destroying the list. -// The usual technique is to pop list items and destroy them, until the -// list is empty. -CZMQ_EXPORT void - zlist_autofree (zlist_t *self); - -// Sets a compare function for this list. The function compares two items. -// It returns an integer less than, equal to, or greater than zero if the -// first item is found, respectively, to be less than, to match, or be -// greater than the second item. -// This function is used for sorting, removal and exists checking. -CZMQ_EXPORT void - zlist_comparefn (zlist_t *self, zlist_compare_fn fn); - -// Set a free function for the specified list item. When the item is -// destroyed, the free function, if any, is called on that item. -// Use this when list items are dynamically allocated, to ensure that -// you don't have memory leaks. You can pass 'free' or NULL as a free_fn. -// Returns the item, or NULL if there is no such item. -CZMQ_EXPORT void * - zlist_freefn (zlist_t *self, void *item, zlist_free_fn fn, bool at_tail); - -// Self test of this class. -CZMQ_EXPORT void - zlist_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zlistx.h b/phonelibs/zmq/aarch64-linux/include/zlistx.h deleted file mode 100644 index 512637cef3..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zlistx.h +++ /dev/null @@ -1,205 +0,0 @@ -/* ========================================================================= - zlistx - extended generic list container - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZLISTX_H_INCLUDED__ -#define __ZLISTX_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zlistx.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Destroy an item -typedef void (zlistx_destructor_fn) ( - void **item); - -// Duplicate an item -typedef void * (zlistx_duplicator_fn) ( - const void *item); - -// Compare two items, for sorting -typedef int (zlistx_comparator_fn) ( - const void *item1, const void *item2); - -// Create a new, empty list. -CZMQ_EXPORT zlistx_t * - zlistx_new (void); - -// Destroy a list. If an item destructor was specified, all items in the -// list are automatically destroyed as well. -CZMQ_EXPORT void - zlistx_destroy (zlistx_t **self_p); - -// Add an item to the head of the list. Calls the item duplicator, if any, -// on the item. Resets cursor to list head. Returns an item handle on -// success, NULL if memory was exhausted. -CZMQ_EXPORT void * - zlistx_add_start (zlistx_t *self, void *item); - -// Add an item to the tail of the list. Calls the item duplicator, if any, -// on the item. Resets cursor to list head. Returns an item handle on -// success, NULL if memory was exhausted. -CZMQ_EXPORT void * - zlistx_add_end (zlistx_t *self, void *item); - -// Return the number of items in the list -CZMQ_EXPORT size_t - zlistx_size (zlistx_t *self); - -// Return first item in the list, or null, leaves the cursor -CZMQ_EXPORT void * - zlistx_head (zlistx_t *self); - -// Return last item in the list, or null, leaves the cursor -CZMQ_EXPORT void * - zlistx_tail (zlistx_t *self); - -// Return the item at the head of list. If the list is empty, returns NULL. -// Leaves cursor pointing at the head item, or NULL if the list is empty. -CZMQ_EXPORT void * - zlistx_first (zlistx_t *self); - -// Return the next item. At the end of the list (or in an empty list), -// returns NULL. Use repeated zlistx_next () calls to work through the list -// from zlistx_first (). First time, acts as zlistx_first(). -CZMQ_EXPORT void * - zlistx_next (zlistx_t *self); - -// Return the previous item. At the start of the list (or in an empty list), -// returns NULL. Use repeated zlistx_prev () calls to work through the list -// backwards from zlistx_last (). First time, acts as zlistx_last(). -CZMQ_EXPORT void * - zlistx_prev (zlistx_t *self); - -// Return the item at the tail of list. If the list is empty, returns NULL. -// Leaves cursor pointing at the tail item, or NULL if the list is empty. -CZMQ_EXPORT void * - zlistx_last (zlistx_t *self); - -// Returns the value of the item at the cursor, or NULL if the cursor is -// not pointing to an item. -CZMQ_EXPORT void * - zlistx_item (zlistx_t *self); - -// Returns the handle of the item at the cursor, or NULL if the cursor is -// not pointing to an item. -CZMQ_EXPORT void * - zlistx_cursor (zlistx_t *self); - -// Returns the item associated with the given list handle, or NULL if passed -// in handle is NULL. Asserts that the passed in handle points to a list element. -CZMQ_EXPORT void * - zlistx_handle_item (void *handle); - -// Find an item in the list, searching from the start. Uses the item -// comparator, if any, else compares item values directly. Returns the -// item handle found, or NULL. Sets the cursor to the found item, if any. -CZMQ_EXPORT void * - zlistx_find (zlistx_t *self, void *item); - -// Detach an item from the list, using its handle. The item is not modified, -// and the caller is responsible for destroying it if necessary. If handle is -// null, detaches the first item on the list. Returns item that was detached, -// or null if none was. If cursor was at item, moves cursor to previous item, -// so you can detach items while iterating forwards through a list. -CZMQ_EXPORT void * - zlistx_detach (zlistx_t *self, void *handle); - -// Detach item at the cursor, if any, from the list. The item is not modified, -// and the caller is responsible for destroying it as necessary. Returns item -// that was detached, or null if none was. Moves cursor to previous item, so -// you can detach items while iterating forwards through a list. -CZMQ_EXPORT void * - zlistx_detach_cur (zlistx_t *self); - -// Delete an item, using its handle. Calls the item destructor is any is -// set. If handle is null, deletes the first item on the list. Returns 0 -// if an item was deleted, -1 if not. If cursor was at item, moves cursor -// to previous item, so you can delete items while iterating forwards -// through a list. -CZMQ_EXPORT int - zlistx_delete (zlistx_t *self, void *handle); - -// Move an item to the start of the list, via its handle. -CZMQ_EXPORT void - zlistx_move_start (zlistx_t *self, void *handle); - -// Move an item to the end of the list, via its handle. -CZMQ_EXPORT void - zlistx_move_end (zlistx_t *self, void *handle); - -// Remove all items from the list, and destroy them if the item destructor -// is set. -CZMQ_EXPORT void - zlistx_purge (zlistx_t *self); - -// Sort the list. If an item comparator was set, calls that to compare -// items, otherwise compares on item value. The sort is not stable, so may -// reorder equal items. -CZMQ_EXPORT void - zlistx_sort (zlistx_t *self); - -// Create a new node and insert it into a sorted list. Calls the item -// duplicator, if any, on the item. If low_value is true, starts searching -// from the start of the list, otherwise searches from the end. Use the item -// comparator, if any, to find where to place the new node. Returns a handle -// to the new node, or NULL if memory was exhausted. Resets the cursor to the -// list head. -CZMQ_EXPORT void * - zlistx_insert (zlistx_t *self, void *item, bool low_value); - -// Move an item, specified by handle, into position in a sorted list. Uses -// the item comparator, if any, to determine the new location. If low_value -// is true, starts searching from the start of the list, otherwise searches -// from the end. -CZMQ_EXPORT void - zlistx_reorder (zlistx_t *self, void *handle, bool low_value); - -// Make a copy of the list; items are duplicated if you set a duplicator -// for the list, otherwise not. Copying a null reference returns a null -// reference. -CZMQ_EXPORT zlistx_t * - zlistx_dup (zlistx_t *self); - -// Set a user-defined deallocator for list items; by default items are not -// freed when the list is destroyed. -CZMQ_EXPORT void - zlistx_set_destructor (zlistx_t *self, zlistx_destructor_fn destructor); - -// Set a user-defined duplicator for list items; by default items are not -// copied when the list is duplicated. -CZMQ_EXPORT void - zlistx_set_duplicator (zlistx_t *self, zlistx_duplicator_fn duplicator); - -// Set a user-defined comparator for zlistx_find and zlistx_sort; the method -// must return -1, 0, or 1 depending on whether item1 is less than, equal to, -// or greater than, item2. -CZMQ_EXPORT void - zlistx_set_comparator (zlistx_t *self, zlistx_comparator_fn comparator); - -// Self test of this class. -CZMQ_EXPORT void - zlistx_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zloop.h b/phonelibs/zmq/aarch64-linux/include/zloop.h deleted file mode 100644 index 83f46f282a..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zloop.h +++ /dev/null @@ -1,163 +0,0 @@ -/* ========================================================================= - zloop - event-driven reactor - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZLOOP_H_INCLUDED__ -#define __ZLOOP_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zloop.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Callback function for reactor socket activity -typedef int (zloop_reader_fn) ( - zloop_t *loop, zsock_t *reader, void *arg); - -// Callback function for reactor events (low-level) -typedef int (zloop_fn) ( - zloop_t *loop, zmq_pollitem_t *item, void *arg); - -// Callback for reactor timer events -typedef int (zloop_timer_fn) ( - zloop_t *loop, int timer_id, void *arg); - -// Create a new zloop reactor -CZMQ_EXPORT zloop_t * - zloop_new (void); - -// Destroy a reactor -CZMQ_EXPORT void - zloop_destroy (zloop_t **self_p); - -// Register socket reader with the reactor. When the reader has messages, -// the reactor will call the handler, passing the arg. Returns 0 if OK, -1 -// if there was an error. If you register the same socket more than once, -// each instance will invoke its corresponding handler. -CZMQ_EXPORT int - zloop_reader (zloop_t *self, zsock_t *sock, zloop_reader_fn handler, void *arg); - -// Cancel a socket reader from the reactor. If multiple readers exist for -// same socket, cancels ALL of them. -CZMQ_EXPORT void - zloop_reader_end (zloop_t *self, zsock_t *sock); - -// Configure a registered reader to ignore errors. If you do not set this, -// then readers that have errors are removed from the reactor silently. -CZMQ_EXPORT void - zloop_reader_set_tolerant (zloop_t *self, zsock_t *sock); - -// Register low-level libzmq pollitem with the reactor. When the pollitem -// is ready, will call the handler, passing the arg. Returns 0 if OK, -1 -// if there was an error. If you register the pollitem more than once, each -// instance will invoke its corresponding handler. A pollitem with -// socket=NULL and fd=0 means 'poll on FD zero'. -CZMQ_EXPORT int - zloop_poller (zloop_t *self, zmq_pollitem_t *item, zloop_fn handler, void *arg); - -// Cancel a pollitem from the reactor, specified by socket or FD. If both -// are specified, uses only socket. If multiple poll items exist for same -// socket/FD, cancels ALL of them. -CZMQ_EXPORT void - zloop_poller_end (zloop_t *self, zmq_pollitem_t *item); - -// Configure a registered poller to ignore errors. If you do not set this, -// then poller that have errors are removed from the reactor silently. -CZMQ_EXPORT void - zloop_poller_set_tolerant (zloop_t *self, zmq_pollitem_t *item); - -// Register a timer that expires after some delay and repeats some number of -// times. At each expiry, will call the handler, passing the arg. To run a -// timer forever, use 0 times. Returns a timer_id that is used to cancel the -// timer in the future. Returns -1 if there was an error. -CZMQ_EXPORT int - zloop_timer (zloop_t *self, size_t delay, size_t times, zloop_timer_fn handler, void *arg); - -// Cancel a specific timer identified by a specific timer_id (as returned by -// zloop_timer). -CZMQ_EXPORT int - zloop_timer_end (zloop_t *self, int timer_id); - -// Register a ticket timer. Ticket timers are very fast in the case where -// you use a lot of timers (thousands), and frequently remove and add them. -// The main use case is expiry timers for servers that handle many clients, -// and which reset the expiry timer for each message received from a client. -// Whereas normal timers perform poorly as the number of clients grows, the -// cost of ticket timers is constant, no matter the number of clients. You -// must set the ticket delay using zloop_set_ticket_delay before creating a -// ticket. Returns a handle to the timer that you should use in -// zloop_ticket_reset and zloop_ticket_delete. -CZMQ_EXPORT void * - zloop_ticket (zloop_t *self, zloop_timer_fn handler, void *arg); - -// Reset a ticket timer, which moves it to the end of the ticket list and -// resets its execution time. This is a very fast operation. -CZMQ_EXPORT void - zloop_ticket_reset (zloop_t *self, void *handle); - -// Delete a ticket timer. We do not actually delete the ticket here, as -// other code may still refer to the ticket. We mark as deleted, and remove -// later and safely. -CZMQ_EXPORT void - zloop_ticket_delete (zloop_t *self, void *handle); - -// Set the ticket delay, which applies to all tickets. If you lower the -// delay and there are already tickets created, the results are undefined. -CZMQ_EXPORT void - zloop_set_ticket_delay (zloop_t *self, size_t ticket_delay); - -// Set hard limit on number of timers allowed. Setting more than a small -// number of timers (10-100) can have a dramatic impact on the performance -// of the reactor. For high-volume cases, use ticket timers. If the hard -// limit is reached, the reactor stops creating new timers and logs an -// error. -CZMQ_EXPORT void - zloop_set_max_timers (zloop_t *self, size_t max_timers); - -// Set verbose tracing of reactor on/off. The default verbose setting is -// off (false). -CZMQ_EXPORT void - zloop_set_verbose (zloop_t *self, bool verbose); - -// By default the reactor stops if the process receives a SIGINT or SIGTERM -// signal. This makes it impossible to shut-down message based architectures -// like zactors. This method lets you switch off break handling. The default -// nonstop setting is off (false). -CZMQ_EXPORT void - zloop_set_nonstop (zloop_t *self, bool nonstop); - -// Start the reactor. Takes control of the thread and returns when the 0MQ -// context is terminated or the process is interrupted, or any event handler -// returns -1. Event handlers may register new sockets and timers, and -// cancel sockets. Returns 0 if interrupted, -1 if canceled by a handler. -CZMQ_EXPORT int - zloop_start (zloop_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zloop_test (bool verbose); - -// @end - - -// Deprecated method aliases -#define zloop_set_tolerant(s,i) zloop_poller_set_tolerant(s,i) - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zmonitor.h b/phonelibs/zmq/aarch64-linux/include/zmonitor.h deleted file mode 100644 index b490bcb1a0..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zmonitor.h +++ /dev/null @@ -1,73 +0,0 @@ -/* ========================================================================= - zmonitor - socket event monitor - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZMONITOR_H_INCLUDED__ -#define __ZMONITOR_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// Create new zmonitor actor instance to monitor a zsock_t socket: -// -// zactor_t *monitor = zactor_new (zmonitor, mysocket); -// -// Destroy zmonitor instance. -// -// zactor_destroy (&monitor); -// -// Enable verbose logging of commands and activity. -// -// zstr_send (monitor, "VERBOSE"); -// -// Listen to monitor event type (zero or types, ending in NULL): -// zstr_sendx (monitor, "LISTEN", type, ..., NULL); -// -// Events: -// CONNECTED -// CONNECT_DELAYED -// CONNECT_RETRIED -// LISTENING -// BIND_FAILED -// ACCEPTED -// ACCEPT_FAILED -// CLOSED -// CLOSE_FAILED -// DISCONNECTED -// MONITOR_STOPPED -// ALL -// -// Start monitor; after this, any further LISTEN commands are ignored. -// -// zstr_send (monitor, "START"); -// zsock_wait (monitor); -// -// Receive next monitor event: -// -// zmsg_t *msg = zmsg_recv (monitor); -// -// This is the zmonitor constructor as a zactor_fn; the argument can be -// a zactor_t, zsock_t, or libzmq void * socket: -CZMQ_EXPORT void - zmonitor (zsock_t *pipe, void *sock); - -// Selftest -CZMQ_EXPORT void - zmonitor_test (bool verbose); -// @end -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zmq.h b/phonelibs/zmq/aarch64-linux/include/zmq.h deleted file mode 100644 index 21a78eb657..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zmq.h +++ /dev/null @@ -1,643 +0,0 @@ -/* - Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file - - This file is part of libzmq, the ZeroMQ core engine in C++. - - libzmq is free software; you can redistribute it and/or modify it under - the terms of the GNU Lesser General Public License (LGPL) as published - by the Free Software Foundation; either version 3 of the License, or - (at your option) any later version. - - As a special exception, the Contributors give you permission to link - this library with independent modules to produce an executable, - regardless of the license terms of these independent modules, and to - copy and distribute the resulting executable under terms of your choice, - provided that you also meet, for each linked independent module, the - terms and conditions of the license of that module. An independent - module is a module which is not derived from or based on this library. - If you modify this library, you must extend this exception to your - version of the library. - - libzmq is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public - License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . - - ************************************************************************* - NOTE to contributors. This file comprises the principal public contract - for ZeroMQ API users. Any change to this file supplied in a stable - release SHOULD not break existing applications. - In practice this means that the value of constants must not change, and - that old values may not be reused for new constants. - ************************************************************************* -*/ - -#ifndef __ZMQ_H_INCLUDED__ -#define __ZMQ_H_INCLUDED__ - -/* Version macros for compile-time API version detection */ -#define ZMQ_VERSION_MAJOR 4 -#define ZMQ_VERSION_MINOR 2 -#define ZMQ_VERSION_PATCH 2 - -#define ZMQ_MAKE_VERSION(major, minor, patch) \ - ((major) * 10000 + (minor) * 100 + (patch)) -#define ZMQ_VERSION \ - ZMQ_MAKE_VERSION(ZMQ_VERSION_MAJOR, ZMQ_VERSION_MINOR, ZMQ_VERSION_PATCH) - -#ifdef __cplusplus -extern "C" { -#endif - -#if !defined _WIN32_WCE -#include -#endif -#include -#include -#if defined _WIN32 -// Set target version to Windows Server 2008, Windows Vista or higher. -// Windows XP (0x0501) is supported but without client & server socket types. -#ifndef _WIN32_WINNT -#define _WIN32_WINNT 0x0600 -#endif - -#ifdef __MINGW32__ -// Require Windows XP or higher with MinGW for getaddrinfo(). -#if(_WIN32_WINNT >= 0x0600) -#else -#undef _WIN32_WINNT -#define _WIN32_WINNT 0x0600 -#endif -#endif -#include -#endif - -/* Handle DSO symbol visibility */ -#if defined _WIN32 -# if defined ZMQ_STATIC -# define ZMQ_EXPORT -# elif defined DLL_EXPORT -# define ZMQ_EXPORT __declspec(dllexport) -# else -# define ZMQ_EXPORT __declspec(dllimport) -# endif -#else -# if defined __SUNPRO_C || defined __SUNPRO_CC -# define ZMQ_EXPORT __global -# elif (defined __GNUC__ && __GNUC__ >= 4) || defined __INTEL_COMPILER -# define ZMQ_EXPORT __attribute__ ((visibility("default"))) -# else -# define ZMQ_EXPORT -# endif -#endif - -/* Define integer types needed for event interface */ -#define ZMQ_DEFINED_STDINT 1 -#if defined ZMQ_HAVE_SOLARIS || defined ZMQ_HAVE_OPENVMS -# include -#elif defined _MSC_VER && _MSC_VER < 1600 -# ifndef int32_t - typedef __int32 int32_t; -# endif -# ifndef uint16_t - typedef unsigned __int16 uint16_t; -# endif -# ifndef uint8_t - typedef unsigned __int8 uint8_t; -# endif -#else -# include -#endif - -// 32-bit AIX's pollfd struct members are called reqevents and rtnevents so it -// defines compatibility macros for them. Need to include that header first to -// stop build failures since zmq_pollset_t defines them as events and revents. -#ifdef ZMQ_HAVE_AIX - #include -#endif - - -/******************************************************************************/ -/* 0MQ errors. */ -/******************************************************************************/ - -/* A number random enough not to collide with different errno ranges on */ -/* different OSes. The assumption is that error_t is at least 32-bit type. */ -#define ZMQ_HAUSNUMERO 156384712 - -/* On Windows platform some of the standard POSIX errnos are not defined. */ -#ifndef ENOTSUP -#define ENOTSUP (ZMQ_HAUSNUMERO + 1) -#endif -#ifndef EPROTONOSUPPORT -#define EPROTONOSUPPORT (ZMQ_HAUSNUMERO + 2) -#endif -#ifndef ENOBUFS -#define ENOBUFS (ZMQ_HAUSNUMERO + 3) -#endif -#ifndef ENETDOWN -#define ENETDOWN (ZMQ_HAUSNUMERO + 4) -#endif -#ifndef EADDRINUSE -#define EADDRINUSE (ZMQ_HAUSNUMERO + 5) -#endif -#ifndef EADDRNOTAVAIL -#define EADDRNOTAVAIL (ZMQ_HAUSNUMERO + 6) -#endif -#ifndef ECONNREFUSED -#define ECONNREFUSED (ZMQ_HAUSNUMERO + 7) -#endif -#ifndef EINPROGRESS -#define EINPROGRESS (ZMQ_HAUSNUMERO + 8) -#endif -#ifndef ENOTSOCK -#define ENOTSOCK (ZMQ_HAUSNUMERO + 9) -#endif -#ifndef EMSGSIZE -#define EMSGSIZE (ZMQ_HAUSNUMERO + 10) -#endif -#ifndef EAFNOSUPPORT -#define EAFNOSUPPORT (ZMQ_HAUSNUMERO + 11) -#endif -#ifndef ENETUNREACH -#define ENETUNREACH (ZMQ_HAUSNUMERO + 12) -#endif -#ifndef ECONNABORTED -#define ECONNABORTED (ZMQ_HAUSNUMERO + 13) -#endif -#ifndef ECONNRESET -#define ECONNRESET (ZMQ_HAUSNUMERO + 14) -#endif -#ifndef ENOTCONN -#define ENOTCONN (ZMQ_HAUSNUMERO + 15) -#endif -#ifndef ETIMEDOUT -#define ETIMEDOUT (ZMQ_HAUSNUMERO + 16) -#endif -#ifndef EHOSTUNREACH -#define EHOSTUNREACH (ZMQ_HAUSNUMERO + 17) -#endif -#ifndef ENETRESET -#define ENETRESET (ZMQ_HAUSNUMERO + 18) -#endif - -/* Native 0MQ error codes. */ -#define EFSM (ZMQ_HAUSNUMERO + 51) -#define ENOCOMPATPROTO (ZMQ_HAUSNUMERO + 52) -#define ETERM (ZMQ_HAUSNUMERO + 53) -#define EMTHREAD (ZMQ_HAUSNUMERO + 54) - -/* This function retrieves the errno as it is known to 0MQ library. The goal */ -/* of this function is to make the code 100% portable, including where 0MQ */ -/* compiled with certain CRT library (on Windows) is linked to an */ -/* application that uses different CRT library. */ -ZMQ_EXPORT int zmq_errno (void); - -/* Resolves system errors and 0MQ errors to human-readable string. */ -ZMQ_EXPORT const char *zmq_strerror (int errnum); - -/* Run-time API version detection */ -ZMQ_EXPORT void zmq_version (int *major, int *minor, int *patch); - -/******************************************************************************/ -/* 0MQ infrastructure (a.k.a. context) initialisation & termination. */ -/******************************************************************************/ - -/* Context options */ -#define ZMQ_IO_THREADS 1 -#define ZMQ_MAX_SOCKETS 2 -#define ZMQ_SOCKET_LIMIT 3 -#define ZMQ_THREAD_PRIORITY 3 -#define ZMQ_THREAD_SCHED_POLICY 4 -#define ZMQ_MAX_MSGSZ 5 - -/* Default for new contexts */ -#define ZMQ_IO_THREADS_DFLT 1 -#define ZMQ_MAX_SOCKETS_DFLT 1023 -#define ZMQ_THREAD_PRIORITY_DFLT -1 -#define ZMQ_THREAD_SCHED_POLICY_DFLT -1 - -ZMQ_EXPORT void *zmq_ctx_new (void); -ZMQ_EXPORT int zmq_ctx_term (void *context); -ZMQ_EXPORT int zmq_ctx_shutdown (void *context); -ZMQ_EXPORT int zmq_ctx_set (void *context, int option, int optval); -ZMQ_EXPORT int zmq_ctx_get (void *context, int option); - -/* Old (legacy) API */ -ZMQ_EXPORT void *zmq_init (int io_threads); -ZMQ_EXPORT int zmq_term (void *context); -ZMQ_EXPORT int zmq_ctx_destroy (void *context); - - -/******************************************************************************/ -/* 0MQ message definition. */ -/******************************************************************************/ - -/* Some architectures, like sparc64 and some variants of aarch64, enforce pointer - * alignment and raise sigbus on violations. Make sure applications allocate - * zmq_msg_t on addresses aligned on a pointer-size boundary to avoid this issue. - */ -typedef struct zmq_msg_t { -#if defined (__GNUC__) || defined ( __INTEL_COMPILER) || \ - (defined (__SUNPRO_C) && __SUNPRO_C >= 0x590) || \ - (defined (__SUNPRO_CC) && __SUNPRO_CC >= 0x590) - unsigned char _ [64] __attribute__ ((aligned (sizeof (void *)))); -#elif defined (_MSC_VER) && (defined (_M_X64) || defined (_M_ARM64)) - __declspec (align (8)) unsigned char _ [64]; -#elif defined (_MSC_VER) && (defined (_M_IX86) || defined (_M_ARM_ARMV7VE)) - __declspec (align (4)) unsigned char _ [64]; -#else - unsigned char _ [64]; -#endif -} zmq_msg_t; - -typedef void (zmq_free_fn) (void *data, void *hint); - -ZMQ_EXPORT int zmq_msg_init (zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_init_size (zmq_msg_t *msg, size_t size); -ZMQ_EXPORT int zmq_msg_init_data (zmq_msg_t *msg, void *data, - size_t size, zmq_free_fn *ffn, void *hint); -ZMQ_EXPORT int zmq_msg_send (zmq_msg_t *msg, void *s, int flags); -ZMQ_EXPORT int zmq_msg_recv (zmq_msg_t *msg, void *s, int flags); -ZMQ_EXPORT int zmq_msg_close (zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_move (zmq_msg_t *dest, zmq_msg_t *src); -ZMQ_EXPORT int zmq_msg_copy (zmq_msg_t *dest, zmq_msg_t *src); -ZMQ_EXPORT void *zmq_msg_data (zmq_msg_t *msg); -ZMQ_EXPORT size_t zmq_msg_size (zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_more (zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_get (zmq_msg_t *msg, int property); -ZMQ_EXPORT int zmq_msg_set (zmq_msg_t *msg, int property, int optval); -ZMQ_EXPORT const char *zmq_msg_gets (zmq_msg_t *msg, const char *property); - -/******************************************************************************/ -/* 0MQ socket definition. */ -/******************************************************************************/ - -/* Socket types. */ -#define ZMQ_PAIR 0 -#define ZMQ_PUB 1 -#define ZMQ_SUB 2 -#define ZMQ_REQ 3 -#define ZMQ_REP 4 -#define ZMQ_DEALER 5 -#define ZMQ_ROUTER 6 -#define ZMQ_PULL 7 -#define ZMQ_PUSH 8 -#define ZMQ_XPUB 9 -#define ZMQ_XSUB 10 -#define ZMQ_STREAM 11 - -/* Deprecated aliases */ -#define ZMQ_XREQ ZMQ_DEALER -#define ZMQ_XREP ZMQ_ROUTER - -/* Socket options. */ -#define ZMQ_AFFINITY 4 -#define ZMQ_IDENTITY 5 -#define ZMQ_SUBSCRIBE 6 -#define ZMQ_UNSUBSCRIBE 7 -#define ZMQ_RATE 8 -#define ZMQ_RECOVERY_IVL 9 -#define ZMQ_SNDBUF 11 -#define ZMQ_RCVBUF 12 -#define ZMQ_RCVMORE 13 -#define ZMQ_FD 14 -#define ZMQ_EVENTS 15 -#define ZMQ_TYPE 16 -#define ZMQ_LINGER 17 -#define ZMQ_RECONNECT_IVL 18 -#define ZMQ_BACKLOG 19 -#define ZMQ_RECONNECT_IVL_MAX 21 -#define ZMQ_MAXMSGSIZE 22 -#define ZMQ_SNDHWM 23 -#define ZMQ_RCVHWM 24 -#define ZMQ_MULTICAST_HOPS 25 -#define ZMQ_RCVTIMEO 27 -#define ZMQ_SNDTIMEO 28 -#define ZMQ_LAST_ENDPOINT 32 -#define ZMQ_ROUTER_MANDATORY 33 -#define ZMQ_TCP_KEEPALIVE 34 -#define ZMQ_TCP_KEEPALIVE_CNT 35 -#define ZMQ_TCP_KEEPALIVE_IDLE 36 -#define ZMQ_TCP_KEEPALIVE_INTVL 37 -#define ZMQ_IMMEDIATE 39 -#define ZMQ_XPUB_VERBOSE 40 -#define ZMQ_ROUTER_RAW 41 -#define ZMQ_IPV6 42 -#define ZMQ_MECHANISM 43 -#define ZMQ_PLAIN_SERVER 44 -#define ZMQ_PLAIN_USERNAME 45 -#define ZMQ_PLAIN_PASSWORD 46 -#define ZMQ_CURVE_SERVER 47 -#define ZMQ_CURVE_PUBLICKEY 48 -#define ZMQ_CURVE_SECRETKEY 49 -#define ZMQ_CURVE_SERVERKEY 50 -#define ZMQ_PROBE_ROUTER 51 -#define ZMQ_REQ_CORRELATE 52 -#define ZMQ_REQ_RELAXED 53 -#define ZMQ_CONFLATE 54 -#define ZMQ_ZAP_DOMAIN 55 -#define ZMQ_ROUTER_HANDOVER 56 -#define ZMQ_TOS 57 -#define ZMQ_CONNECT_RID 61 -#define ZMQ_GSSAPI_SERVER 62 -#define ZMQ_GSSAPI_PRINCIPAL 63 -#define ZMQ_GSSAPI_SERVICE_PRINCIPAL 64 -#define ZMQ_GSSAPI_PLAINTEXT 65 -#define ZMQ_HANDSHAKE_IVL 66 -#define ZMQ_SOCKS_PROXY 68 -#define ZMQ_XPUB_NODROP 69 -#define ZMQ_BLOCKY 70 -#define ZMQ_XPUB_MANUAL 71 -#define ZMQ_XPUB_WELCOME_MSG 72 -#define ZMQ_STREAM_NOTIFY 73 -#define ZMQ_INVERT_MATCHING 74 -#define ZMQ_HEARTBEAT_IVL 75 -#define ZMQ_HEARTBEAT_TTL 76 -#define ZMQ_HEARTBEAT_TIMEOUT 77 -#define ZMQ_XPUB_VERBOSER 78 -#define ZMQ_CONNECT_TIMEOUT 79 -#define ZMQ_TCP_MAXRT 80 -#define ZMQ_THREAD_SAFE 81 -#define ZMQ_MULTICAST_MAXTPDU 84 -#define ZMQ_VMCI_BUFFER_SIZE 85 -#define ZMQ_VMCI_BUFFER_MIN_SIZE 86 -#define ZMQ_VMCI_BUFFER_MAX_SIZE 87 -#define ZMQ_VMCI_CONNECT_TIMEOUT 88 -#define ZMQ_USE_FD 89 - -/* Message options */ -#define ZMQ_MORE 1 -#define ZMQ_SHARED 3 - -/* Send/recv options. */ -#define ZMQ_DONTWAIT 1 -#define ZMQ_SNDMORE 2 - -/* Security mechanisms */ -#define ZMQ_NULL 0 -#define ZMQ_PLAIN 1 -#define ZMQ_CURVE 2 -#define ZMQ_GSSAPI 3 - -/* RADIO-DISH protocol */ -#define ZMQ_GROUP_MAX_LENGTH 15 - -/* Deprecated options and aliases */ -#define ZMQ_TCP_ACCEPT_FILTER 38 -#define ZMQ_IPC_FILTER_PID 58 -#define ZMQ_IPC_FILTER_UID 59 -#define ZMQ_IPC_FILTER_GID 60 -#define ZMQ_IPV4ONLY 31 -#define ZMQ_DELAY_ATTACH_ON_CONNECT ZMQ_IMMEDIATE -#define ZMQ_NOBLOCK ZMQ_DONTWAIT -#define ZMQ_FAIL_UNROUTABLE ZMQ_ROUTER_MANDATORY -#define ZMQ_ROUTER_BEHAVIOR ZMQ_ROUTER_MANDATORY - -/* Deprecated Message options */ -#define ZMQ_SRCFD 2 - -/******************************************************************************/ -/* 0MQ socket events and monitoring */ -/******************************************************************************/ - -/* Socket transport events (TCP, IPC and TIPC only) */ - -#define ZMQ_EVENT_CONNECTED 0x0001 -#define ZMQ_EVENT_CONNECT_DELAYED 0x0002 -#define ZMQ_EVENT_CONNECT_RETRIED 0x0004 -#define ZMQ_EVENT_LISTENING 0x0008 -#define ZMQ_EVENT_BIND_FAILED 0x0010 -#define ZMQ_EVENT_ACCEPTED 0x0020 -#define ZMQ_EVENT_ACCEPT_FAILED 0x0040 -#define ZMQ_EVENT_CLOSED 0x0080 -#define ZMQ_EVENT_CLOSE_FAILED 0x0100 -#define ZMQ_EVENT_DISCONNECTED 0x0200 -#define ZMQ_EVENT_MONITOR_STOPPED 0x0400 -#define ZMQ_EVENT_ALL 0xFFFF - -ZMQ_EXPORT void *zmq_socket (void *, int type); -ZMQ_EXPORT int zmq_close (void *s); -ZMQ_EXPORT int zmq_setsockopt (void *s, int option, const void *optval, - size_t optvallen); -ZMQ_EXPORT int zmq_getsockopt (void *s, int option, void *optval, - size_t *optvallen); -ZMQ_EXPORT int zmq_bind (void *s, const char *addr); -ZMQ_EXPORT int zmq_connect (void *s, const char *addr); -ZMQ_EXPORT int zmq_unbind (void *s, const char *addr); -ZMQ_EXPORT int zmq_disconnect (void *s, const char *addr); -ZMQ_EXPORT int zmq_send (void *s, const void *buf, size_t len, int flags); -ZMQ_EXPORT int zmq_send_const (void *s, const void *buf, size_t len, int flags); -ZMQ_EXPORT int zmq_recv (void *s, void *buf, size_t len, int flags); -ZMQ_EXPORT int zmq_socket_monitor (void *s, const char *addr, int events); - - -/******************************************************************************/ -/* I/O multiplexing. */ -/******************************************************************************/ - -#define ZMQ_POLLIN 1 -#define ZMQ_POLLOUT 2 -#define ZMQ_POLLERR 4 -#define ZMQ_POLLPRI 8 - -typedef struct zmq_pollitem_t -{ - void *socket; -#if defined _WIN32 - SOCKET fd; -#else - int fd; -#endif - short events; - short revents; -} zmq_pollitem_t; - -#define ZMQ_POLLITEMS_DFLT 16 - -ZMQ_EXPORT int zmq_poll (zmq_pollitem_t *items, int nitems, long timeout); - -/******************************************************************************/ -/* Message proxying */ -/******************************************************************************/ - -ZMQ_EXPORT int zmq_proxy (void *frontend, void *backend, void *capture); -ZMQ_EXPORT int zmq_proxy_steerable (void *frontend, void *backend, void *capture, void *control); - -/******************************************************************************/ -/* Probe library capabilities */ -/******************************************************************************/ - -#define ZMQ_HAS_CAPABILITIES 1 -ZMQ_EXPORT int zmq_has (const char *capability); - -/* Deprecated aliases */ -#define ZMQ_STREAMER 1 -#define ZMQ_FORWARDER 2 -#define ZMQ_QUEUE 3 - -/* Deprecated methods */ -ZMQ_EXPORT int zmq_device (int type, void *frontend, void *backend); -ZMQ_EXPORT int zmq_sendmsg (void *s, zmq_msg_t *msg, int flags); -ZMQ_EXPORT int zmq_recvmsg (void *s, zmq_msg_t *msg, int flags); -struct iovec; -ZMQ_EXPORT int zmq_sendiov (void *s, struct iovec *iov, size_t count, int flags); -ZMQ_EXPORT int zmq_recviov (void *s, struct iovec *iov, size_t *count, int flags); - -/******************************************************************************/ -/* Encryption functions */ -/******************************************************************************/ - -/* Encode data with Z85 encoding. Returns encoded data */ -ZMQ_EXPORT char *zmq_z85_encode (char *dest, const uint8_t *data, size_t size); - -/* Decode data with Z85 encoding. Returns decoded data */ -ZMQ_EXPORT uint8_t *zmq_z85_decode (uint8_t *dest, const char *string); - -/* Generate z85-encoded public and private keypair with tweetnacl/libsodium. */ -/* Returns 0 on success. */ -ZMQ_EXPORT int zmq_curve_keypair (char *z85_public_key, char *z85_secret_key); - -/* Derive the z85-encoded public key from the z85-encoded secret key. */ -/* Returns 0 on success. */ -ZMQ_EXPORT int zmq_curve_public (char *z85_public_key, const char *z85_secret_key); - -/******************************************************************************/ -/* Atomic utility methods */ -/******************************************************************************/ - -ZMQ_EXPORT void *zmq_atomic_counter_new (void); -ZMQ_EXPORT void zmq_atomic_counter_set (void *counter, int value); -ZMQ_EXPORT int zmq_atomic_counter_inc (void *counter); -ZMQ_EXPORT int zmq_atomic_counter_dec (void *counter); -ZMQ_EXPORT int zmq_atomic_counter_value (void *counter); -ZMQ_EXPORT void zmq_atomic_counter_destroy (void **counter_p); - - -/******************************************************************************/ -/* These functions are not documented by man pages -- use at your own risk. */ -/* If you need these to be part of the formal ZMQ API, then (a) write a man */ -/* page, and (b) write a test case in tests. */ -/******************************************************************************/ - -/* Helper functions are used by perf tests so that they don't have to care */ -/* about minutiae of time-related functions on different OS platforms. */ - -/* Starts the stopwatch. Returns the handle to the watch. */ -ZMQ_EXPORT void *zmq_stopwatch_start (void); - -/* Stops the stopwatch. Returns the number of microseconds elapsed since */ -/* the stopwatch was started. */ -ZMQ_EXPORT unsigned long zmq_stopwatch_stop (void *watch_); - -/* Sleeps for specified number of seconds. */ -ZMQ_EXPORT void zmq_sleep (int seconds_); - -typedef void (zmq_thread_fn) (void*); - -/* Start a thread. Returns a handle to the thread. */ -ZMQ_EXPORT void *zmq_threadstart (zmq_thread_fn* func, void* arg); - -/* Wait for thread to complete then free up resources. */ -ZMQ_EXPORT void zmq_threadclose (void* thread); - - -/******************************************************************************/ -/* These functions are DRAFT and disabled in stable releases, and subject to */ -/* change at ANY time until declared stable. */ -/******************************************************************************/ - -#ifdef ZMQ_BUILD_DRAFT_API - -/* DRAFT Socket types. */ -#define ZMQ_SERVER 12 -#define ZMQ_CLIENT 13 -#define ZMQ_RADIO 14 -#define ZMQ_DISH 15 -#define ZMQ_GATHER 16 -#define ZMQ_SCATTER 17 -#define ZMQ_DGRAM 18 - -/* DRAFT 0MQ socket events and monitoring */ -#define ZMQ_EVENT_HANDSHAKE_FAILED 0x0800 -#define ZMQ_EVENT_HANDSHAKE_SUCCEED 0x1000 - -/* DRAFT Context options */ -#define ZMQ_MSG_T_SIZE 6 - -/* DRAFT Socket methods. */ -ZMQ_EXPORT int zmq_join (void *s, const char *group); -ZMQ_EXPORT int zmq_leave (void *s, const char *group); - -/* DRAFT Msg methods. */ -ZMQ_EXPORT int zmq_msg_set_routing_id(zmq_msg_t *msg, uint32_t routing_id); -ZMQ_EXPORT uint32_t zmq_msg_routing_id(zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_set_group(zmq_msg_t *msg, const char *group); -ZMQ_EXPORT const char *zmq_msg_group(zmq_msg_t *msg); - -/******************************************************************************/ -/* Poller polling on sockets,fd and thread-safe sockets */ -/******************************************************************************/ - -#define ZMQ_HAVE_POLLER - -typedef struct zmq_poller_event_t -{ - void *socket; -#if defined _WIN32 - SOCKET fd; -#else - int fd; -#endif - void *user_data; - short events; -} zmq_poller_event_t; - -ZMQ_EXPORT void *zmq_poller_new (void); -ZMQ_EXPORT int zmq_poller_destroy (void **poller_p); -ZMQ_EXPORT int zmq_poller_add (void *poller, void *socket, void *user_data, short events); -ZMQ_EXPORT int zmq_poller_modify (void *poller, void *socket, short events); -ZMQ_EXPORT int zmq_poller_remove (void *poller, void *socket); -ZMQ_EXPORT int zmq_poller_wait (void *poller, zmq_poller_event_t *event, long timeout); -ZMQ_EXPORT int zmq_poller_wait_all (void *poller, zmq_poller_event_t *events, int n_events, long timeout); - -#if defined _WIN32 -ZMQ_EXPORT int zmq_poller_add_fd (void *poller, SOCKET fd, void *user_data, short events); -ZMQ_EXPORT int zmq_poller_modify_fd (void *poller, SOCKET fd, short events); -ZMQ_EXPORT int zmq_poller_remove_fd (void *poller, SOCKET fd); -#else -ZMQ_EXPORT int zmq_poller_add_fd (void *poller, int fd, void *user_data, short events); -ZMQ_EXPORT int zmq_poller_modify_fd (void *poller, int fd, short events); -ZMQ_EXPORT int zmq_poller_remove_fd (void *poller, int fd); -#endif - -/******************************************************************************/ -/* Scheduling timers */ -/******************************************************************************/ - -#define ZMQ_HAVE_TIMERS - -typedef void (zmq_timer_fn)(int timer_id, void *arg); - -ZMQ_EXPORT void *zmq_timers_new (void); -ZMQ_EXPORT int zmq_timers_destroy (void **timers_p); -ZMQ_EXPORT int zmq_timers_add (void *timers, size_t interval, zmq_timer_fn handler, void *arg); -ZMQ_EXPORT int zmq_timers_cancel (void *timers, int timer_id); -ZMQ_EXPORT int zmq_timers_set_interval (void *timers, int timer_id, size_t interval); -ZMQ_EXPORT int zmq_timers_reset (void *timers, int timer_id); -ZMQ_EXPORT long zmq_timers_timeout (void *timers); -ZMQ_EXPORT int zmq_timers_execute (void *timers); - -#endif // ZMQ_BUILD_DRAFT_API - - -#undef ZMQ_EXPORT - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zmq_utils.h b/phonelibs/zmq/aarch64-linux/include/zmq_utils.h deleted file mode 100644 index f29638d553..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zmq_utils.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file - - This file is part of libzmq, the ZeroMQ core engine in C++. - - libzmq is free software; you can redistribute it and/or modify it under - the terms of the GNU Lesser General Public License (LGPL) as published - by the Free Software Foundation; either version 3 of the License, or - (at your option) any later version. - - As a special exception, the Contributors give you permission to link - this library with independent modules to produce an executable, - regardless of the license terms of these independent modules, and to - copy and distribute the resulting executable under terms of your choice, - provided that you also meet, for each linked independent module, the - terms and conditions of the license of that module. An independent - module is a module which is not derived from or based on this library. - If you modify this library, you must extend this exception to your - version of the library. - - libzmq is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public - License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . -*/ - -/* This file is deprecated, and all its functionality provided by zmq.h */ -/* Note that -Wpedantic compilation requires GCC to avoid using its custom - extensions such as #warning, hence the trick below. Also, pragmas for - warnings or other messages are not standard, not portable, and not all - compilers even have an equivalent concept. - So in the worst case, this include file is treated as silently empty. */ - -#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) || defined(_MSC_VER) -#if defined(__GNUC__) || defined(__GNUG__) -#pragma GCC diagnostic push -#pragma GCC diagnostic warning "-Wcpp" -#pragma GCC diagnostic ignored "-Werror" -#pragma GCC diagnostic ignored "-Wall" -#endif -#pragma message("Warning: zmq_utils.h is deprecated. All its functionality is provided by zmq.h.") -#if defined(__GNUC__) || defined(__GNUG__) -#pragma GCC diagnostic pop -#endif -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zmsg.h b/phonelibs/zmq/aarch64-linux/include/zmsg.h deleted file mode 100644 index d8a84d1f41..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zmsg.h +++ /dev/null @@ -1,280 +0,0 @@ -/* ========================================================================= - zmsg - working with multipart messages - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZMSG_H_INCLUDED__ -#define __ZMSG_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zmsg.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// Create a new empty message object -CZMQ_EXPORT zmsg_t * - zmsg_new (void); - -// Receive message from socket, returns zmsg_t object or NULL if the recv -// was interrupted. Does a blocking recv. If you want to not block then use -// the zloop class or zmsg_recv_nowait or zmq_poll to check for socket input -// before receiving. -CZMQ_EXPORT zmsg_t * - zmsg_recv (void *source); - -// Load/append an open file into new message, return the message. -// Returns NULL if the message could not be loaded. -CZMQ_EXPORT zmsg_t * - zmsg_load (FILE *file); - -// Decodes a serialized message frame created by zmsg_encode () and returns -// a new zmsg_t object. Returns NULL if the frame was badly formatted or -// there was insufficient memory to work. -CZMQ_EXPORT zmsg_t * - zmsg_decode (zframe_t *frame); - -// Generate a signal message encoding the given status. A signal is a short -// message carrying a 1-byte success/failure code (by convention, 0 means -// OK). Signals are encoded to be distinguishable from "normal" messages. -CZMQ_EXPORT zmsg_t * - zmsg_new_signal (byte status); - -// Destroy a message object and all frames it contains -CZMQ_EXPORT void - zmsg_destroy (zmsg_t **self_p); - -// Send message to destination socket, and destroy the message after sending -// it successfully. If the message has no frames, sends nothing but destroys -// the message anyhow. Nullifies the caller's reference to the message (as -// it is a destructor). -CZMQ_EXPORT int - zmsg_send (zmsg_t **self_p, void *dest); - -// Send message to destination socket as part of a multipart sequence, and -// destroy the message after sending it successfully. Note that after a -// zmsg_sendm, you must call zmsg_send or another method that sends a final -// message part. If the message has no frames, sends nothing but destroys -// the message anyhow. Nullifies the caller's reference to the message (as -// it is a destructor). -CZMQ_EXPORT int - zmsg_sendm (zmsg_t **self_p, void *dest); - -// Return size of message, i.e. number of frames (0 or more). -CZMQ_EXPORT size_t - zmsg_size (zmsg_t *self); - -// Return total size of all frames in message. -CZMQ_EXPORT size_t - zmsg_content_size (zmsg_t *self); - -// Push frame to the front of the message, i.e. before all other frames. -// Message takes ownership of frame, will destroy it when message is sent. -// Returns 0 on success, -1 on error. Deprecates zmsg_push, which did not -// nullify the caller's frame reference. -CZMQ_EXPORT int - zmsg_prepend (zmsg_t *self, zframe_t **frame_p); - -// Add frame to the end of the message, i.e. after all other frames. -// Message takes ownership of frame, will destroy it when message is sent. -// Returns 0 on success. Deprecates zmsg_add, which did not nullify the -// caller's frame reference. -CZMQ_EXPORT int - zmsg_append (zmsg_t *self, zframe_t **frame_p); - -// Remove first frame from message, if any. Returns frame, or NULL. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zmsg_pop (zmsg_t *self); - -// Push block of memory to front of message, as a new frame. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_pushmem (zmsg_t *self, const void *data, size_t size); - -// Add block of memory to the end of the message, as a new frame. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_addmem (zmsg_t *self, const void *data, size_t size); - -// Push string as new frame to front of message. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_pushstr (zmsg_t *self, const char *string); - -// Push string as new frame to end of message. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_addstr (zmsg_t *self, const char *string); - -// Push formatted string as new frame to front of message. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_pushstrf (zmsg_t *self, const char *format, ...) CHECK_PRINTF (2); - -// Push formatted string as new frame to end of message. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_addstrf (zmsg_t *self, const char *format, ...) CHECK_PRINTF (2); - -// Pop frame off front of message, return as fresh string. If there were -// no more frames in the message, returns NULL. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zmsg_popstr (zmsg_t *self); - -// Push encoded message as a new frame. Message takes ownership of -// submessage, so the original is destroyed in this call. Returns 0 on -// success, -1 on error. -CZMQ_EXPORT int - zmsg_addmsg (zmsg_t *self, zmsg_t **msg_p); - -// Remove first submessage from message, if any. Returns zmsg_t, or NULL if -// decoding was not successful. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zmsg_t * - zmsg_popmsg (zmsg_t *self); - -// Remove specified frame from list, if present. Does not destroy frame. -CZMQ_EXPORT void - zmsg_remove (zmsg_t *self, zframe_t *frame); - -// Set cursor to first frame in message. Returns frame, or NULL, if the -// message is empty. Use this to navigate the frames as a list. -CZMQ_EXPORT zframe_t * - zmsg_first (zmsg_t *self); - -// Return the next frame. If there are no more frames, returns NULL. To move -// to the first frame call zmsg_first(). Advances the cursor. -CZMQ_EXPORT zframe_t * - zmsg_next (zmsg_t *self); - -// Return the last frame. If there are no frames, returns NULL. -CZMQ_EXPORT zframe_t * - zmsg_last (zmsg_t *self); - -// Save message to an open file, return 0 if OK, else -1. The message is -// saved as a series of frames, each with length and data. Note that the -// file is NOT guaranteed to be portable between operating systems, not -// versions of CZMQ. The file format is at present undocumented and liable -// to arbitrary change. -CZMQ_EXPORT int - zmsg_save (zmsg_t *self, FILE *file); - -// Serialize multipart message to a single message frame. Use this method -// to send structured messages across transports that do not support -// multipart data. Allocates and returns a new frame containing the -// serialized message. To decode a serialized message frame, use -// zmsg_decode (). -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zmsg_encode (zmsg_t *self); - -// Create copy of message, as new message object. Returns a fresh zmsg_t -// object. If message is null, or memory was exhausted, returns null. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zmsg_t * - zmsg_dup (zmsg_t *self); - -// Send message to zsys log sink (may be stdout, or system facility as -// configured by zsys_set_logstream). -CZMQ_EXPORT void - zmsg_print (zmsg_t *self); - -// Return true if the two messages have the same number of frames and each -// frame in the first message is identical to the corresponding frame in the -// other message. As with zframe_eq, return false if either message is NULL. -CZMQ_EXPORT bool - zmsg_eq (zmsg_t *self, zmsg_t *other); - -// Return signal value, 0 or greater, if message is a signal, -1 if not. -CZMQ_EXPORT int - zmsg_signal (zmsg_t *self); - -// Probe the supplied object, and report if it looks like a zmsg_t. -CZMQ_EXPORT bool - zmsg_is (void *self); - -// Self test of this class. -CZMQ_EXPORT void - zmsg_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Return message routing ID, if the message came from a ZMQ_SERVER socket. -// Else returns zero. -CZMQ_EXPORT uint32_t - zmsg_routing_id (zmsg_t *self); - -// *** Draft method, for development use, may change without warning *** -// Set routing ID on message. This is used if/when the message is sent to a -// ZMQ_SERVER socket. -CZMQ_EXPORT void - zmsg_set_routing_id (zmsg_t *self, uint32_t routing_id); - -#endif // CZMQ_BUILD_DRAFT_API -// @end - - -// DEPRECATED as over-engineered, poor style -// Pop frame off front of message, caller now owns frame -// If next frame is empty, pops and destroys that empty frame. -CZMQ_EXPORT zframe_t * - zmsg_unwrap (zmsg_t *self); - -// DEPRECATED as poor style -- callers should use zloop or zpoller -// Receive message from socket, returns zmsg_t object, or NULL either if -// there was no input waiting, or the recv was interrupted. -CZMQ_EXPORT zmsg_t * - zmsg_recv_nowait (void *source); - -// DEPRECATED as unsafe -- does not nullify frame reference. -// Push frame plus empty frame to front of message, before first frame. -// Message takes ownership of frame, will destroy it when message is sent. -CZMQ_EXPORT void - zmsg_wrap (zmsg_t *self, zframe_t *frame); - -// DEPRECATED - will be removed for next + 1 stable release -// Add frame to the front of the message, i.e. before all other frames. -// Message takes ownership of frame, will destroy it when message is sent. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_push (zmsg_t *self, zframe_t *frame); - -// DEPRECATED - will be removed for next stable release -CZMQ_EXPORT int - zmsg_add (zmsg_t *self, zframe_t *frame); - -// DEPRECATED as inconsistent; breaks principle that logging should all go -// to a single destination. -// Print message to open stream -// Truncates to first 10 frames, for readability. -CZMQ_EXPORT void - zmsg_fprint (zmsg_t *self, FILE *file); - -// Compiler hints -CZMQ_EXPORT int zmsg_addstrf (zmsg_t *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int zmsg_pushstrf (zmsg_t *self, const char *format, ...) CHECK_PRINTF (2); - -#ifdef __cplusplus -} -#endif - -// Deprecated method aliases -#define zmsg_dump(s) zmsg_print(s) -#define zmsg_dump_to_stream(s,F) zmsg_fprint(s,F) - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zpoller.h b/phonelibs/zmq/aarch64-linux/include/zpoller.h deleted file mode 100644 index 3b394c3516..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zpoller.h +++ /dev/null @@ -1,87 +0,0 @@ -/* ========================================================================= - zpoller - trivial socket poller class - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __zpoller_H_INCLUDED__ -#define __zpoller_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zpoller.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Create new poller, specifying zero or more readers. The list of -// readers ends in a NULL. Each reader can be a zsock_t instance, a -// zactor_t instance, a libzmq socket (void *), or a file handle. -CZMQ_EXPORT zpoller_t * - zpoller_new (void *reader, ...); - -// Destroy a poller -CZMQ_EXPORT void - zpoller_destroy (zpoller_t **self_p); - -// Add a reader to be polled. Returns 0 if OK, -1 on failure. The reader may -// be a libzmq void * socket, a zsock_t instance, or a zactor_t instance. -CZMQ_EXPORT int - zpoller_add (zpoller_t *self, void *reader); - -// Remove a reader from the poller; returns 0 if OK, -1 on failure. The reader -// must have been passed during construction, or in an zpoller_add () call. -CZMQ_EXPORT int - zpoller_remove (zpoller_t *self, void *reader); - -// By default the poller stops if the process receives a SIGINT or SIGTERM -// signal. This makes it impossible to shut-down message based architectures -// like zactors. This method lets you switch off break handling. The default -// nonstop setting is off (false). -CZMQ_EXPORT void - zpoller_set_nonstop (zpoller_t *self, bool nonstop); - -// Poll the registered readers for I/O, return first reader that has input. -// The reader will be a libzmq void * socket, or a zsock_t or zactor_t -// instance as specified in zpoller_new/zpoller_add. The timeout should be -// zero or greater, or -1 to wait indefinitely. Socket priority is defined -// by their order in the poll list. If you need a balanced poll, use the low -// level zmq_poll method directly. If the poll call was interrupted (SIGINT), -// or the ZMQ context was destroyed, or the timeout expired, returns NULL. -// You can test the actual exit condition by calling zpoller_expired () and -// zpoller_terminated (). The timeout is in msec. -CZMQ_EXPORT void * - zpoller_wait (zpoller_t *self, int timeout); - -// Return true if the last zpoller_wait () call ended because the timeout -// expired, without any error. -CZMQ_EXPORT bool - zpoller_expired (zpoller_t *self); - -// Return true if the last zpoller_wait () call ended because the process -// was interrupted, or the parent context was destroyed. -CZMQ_EXPORT bool - zpoller_terminated (zpoller_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zpoller_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/phonelibs/zmq/aarch64-linux/include/zproxy.h b/phonelibs/zmq/aarch64-linux/include/zproxy.h deleted file mode 100644 index f672c5e724..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zproxy.h +++ /dev/null @@ -1,111 +0,0 @@ -/* ========================================================================= - zproxy - run a steerable proxy in the background - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZPROXY_H_INCLUDED__ -#define __ZPROXY_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// Create new zproxy actor instance. The proxy switches messages between -// a frontend socket and a backend socket; use the FRONTEND and BACKEND -// commands to configure these: -// -// zactor_t *proxy = zactor_new (zproxy, NULL); -// -// Destroy zproxy instance. This destroys the two sockets and stops any -// message flow between them: -// -// zactor_destroy (&proxy); -// -// Note that all zproxy commands are synchronous, so your application always -// waits for a signal from the actor after each command. -// -// Enable verbose logging of commands and activity: -// -// zstr_send (proxy, "VERBOSE"); -// zsock_wait (proxy); -// -// Specify frontend socket type -- see zsock_type_str () -- and attach to -// endpoints, see zsock_attach (). Note that a proxy socket is always -// serverish: -// -// zstr_sendx (proxy, "FRONTEND", "XSUB", endpoints, NULL); -// zsock_wait (proxy); -// -// Specify backend socket type -- see zsock_type_str () -- and attach to -// endpoints, see zsock_attach (). Note that a proxy socket is always -// serverish: -// -// zstr_sendx (proxy, "BACKEND", "XPUB", endpoints, NULL); -// zsock_wait (proxy); -// -// Capture all proxied messages; these are delivered to the application -// via an inproc PULL socket that you have already bound to the specified -// endpoint: -// -// zstr_sendx (proxy, "CAPTURE", endpoint, NULL); -// zsock_wait (proxy); -// -// Pause the proxy. A paused proxy will cease processing messages, causing -// them to be queued up and potentially hit the high-water mark on the -// frontend or backend socket, causing messages to be dropped, or writing -// applications to block: -// -// zstr_sendx (proxy, "PAUSE", NULL); -// zsock_wait (proxy); -// -// Resume the proxy. Note that the proxy starts automatically as soon as it -// has a properly attached frontend and backend socket: -// -// zstr_sendx (proxy, "RESUME", NULL); -// zsock_wait (proxy); -// -// Configure an authentication domain for the "FRONTEND" or "BACKEND" proxy -// socket -- see zsock_set_zap_domain (). Call before binding socket: -// -// zstr_sendx (proxy, "DOMAIN", "FRONTEND", "global", NULL); -// zsock_wait (proxy); -// -// Configure PLAIN authentication for the "FRONTEND" or "BACKEND" proxy -// socket -- see zsock_set_plain_server (). Call before binding socket: -// -// zstr_sendx (proxy, "PLAIN", "BACKEND", NULL); -// zsock_wait (proxy); -// -// Configure CURVE authentication for the "FRONTEND" or "BACKEND" proxy -// socket -- see zsock_set_curve_server () -- specifying both the public and -// secret keys of a certificate as Z85 armored strings -- see -// zcert_public_txt () and zcert_secret_txt (). Call before binding socket: -// -// zstr_sendx (proxy, "CURVE", "FRONTEND", public_txt, secret_txt, NULL); -// zsock_wait (proxy); -// -// This is the zproxy constructor as a zactor_fn; the argument is a -// character string specifying frontend and backend socket types as two -// uppercase strings separated by a hyphen: -CZMQ_EXPORT void - zproxy (zsock_t *pipe, void *unused); - -// Selftest -CZMQ_EXPORT void - zproxy_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zrex.h b/phonelibs/zmq/aarch64-linux/include/zrex.h deleted file mode 100644 index 8b50618a34..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zrex.h +++ /dev/null @@ -1,82 +0,0 @@ -/* ========================================================================= - zrex - work with regular expressions - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZREX_H_INCLUDED__ -#define __ZREX_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// Constructor. Optionally, sets an expression against which we can match -// text and capture hits. If there is an error in the expression, reports -// zrex_valid() as false and provides the error in zrex_strerror(). If you -// set a pattern, you can call zrex_matches() to test it against text. -CZMQ_EXPORT zrex_t * - zrex_new (const char *expression); - -// Destructor -CZMQ_EXPORT void - zrex_destroy (zrex_t **self_p); - -// Return true if the expression was valid and compiled without errors. -CZMQ_EXPORT bool - zrex_valid (zrex_t *self); - -// Return the error message generated during compilation of the expression. -CZMQ_EXPORT const char * - zrex_strerror (zrex_t *self); - -// Returns true if the text matches the previously compiled expression. -// Use this method to compare one expression against many strings. -CZMQ_EXPORT bool - zrex_matches (zrex_t *self, const char *text); - -// Returns true if the text matches the supplied expression. Use this -// method to compare one string against several expressions. -CZMQ_EXPORT bool - zrex_eq (zrex_t *self, const char *text, const char *expression); - -// Returns number of hits from last zrex_matches or zrex_eq. If the text -// matched, returns 1 plus the number of capture groups. If the text did -// not match, returns zero. To retrieve individual capture groups, call -// zrex_hit (). -CZMQ_EXPORT int - zrex_hits (zrex_t *self); - -// Returns the Nth capture group from the last expression match, where -// N is 0 to the value returned by zrex_hits(). Capture group 0 is the -// whole matching string. Sequence 1 is the first capture group, if any, -// and so on. -CZMQ_EXPORT const char * - zrex_hit (zrex_t *self, uint index); - -// Fetches hits into string variables provided by caller; this makes for -// nicer code than accessing hits by index. Caller should not modify nor -// free the returned values. Returns number of strings returned. This -// method starts at hit 1, i.e. first capture group, as hit 0 is always -// the original matched string. -CZMQ_EXPORT int - zrex_fetch (zrex_t *self, const char **string_p, ...); - -// Self test of this class -CZMQ_EXPORT void - zrex_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zsock.h b/phonelibs/zmq/aarch64-linux/include/zsock.h deleted file mode 100644 index 9ab060d6a3..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zsock.h +++ /dev/null @@ -1,1159 +0,0 @@ -/* ========================================================================= - zsock - high-level socket API that hides libzmq contexts and sockets - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZSOCK_H_INCLUDED__ -#define __ZSOCK_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// This interface includes some smart constructors, which create sockets with -// additional set-up. In all of these, the endpoint is NULL, or starts with -// '@' (bind) or '>' (connect). Multiple endpoints are allowed, separated by -// commas. If endpoint does not start with '@' or '>', default action depends -// on socket type. - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zsock.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// Create a new socket. Returns the new socket, or NULL if the new socket -// could not be created. Note that the symbol zsock_new (and other -// constructors/destructors for zsock) are redirected to the *_checked -// variant, enabling intelligent socket leak detection. This can have -// performance implications if you use a LOT of sockets. To turn off this -// redirection behaviour, define ZSOCK_NOCHECK. -CZMQ_EXPORT zsock_t * - zsock_new (int type); - -// Create a PUB socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_pub (const char *endpoint); - -// Create a SUB socket, and optionally subscribe to some prefix string. Default -// action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_sub (const char *endpoint, const char *subscribe); - -// Create a REQ socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_req (const char *endpoint); - -// Create a REP socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_rep (const char *endpoint); - -// Create a DEALER socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_dealer (const char *endpoint); - -// Create a ROUTER socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_router (const char *endpoint); - -// Create a PUSH socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_push (const char *endpoint); - -// Create a PULL socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_pull (const char *endpoint); - -// Create an XPUB socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_xpub (const char *endpoint); - -// Create an XSUB socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_xsub (const char *endpoint); - -// Create a PAIR socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_pair (const char *endpoint); - -// Create a STREAM socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_stream (const char *endpoint); - -// Destroy the socket. You must use this for any socket created via the -// zsock_new method. -CZMQ_EXPORT void - zsock_destroy (zsock_t **self_p); - -// Bind a socket to a formatted endpoint. For tcp:// endpoints, supports -// ephemeral ports, if you specify the port number as "*". By default -// zsock uses the IANA designated range from C000 (49152) to FFFF (65535). -// To override this range, follow the "*" with "[first-last]". Either or -// both first and last may be empty. To bind to a random port within the -// range, use "!" in place of "*". -// -// Examples: -// tcp://127.0.0.1:* bind to first free port from C000 up -// tcp://127.0.0.1:! bind to random port from C000 to FFFF -// tcp://127.0.0.1:*[60000-] bind to first free port from 60000 up -// tcp://127.0.0.1:![-60000] bind to random port from C000 to 60000 -// tcp://127.0.0.1:![55000-55999] -// bind to random port from 55000 to 55999 -// -// On success, returns the actual port number used, for tcp:// endpoints, -// and 0 for other transports. On failure, returns -1. Note that when using -// ephemeral ports, a port may be reused by different services without -// clients being aware. Protocols that run on ephemeral ports should take -// this into account. -CZMQ_EXPORT int - zsock_bind (zsock_t *self, const char *format, ...) CHECK_PRINTF (2); - -// Returns last bound endpoint, if any. -CZMQ_EXPORT const char * - zsock_endpoint (zsock_t *self); - -// Unbind a socket from a formatted endpoint. -// Returns 0 if OK, -1 if the endpoint was invalid or the function -// isn't supported. -CZMQ_EXPORT int - zsock_unbind (zsock_t *self, const char *format, ...) CHECK_PRINTF (2); - -// Connect a socket to a formatted endpoint -// Returns 0 if OK, -1 if the endpoint was invalid. -CZMQ_EXPORT int - zsock_connect (zsock_t *self, const char *format, ...) CHECK_PRINTF (2); - -// Disconnect a socket from a formatted endpoint -// Returns 0 if OK, -1 if the endpoint was invalid or the function -// isn't supported. -CZMQ_EXPORT int - zsock_disconnect (zsock_t *self, const char *format, ...) CHECK_PRINTF (2); - -// Attach a socket to zero or more endpoints. If endpoints is not null, -// parses as list of ZeroMQ endpoints, separated by commas, and prefixed by -// '@' (to bind the socket) or '>' (to connect the socket). Returns 0 if all -// endpoints were valid, or -1 if there was a syntax error. If the endpoint -// does not start with '@' or '>', the serverish argument defines whether -// it is used to bind (serverish = true) or connect (serverish = false). -CZMQ_EXPORT int - zsock_attach (zsock_t *self, const char *endpoints, bool serverish); - -// Returns socket type as printable constant string. -CZMQ_EXPORT const char * - zsock_type_str (zsock_t *self); - -// Send a 'picture' message to the socket (or actor). The picture is a -// string that defines the type of each frame. This makes it easy to send -// a complex multiframe message in one call. The picture can contain any -// of these characters, each corresponding to one or two arguments: -// -// i = int (signed) -// 1 = uint8_t -// 2 = uint16_t -// 4 = uint32_t -// 8 = uint64_t -// s = char * -// b = byte *, size_t (2 arguments) -// c = zchunk_t * -// f = zframe_t * -// h = zhashx_t * -// U = zuuid_t * -// p = void * (sends the pointer value, only meaningful over inproc) -// m = zmsg_t * (sends all frames in the zmsg) -// z = sends zero-sized frame (0 arguments) -// u = uint (deprecated) -// -// Note that s, b, c, and f are encoded the same way and the choice is -// offered as a convenience to the sender, which may or may not already -// have data in a zchunk or zframe. Does not change or take ownership of -// any arguments. Returns 0 if successful, -1 if sending failed for any -// reason. -CZMQ_EXPORT int - zsock_send (void *self, const char *picture, ...); - -// Send a 'picture' message to the socket (or actor). This is a va_list -// version of zsock_send (), so please consult its documentation for the -// details. -CZMQ_EXPORT int - zsock_vsend (void *self, const char *picture, va_list argptr); - -// Receive a 'picture' message to the socket (or actor). See zsock_send for -// the format and meaning of the picture. Returns the picture elements into -// a series of pointers as provided by the caller: -// -// i = int * (stores signed integer) -// 4 = uint32_t * (stores 32-bit unsigned integer) -// 8 = uint64_t * (stores 64-bit unsigned integer) -// s = char ** (allocates new string) -// b = byte **, size_t * (2 arguments) (allocates memory) -// c = zchunk_t ** (creates zchunk) -// f = zframe_t ** (creates zframe) -// U = zuuid_t * (creates a zuuid with the data) -// h = zhashx_t ** (creates zhashx) -// p = void ** (stores pointer) -// m = zmsg_t ** (creates a zmsg with the remaing frames) -// z = null, asserts empty frame (0 arguments) -// u = uint * (stores unsigned integer, deprecated) -// -// Note that zsock_recv creates the returned objects, and the caller must -// destroy them when finished with them. The supplied pointers do not need -// to be initialized. Returns 0 if successful, or -1 if it failed to recv -// a message, in which case the pointers are not modified. When message -// frames are truncated (a short message), sets return values to zero/null. -// If an argument pointer is NULL, does not store any value (skips it). -// An 'n' picture matches an empty frame; if the message does not match, -// the method will return -1. -CZMQ_EXPORT int - zsock_recv (void *self, const char *picture, ...); - -// Receive a 'picture' message from the socket (or actor). This is a -// va_list version of zsock_recv (), so please consult its documentation -// for the details. -CZMQ_EXPORT int - zsock_vrecv (void *self, const char *picture, va_list argptr); - -// Send a binary encoded 'picture' message to the socket (or actor). This -// method is similar to zsock_send, except the arguments are encoded in a -// binary format that is compatible with zproto, and is designed to reduce -// memory allocations. The pattern argument is a string that defines the -// type of each argument. Supports these argument types: -// -// pattern C type zproto type: -// 1 uint8_t type = "number" size = "1" -// 2 uint16_t type = "number" size = "2" -// 4 uint32_t type = "number" size = "3" -// 8 uint64_t type = "number" size = "4" -// s char *, 0-255 chars type = "string" -// S char *, 0-2^32-1 chars type = "longstr" -// c zchunk_t * type = "chunk" -// f zframe_t * type = "frame" -// u zuuid_t * type = "uuid" -// m zmsg_t * type = "msg" -// p void *, sends pointer value, only over inproc -// -// Does not change or take ownership of any arguments. Returns 0 if -// successful, -1 if sending failed for any reason. -CZMQ_EXPORT int - zsock_bsend (void *self, const char *picture, ...); - -// Receive a binary encoded 'picture' message from the socket (or actor). -// This method is similar to zsock_recv, except the arguments are encoded -// in a binary format that is compatible with zproto, and is designed to -// reduce memory allocations. The pattern argument is a string that defines -// the type of each argument. See zsock_bsend for the supported argument -// types. All arguments must be pointers; this call sets them to point to -// values held on a per-socket basis. -// Note that zsock_brecv creates the returned objects, and the caller must -// destroy them when finished with them. The supplied pointers do not need -// to be initialized. Returns 0 if successful, or -1 if it failed to read -// a message. -CZMQ_EXPORT int - zsock_brecv (void *self, const char *picture, ...); - -// Set socket to use unbounded pipes (HWM=0); use this in cases when you are -// totally certain the message volume can fit in memory. This method works -// across all versions of ZeroMQ. Takes a polymorphic socket reference. -CZMQ_EXPORT void - zsock_set_unbounded (void *self); - -// Send a signal over a socket. A signal is a short message carrying a -// success/failure code (by convention, 0 means OK). Signals are encoded -// to be distinguishable from "normal" messages. Accepts a zsock_t or a -// zactor_t argument, and returns 0 if successful, -1 if the signal could -// not be sent. Takes a polymorphic socket reference. -CZMQ_EXPORT int - zsock_signal (void *self, byte status); - -// Wait on a signal. Use this to coordinate between threads, over pipe -// pairs. Blocks until the signal is received. Returns -1 on error, 0 or -// greater on success. Accepts a zsock_t or a zactor_t as argument. -// Takes a polymorphic socket reference. -CZMQ_EXPORT int - zsock_wait (void *self); - -// If there is a partial message still waiting on the socket, remove and -// discard it. This is useful when reading partial messages, to get specific -// message types. -CZMQ_EXPORT void - zsock_flush (void *self); - -// Probe the supplied object, and report if it looks like a zsock_t. -// Takes a polymorphic socket reference. -CZMQ_EXPORT bool - zsock_is (void *self); - -// Probe the supplied reference. If it looks like a zsock_t instance, return -// the underlying libzmq socket handle; else if it looks like a file -// descriptor, return NULL; else if it looks like a libzmq socket handle, -// return the supplied value. Takes a polymorphic socket reference. -CZMQ_EXPORT void * - zsock_resolve (void *self); - -// Get socket option `heartbeat_ivl`. -// Available from libzmq 4.2.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_heartbeat_ivl (void *self); - -// Set socket option `heartbeat_ivl`. -// Available from libzmq 4.2.0. -CZMQ_EXPORT void - zsock_set_heartbeat_ivl (void *self, int heartbeat_ivl); - -// Get socket option `heartbeat_ttl`. -// Available from libzmq 4.2.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_heartbeat_ttl (void *self); - -// Set socket option `heartbeat_ttl`. -// Available from libzmq 4.2.0. -CZMQ_EXPORT void - zsock_set_heartbeat_ttl (void *self, int heartbeat_ttl); - -// Get socket option `heartbeat_timeout`. -// Available from libzmq 4.2.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_heartbeat_timeout (void *self); - -// Set socket option `heartbeat_timeout`. -// Available from libzmq 4.2.0. -CZMQ_EXPORT void - zsock_set_heartbeat_timeout (void *self, int heartbeat_timeout); - -// Get socket option `use_fd`. -// Available from libzmq 4.2.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_use_fd (void *self); - -// Set socket option `use_fd`. -// Available from libzmq 4.2.0. -CZMQ_EXPORT void - zsock_set_use_fd (void *self, int use_fd); - -// Set socket option `xpub_manual`. -// Available from libzmq 4.2.0. -CZMQ_EXPORT void - zsock_set_xpub_manual (void *self, int xpub_manual); - -// Set socket option `xpub_welcome_msg`. -// Available from libzmq 4.2.0. -CZMQ_EXPORT void - zsock_set_xpub_welcome_msg (void *self, const char *xpub_welcome_msg); - -// Set socket option `stream_notify`. -// Available from libzmq 4.2.0. -CZMQ_EXPORT void - zsock_set_stream_notify (void *self, int stream_notify); - -// Get socket option `invert_matching`. -// Available from libzmq 4.2.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_invert_matching (void *self); - -// Set socket option `invert_matching`. -// Available from libzmq 4.2.0. -CZMQ_EXPORT void - zsock_set_invert_matching (void *self, int invert_matching); - -// Set socket option `xpub_verboser`. -// Available from libzmq 4.2.0. -CZMQ_EXPORT void - zsock_set_xpub_verboser (void *self, int xpub_verboser); - -// Get socket option `connect_timeout`. -// Available from libzmq 4.2.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_connect_timeout (void *self); - -// Set socket option `connect_timeout`. -// Available from libzmq 4.2.0. -CZMQ_EXPORT void - zsock_set_connect_timeout (void *self, int connect_timeout); - -// Get socket option `tcp_maxrt`. -// Available from libzmq 4.2.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_tcp_maxrt (void *self); - -// Set socket option `tcp_maxrt`. -// Available from libzmq 4.2.0. -CZMQ_EXPORT void - zsock_set_tcp_maxrt (void *self, int tcp_maxrt); - -// Get socket option `thread_safe`. -// Available from libzmq 4.2.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_thread_safe (void *self); - -// Get socket option `multicast_maxtpdu`. -// Available from libzmq 4.2.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_multicast_maxtpdu (void *self); - -// Set socket option `multicast_maxtpdu`. -// Available from libzmq 4.2.0. -CZMQ_EXPORT void - zsock_set_multicast_maxtpdu (void *self, int multicast_maxtpdu); - -// Get socket option `vmci_buffer_size`. -// Available from libzmq 4.2.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_vmci_buffer_size (void *self); - -// Set socket option `vmci_buffer_size`. -// Available from libzmq 4.2.0. -CZMQ_EXPORT void - zsock_set_vmci_buffer_size (void *self, int vmci_buffer_size); - -// Get socket option `vmci_buffer_min_size`. -// Available from libzmq 4.2.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_vmci_buffer_min_size (void *self); - -// Set socket option `vmci_buffer_min_size`. -// Available from libzmq 4.2.0. -CZMQ_EXPORT void - zsock_set_vmci_buffer_min_size (void *self, int vmci_buffer_min_size); - -// Get socket option `vmci_buffer_max_size`. -// Available from libzmq 4.2.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_vmci_buffer_max_size (void *self); - -// Set socket option `vmci_buffer_max_size`. -// Available from libzmq 4.2.0. -CZMQ_EXPORT void - zsock_set_vmci_buffer_max_size (void *self, int vmci_buffer_max_size); - -// Get socket option `vmci_connect_timeout`. -// Available from libzmq 4.2.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_vmci_connect_timeout (void *self); - -// Set socket option `vmci_connect_timeout`. -// Available from libzmq 4.2.0. -CZMQ_EXPORT void - zsock_set_vmci_connect_timeout (void *self, int vmci_connect_timeout); - -// Get socket option `tos`. -// Available from libzmq 4.1.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_tos (void *self); - -// Set socket option `tos`. -// Available from libzmq 4.1.0. -CZMQ_EXPORT void - zsock_set_tos (void *self, int tos); - -// Set socket option `router_handover`. -// Available from libzmq 4.1.0. -CZMQ_EXPORT void - zsock_set_router_handover (void *self, int router_handover); - -// Set socket option `connect_rid`. -// Available from libzmq 4.1.0. -CZMQ_EXPORT void - zsock_set_connect_rid (void *self, const char *connect_rid); - -// Set socket option `connect_rid` from 32-octet binary -// Available from libzmq 4.1.0. -CZMQ_EXPORT void - zsock_set_connect_rid_bin (void *self, const byte *connect_rid); - -// Get socket option `handshake_ivl`. -// Available from libzmq 4.1.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_handshake_ivl (void *self); - -// Set socket option `handshake_ivl`. -// Available from libzmq 4.1.0. -CZMQ_EXPORT void - zsock_set_handshake_ivl (void *self, int handshake_ivl); - -// Get socket option `socks_proxy`. -// Available from libzmq 4.1.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_socks_proxy (void *self); - -// Set socket option `socks_proxy`. -// Available from libzmq 4.1.0. -CZMQ_EXPORT void - zsock_set_socks_proxy (void *self, const char *socks_proxy); - -// Set socket option `xpub_nodrop`. -// Available from libzmq 4.1.0. -CZMQ_EXPORT void - zsock_set_xpub_nodrop (void *self, int xpub_nodrop); - -// Set socket option `router_mandatory`. -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_router_mandatory (void *self, int router_mandatory); - -// Set socket option `probe_router`. -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_probe_router (void *self, int probe_router); - -// Set socket option `req_relaxed`. -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_req_relaxed (void *self, int req_relaxed); - -// Set socket option `req_correlate`. -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_req_correlate (void *self, int req_correlate); - -// Set socket option `conflate`. -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_conflate (void *self, int conflate); - -// Get socket option `zap_domain`. -// Available from libzmq 4.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_zap_domain (void *self); - -// Set socket option `zap_domain`. -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_zap_domain (void *self, const char *zap_domain); - -// Get socket option `mechanism`. -// Available from libzmq 4.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_mechanism (void *self); - -// Get socket option `plain_server`. -// Available from libzmq 4.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_plain_server (void *self); - -// Set socket option `plain_server`. -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_plain_server (void *self, int plain_server); - -// Get socket option `plain_username`. -// Available from libzmq 4.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_plain_username (void *self); - -// Set socket option `plain_username`. -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_plain_username (void *self, const char *plain_username); - -// Get socket option `plain_password`. -// Available from libzmq 4.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_plain_password (void *self); - -// Set socket option `plain_password`. -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_plain_password (void *self, const char *plain_password); - -// Get socket option `curve_server`. -// Available from libzmq 4.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_curve_server (void *self); - -// Set socket option `curve_server`. -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_curve_server (void *self, int curve_server); - -// Get socket option `curve_publickey`. -// Available from libzmq 4.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_curve_publickey (void *self); - -// Set socket option `curve_publickey`. -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_curve_publickey (void *self, const char *curve_publickey); - -// Set socket option `curve_publickey` from 32-octet binary -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_curve_publickey_bin (void *self, const byte *curve_publickey); - -// Get socket option `curve_secretkey`. -// Available from libzmq 4.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_curve_secretkey (void *self); - -// Set socket option `curve_secretkey`. -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_curve_secretkey (void *self, const char *curve_secretkey); - -// Set socket option `curve_secretkey` from 32-octet binary -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_curve_secretkey_bin (void *self, const byte *curve_secretkey); - -// Get socket option `curve_serverkey`. -// Available from libzmq 4.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_curve_serverkey (void *self); - -// Set socket option `curve_serverkey`. -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_curve_serverkey (void *self, const char *curve_serverkey); - -// Set socket option `curve_serverkey` from 32-octet binary -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_curve_serverkey_bin (void *self, const byte *curve_serverkey); - -// Get socket option `gssapi_server`. -// Available from libzmq 4.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_gssapi_server (void *self); - -// Set socket option `gssapi_server`. -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_gssapi_server (void *self, int gssapi_server); - -// Get socket option `gssapi_plaintext`. -// Available from libzmq 4.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_gssapi_plaintext (void *self); - -// Set socket option `gssapi_plaintext`. -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_gssapi_plaintext (void *self, int gssapi_plaintext); - -// Get socket option `gssapi_principal`. -// Available from libzmq 4.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_gssapi_principal (void *self); - -// Set socket option `gssapi_principal`. -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_gssapi_principal (void *self, const char *gssapi_principal); - -// Get socket option `gssapi_service_principal`. -// Available from libzmq 4.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_gssapi_service_principal (void *self); - -// Set socket option `gssapi_service_principal`. -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_gssapi_service_principal (void *self, const char *gssapi_service_principal); - -// Get socket option `ipv6`. -// Available from libzmq 4.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_ipv6 (void *self); - -// Set socket option `ipv6`. -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_ipv6 (void *self, int ipv6); - -// Get socket option `immediate`. -// Available from libzmq 4.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_immediate (void *self); - -// Set socket option `immediate`. -// Available from libzmq 4.0.0. -CZMQ_EXPORT void - zsock_set_immediate (void *self, int immediate); - -// Get socket option `type`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_type (void *self); - -// Get socket option `sndhwm`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_sndhwm (void *self); - -// Set socket option `sndhwm`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_sndhwm (void *self, int sndhwm); - -// Get socket option `rcvhwm`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_rcvhwm (void *self); - -// Set socket option `rcvhwm`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_rcvhwm (void *self, int rcvhwm); - -// Get socket option `affinity`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_affinity (void *self); - -// Set socket option `affinity`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_affinity (void *self, int affinity); - -// Set socket option `subscribe`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_subscribe (void *self, const char *subscribe); - -// Set socket option `unsubscribe`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_unsubscribe (void *self, const char *unsubscribe); - -// Get socket option `identity`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_identity (void *self); - -// Set socket option `identity`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_identity (void *self, const char *identity); - -// Get socket option `rate`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_rate (void *self); - -// Set socket option `rate`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_rate (void *self, int rate); - -// Get socket option `recovery_ivl`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_recovery_ivl (void *self); - -// Set socket option `recovery_ivl`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_recovery_ivl (void *self, int recovery_ivl); - -// Get socket option `sndbuf`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_sndbuf (void *self); - -// Set socket option `sndbuf`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_sndbuf (void *self, int sndbuf); - -// Get socket option `rcvbuf`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_rcvbuf (void *self); - -// Set socket option `rcvbuf`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_rcvbuf (void *self, int rcvbuf); - -// Get socket option `linger`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_linger (void *self); - -// Set socket option `linger`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_linger (void *self, int linger); - -// Get socket option `reconnect_ivl`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_reconnect_ivl (void *self); - -// Set socket option `reconnect_ivl`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_reconnect_ivl (void *self, int reconnect_ivl); - -// Get socket option `reconnect_ivl_max`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_reconnect_ivl_max (void *self); - -// Set socket option `reconnect_ivl_max`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_reconnect_ivl_max (void *self, int reconnect_ivl_max); - -// Get socket option `backlog`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_backlog (void *self); - -// Set socket option `backlog`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_backlog (void *self, int backlog); - -// Get socket option `maxmsgsize`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_maxmsgsize (void *self); - -// Set socket option `maxmsgsize`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_maxmsgsize (void *self, int maxmsgsize); - -// Get socket option `multicast_hops`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_multicast_hops (void *self); - -// Set socket option `multicast_hops`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_multicast_hops (void *self, int multicast_hops); - -// Get socket option `rcvtimeo`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_rcvtimeo (void *self); - -// Set socket option `rcvtimeo`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_rcvtimeo (void *self, int rcvtimeo); - -// Get socket option `sndtimeo`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_sndtimeo (void *self); - -// Set socket option `sndtimeo`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_sndtimeo (void *self, int sndtimeo); - -// Set socket option `xpub_verbose`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_xpub_verbose (void *self, int xpub_verbose); - -// Get socket option `tcp_keepalive`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_tcp_keepalive (void *self); - -// Set socket option `tcp_keepalive`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_tcp_keepalive (void *self, int tcp_keepalive); - -// Get socket option `tcp_keepalive_idle`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_tcp_keepalive_idle (void *self); - -// Set socket option `tcp_keepalive_idle`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_tcp_keepalive_idle (void *self, int tcp_keepalive_idle); - -// Get socket option `tcp_keepalive_cnt`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_tcp_keepalive_cnt (void *self); - -// Set socket option `tcp_keepalive_cnt`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_tcp_keepalive_cnt (void *self, int tcp_keepalive_cnt); - -// Get socket option `tcp_keepalive_intvl`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_tcp_keepalive_intvl (void *self); - -// Set socket option `tcp_keepalive_intvl`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_tcp_keepalive_intvl (void *self, int tcp_keepalive_intvl); - -// Get socket option `tcp_accept_filter`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_tcp_accept_filter (void *self); - -// Set socket option `tcp_accept_filter`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_tcp_accept_filter (void *self, const char *tcp_accept_filter); - -// Get socket option `rcvmore`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_rcvmore (void *self); - -// Get socket option `fd`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT SOCKET - zsock_fd (void *self); - -// Get socket option `events`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_events (void *self); - -// Get socket option `last_endpoint`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_last_endpoint (void *self); - -// Set socket option `router_raw`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_router_raw (void *self, int router_raw); - -// Get socket option `ipv4only`. -// Available from libzmq 3.0.0. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_ipv4only (void *self); - -// Set socket option `ipv4only`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_ipv4only (void *self, int ipv4only); - -// Set socket option `delay_attach_on_connect`. -// Available from libzmq 3.0.0. -CZMQ_EXPORT void - zsock_set_delay_attach_on_connect (void *self, int delay_attach_on_connect); - -// Self test of this class. -CZMQ_EXPORT void - zsock_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Create a SERVER socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_server (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a CLIENT socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_client (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a RADIO socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_radio (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a DISH socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_dish (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a GATHER socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_gather (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a SCATTER socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_scatter (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Return socket routing ID if any. This returns 0 if the socket is not -// of type ZMQ_SERVER or if no request was already received on it. -CZMQ_EXPORT uint32_t - zsock_routing_id (zsock_t *self); - -// *** Draft method, for development use, may change without warning *** -// Set routing ID on socket. The socket MUST be of type ZMQ_SERVER. -// This will be used when sending messages on the socket via the zsock API. -CZMQ_EXPORT void - zsock_set_routing_id (zsock_t *self, uint32_t routing_id); - -// *** Draft method, for development use, may change without warning *** -// Join a group for the RADIO-DISH pattern. Call only on ZMQ_DISH. -// Returns 0 if OK, -1 if failed. -CZMQ_EXPORT int - zsock_join (void *self, const char *group); - -// *** Draft method, for development use, may change without warning *** -// Leave a group for the RADIO-DISH pattern. Call only on ZMQ_DISH. -// Returns 0 if OK, -1 if failed. -CZMQ_EXPORT int - zsock_leave (void *self, const char *group); - -#endif // CZMQ_BUILD_DRAFT_API -// @end - - -// zsock leak detection - not a part of the official interface to zsock. This -// enables CZMQ to report socket leaks intelligently. -#if defined ZSOCK_NOCHECK - // no checking active - use the above interface methods directly. -#else -# define zsock_new(t) zsock_new_checked((t), __FILE__, __LINE__) -# define zsock_new_pub(e) zsock_new_pub_checked((e), __FILE__, __LINE__) -# define zsock_new_sub(e,s) zsock_new_sub_checked((e), (s), __FILE__, __LINE__) -# define zsock_new_req(e) zsock_new_req_checked((e), __FILE__, __LINE__) -# define zsock_new_rep(e) zsock_new_rep_checked((e), __FILE__, __LINE__) -# define zsock_new_dealer(e) zsock_new_dealer_checked((e), __FILE__, __LINE__) -# define zsock_new_router(e) zsock_new_router_checked((e), __FILE__, __LINE__) -# define zsock_new_pull(e) zsock_new_pull_checked((e), __FILE__, __LINE__) -# define zsock_new_push(e) zsock_new_push_checked((e), __FILE__, __LINE__) -# define zsock_new_xpub(e) zsock_new_xpub_checked((e), __FILE__, __LINE__) -# define zsock_new_xsub(e) zsock_new_xsub_checked((e), __FILE__, __LINE__) -# define zsock_new_pair(e) zsock_new_pair_checked((e), __FILE__, __LINE__) -# define zsock_new_stream(e) zsock_new_stream_checked((e), __FILE__, __LINE__) -# define zsock_destroy(t) zsock_destroy_checked((t), __FILE__, __LINE__) -#endif - -CZMQ_EXPORT zsock_t * - zsock_new_checked (int type, const char *filename, size_t line_nbr); - -CZMQ_EXPORT void - zsock_destroy_checked (zsock_t **self_p, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_pub_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_sub_checked (const char *endpoint, const char *subscribe, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_req_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_rep_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_dealer_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_router_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_push_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_pull_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_xpub_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_xsub_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_pair_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_stream_checked (const char *endpoint, const char *filename, size_t line_nbr); - -#ifdef CZMQ_BUILD_DRAFT_API -CZMQ_EXPORT zsock_t * - zsock_new_server_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_client_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_radio_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_dish_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_gather_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_scatter_checked (const char *endpoint, const char *filename, size_t line_nbr); -#endif // CZMQ_BUILD_DRAFT_API - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zstr.h b/phonelibs/zmq/aarch64-linux/include/zstr.h deleted file mode 100644 index 67f2f852b6..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zstr.h +++ /dev/null @@ -1,110 +0,0 @@ -/* ========================================================================= - zstr - sending and receiving strings - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZSTR_H_INCLUDED__ -#define __ZSTR_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zstr.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// Receive C string from socket. Caller must free returned string using -// zstr_free(). Returns NULL if the context is being terminated or the -// process was interrupted. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zstr_recv (void *source); - -// Receive a series of strings (until NULL) from multipart data. -// Each string is allocated and filled with string data; if there -// are not enough frames, unallocated strings are set to NULL. -// Returns -1 if the message could not be read, else returns the -// number of strings filled, zero or more. Free each returned string -// using zstr_free(). If not enough strings are provided, remaining -// multipart frames in the message are dropped. -CZMQ_EXPORT int - zstr_recvx (void *source, char **string_p, ...); - -// Send a C string to a socket, as a frame. The string is sent without -// trailing null byte; to read this you can use zstr_recv, or a similar -// method that adds a null terminator on the received string. String -// may be NULL, which is sent as "". -CZMQ_EXPORT int - zstr_send (void *dest, const char *string); - -// Send a C string to a socket, as zstr_send(), with a MORE flag, so that -// you can send further strings in the same multi-part message. -CZMQ_EXPORT int - zstr_sendm (void *dest, const char *string); - -// Send a formatted string to a socket. Note that you should NOT use -// user-supplied strings in the format (they may contain '%' which -// will create security holes). -CZMQ_EXPORT int - zstr_sendf (void *dest, const char *format, ...) CHECK_PRINTF (2); - -// Send a formatted string to a socket, as for zstr_sendf(), with a -// MORE flag, so that you can send further strings in the same multi-part -// message. -CZMQ_EXPORT int - zstr_sendfm (void *dest, const char *format, ...) CHECK_PRINTF (2); - -// Send a series of strings (until NULL) as multipart data -// Returns 0 if the strings could be sent OK, or -1 on error. -CZMQ_EXPORT int - zstr_sendx (void *dest, const char *string, ...); - -// Free a provided string, and nullify the parent pointer. Safe to call on -// a null pointer. -CZMQ_EXPORT void - zstr_free (char **string_p); - -// Self test of this class. -CZMQ_EXPORT void - zstr_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Accepts a void pointer and returns a fresh character string. If source -// is null, returns an empty string. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zstr_str (void *source); - -#endif // CZMQ_BUILD_DRAFT_API -// @end - - -// DEPRECATED as poor style -- callers should use zloop or zpoller -// Receive C string from socket, if socket had input ready. Caller must -// free returned string using zstr_free. Returns NULL if there was no input -// waiting, or if the context was terminated. Use zctx_interrupted to exit -// any loop that relies on this method. -CZMQ_EXPORT char * - zstr_recv_nowait (void *source); - -// Compiler hints -CZMQ_EXPORT int zstr_sendf (void *dest, const char *format, ...) CHECK_PRINTF (2); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zsys.h b/phonelibs/zmq/aarch64-linux/include/zsys.h deleted file mode 100644 index 200271d924..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zsys.h +++ /dev/null @@ -1,395 +0,0 @@ -/* ========================================================================= - zsys - system-level methods - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZSYS_H_INCLUDED__ -#define __ZSYS_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -#define UDP_FRAME_MAX 255 // Max size of UDP frame - -// Callback for interrupt signal handler -typedef void (zsys_handler_fn) (int signal_value); - -// Initialize CZMQ zsys layer; this happens automatically when you create -// a socket or an actor; however this call lets you force initialization -// earlier, so e.g. logging is properly set-up before you start working. -// Not threadsafe, so call only from main thread. Safe to call multiple -// times. Returns global CZMQ context. -CZMQ_EXPORT void * - zsys_init (void); - -// Optionally shut down the CZMQ zsys layer; this normally happens automatically -// when the process exits; however this call lets you force a shutdown -// earlier, avoiding any potential problems with atexit() ordering, especially -// with Windows dlls. -CZMQ_EXPORT void - zsys_shutdown (void); - -// Get a new ZMQ socket, automagically creating a ZMQ context if this is -// the first time. Caller is responsible for destroying the ZMQ socket -// before process exits, to avoid a ZMQ deadlock. Note: you should not use -// this method in CZMQ apps, use zsock_new() instead. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT void * - zsys_socket (int type, const char *filename, size_t line_nbr); - -// Destroy/close a ZMQ socket. You should call this for every socket you -// create using zsys_socket(). -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT int - zsys_close (void *handle, const char *filename, size_t line_nbr); - -// Return ZMQ socket name for socket type -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT char * - zsys_sockname (int socktype); - -// Create a pipe, which consists of two PAIR sockets connected over inproc. -// The pipe is configured to use the zsys_pipehwm setting. Returns the -// frontend socket successful, NULL if failed. -CZMQ_EXPORT zsock_t * - zsys_create_pipe (zsock_t **backend_p); - -// Set interrupt handler; this saves the default handlers so that a -// zsys_handler_reset () can restore them. If you call this multiple times -// then the last handler will take affect. If handler_fn is NULL, disables -// default SIGINT/SIGTERM handling in CZMQ. -CZMQ_EXPORT void - zsys_handler_set (zsys_handler_fn *handler_fn); - -// Reset interrupt handler, call this at exit if needed -CZMQ_EXPORT void - zsys_handler_reset (void); - -// Set default interrupt handler, so Ctrl-C or SIGTERM will set -// zsys_interrupted. Idempotent; safe to call multiple times. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT void - zsys_catch_interrupts (void); - -// Return 1 if file exists, else zero -CZMQ_EXPORT bool - zsys_file_exists (const char *filename); - -// Return size of file, or -1 if not found -CZMQ_EXPORT ssize_t - zsys_file_size (const char *filename); - -// Return file modification time. Returns 0 if the file does not exist. -CZMQ_EXPORT time_t - zsys_file_modified (const char *filename); - -// Return file mode; provides at least support for the POSIX S_ISREG(m) -// and S_ISDIR(m) macros and the S_IRUSR and S_IWUSR bits, on all boxes. -// Returns a mode_t cast to int, or -1 in case of error. -CZMQ_EXPORT int - zsys_file_mode (const char *filename); - -// Delete file. Does not complain if the file is absent -CZMQ_EXPORT int - zsys_file_delete (const char *filename); - -// Check if file is 'stable' -CZMQ_EXPORT bool - zsys_file_stable (const char *filename); - -// Create a file path if it doesn't exist. The file path is treated as a -// printf format. -CZMQ_EXPORT int - zsys_dir_create (const char *pathname, ...); - -// Remove a file path if empty; the pathname is treated as printf format. -CZMQ_EXPORT int - zsys_dir_delete (const char *pathname, ...); - -// Move to a specified working directory. Returns 0 if OK, -1 if this failed. -CZMQ_EXPORT int - zsys_dir_change (const char *pathname); - -// Set private file creation mode; all files created from here will be -// readable/writable by the owner only. -CZMQ_EXPORT void - zsys_file_mode_private (void); - -// Reset default file creation mode; all files created from here will use -// process file mode defaults. -CZMQ_EXPORT void - zsys_file_mode_default (void); - -// Return the CZMQ version for run-time API detection; returns version -// number into provided fields, providing reference isn't null in each case. -CZMQ_EXPORT void - zsys_version (int *major, int *minor, int *patch); - -// Format a string using printf formatting, returning a freshly allocated -// buffer. If there was insufficient memory, returns NULL. Free the returned -// string using zstr_free(). -CZMQ_EXPORT char * - zsys_sprintf (const char *format, ...); - -// Format a string with a va_list argument, returning a freshly allocated -// buffer. If there was insufficient memory, returns NULL. Free the returned -// string using zstr_free(). -CZMQ_EXPORT char * - zsys_vprintf (const char *format, va_list argptr); - -// Create UDP beacon socket; if the routable option is true, uses -// multicast (not yet implemented), else uses broadcast. This method -// and related ones might _eventually_ be moved to a zudp class. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT SOCKET - zsys_udp_new (bool routable); - -// Close a UDP socket -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT int - zsys_udp_close (SOCKET handle); - -// Send zframe to UDP socket, return -1 if sending failed due to -// interface having disappeared (happens easily with WiFi) -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT int - zsys_udp_send (SOCKET udpsock, zframe_t *frame, inaddr_t *address, int addrlen); - -// Receive zframe from UDP socket, and set address of peer that sent it -// The peername must be a char [INET_ADDRSTRLEN] array. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT zframe_t * - zsys_udp_recv (SOCKET udpsock, char *peername, int peerlen); - -// Handle an I/O error on some socket operation; will report and die on -// fatal errors, and continue silently on "try again" errors. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT void - zsys_socket_error (const char *reason); - -// Return current host name, for use in public tcp:// endpoints. Caller gets -// a freshly allocated string, should free it using zstr_free(). If the host -// name is not resolvable, returns NULL. -CZMQ_EXPORT char * - zsys_hostname (void); - -// Move the current process into the background. The precise effect depends -// on the operating system. On POSIX boxes, moves to a specified working -// directory (if specified), closes all file handles, reopens stdin, stdout, -// and stderr to the null device, and sets the process to ignore SIGHUP. On -// Windows, does nothing. Returns 0 if OK, -1 if there was an error. -CZMQ_EXPORT int - zsys_daemonize (const char *workdir); - -// Drop the process ID into the lockfile, with exclusive lock, and switch -// the process to the specified group and/or user. Any of the arguments -// may be null, indicating a no-op. Returns 0 on success, -1 on failure. -// Note if you combine this with zsys_daemonize, run after, not before -// that method, or the lockfile will hold the wrong process ID. -CZMQ_EXPORT int - zsys_run_as (const char *lockfile, const char *group, const char *user); - -// Returns true if the underlying libzmq supports CURVE security. -// Uses a heuristic probe according to the version of libzmq being used. -CZMQ_EXPORT bool - zsys_has_curve (void); - -// Configure the number of I/O threads that ZeroMQ will use. A good -// rule of thumb is one thread per gigabit of traffic in or out. The -// default is 1, sufficient for most applications. If the environment -// variable ZSYS_IO_THREADS is defined, that provides the default. -// Note that this method is valid only before any socket is created. -CZMQ_EXPORT void - zsys_set_io_threads (size_t io_threads); - -// Configure the number of sockets that ZeroMQ will allow. The default -// is 1024. The actual limit depends on the system, and you can query it -// by using zsys_socket_limit (). A value of zero means "maximum". -// Note that this method is valid only before any socket is created. -CZMQ_EXPORT void - zsys_set_max_sockets (size_t max_sockets); - -// Return maximum number of ZeroMQ sockets that the system will support. -CZMQ_EXPORT size_t - zsys_socket_limit (void); - -// Configure the maximum allowed size of a message sent. -// The default is INT_MAX. -CZMQ_EXPORT void - zsys_set_max_msgsz (int max_msgsz); - -// Return maximum message size. -CZMQ_EXPORT int - zsys_max_msgsz (void); - -// Configure the default linger timeout in msecs for new zsock instances. -// You can also set this separately on each zsock_t instance. The default -// linger time is zero, i.e. any pending messages will be dropped. If the -// environment variable ZSYS_LINGER is defined, that provides the default. -// Note that process exit will typically be delayed by the linger time. -CZMQ_EXPORT void - zsys_set_linger (size_t linger); - -// Configure the default outgoing pipe limit (HWM) for new zsock instances. -// You can also set this separately on each zsock_t instance. The default -// HWM is 1,000, on all versions of ZeroMQ. If the environment variable -// ZSYS_SNDHWM is defined, that provides the default. Note that a value of -// zero means no limit, i.e. infinite memory consumption. -CZMQ_EXPORT void - zsys_set_sndhwm (size_t sndhwm); - -// Configure the default incoming pipe limit (HWM) for new zsock instances. -// You can also set this separately on each zsock_t instance. The default -// HWM is 1,000, on all versions of ZeroMQ. If the environment variable -// ZSYS_RCVHWM is defined, that provides the default. Note that a value of -// zero means no limit, i.e. infinite memory consumption. -CZMQ_EXPORT void - zsys_set_rcvhwm (size_t rcvhwm); - -// Configure the default HWM for zactor internal pipes; this is set on both -// ends of the pipe, for outgoing messages only (sndhwm). The default HWM is -// 1,000, on all versions of ZeroMQ. If the environment var ZSYS_ACTORHWM is -// defined, that provides the default. Note that a value of zero means no -// limit, i.e. infinite memory consumption. -CZMQ_EXPORT void - zsys_set_pipehwm (size_t pipehwm); - -// Return the HWM for zactor internal pipes. -CZMQ_EXPORT size_t - zsys_pipehwm (void); - -// Configure use of IPv6 for new zsock instances. By default sockets accept -// and make only IPv4 connections. When you enable IPv6, sockets will accept -// and connect to both IPv4 and IPv6 peers. You can override the setting on -// each zsock_t instance. The default is IPv4 only (ipv6 set to 0). If the -// environment variable ZSYS_IPV6 is defined (as 1 or 0), this provides the -// default. Note: has no effect on ZMQ v2. -CZMQ_EXPORT void - zsys_set_ipv6 (int ipv6); - -// Return use of IPv6 for zsock instances. -CZMQ_EXPORT int - zsys_ipv6 (void); - -// Set network interface name to use for broadcasts, particularly zbeacon. -// This lets the interface be configured for test environments where required. -// For example, on Mac OS X, zbeacon cannot bind to 255.255.255.255 which is -// the default when there is no specified interface. If the environment -// variable ZSYS_INTERFACE is set, use that as the default interface name. -// Setting the interface to "*" means "use all available interfaces". -CZMQ_EXPORT void - zsys_set_interface (const char *value); - -// Return network interface to use for broadcasts, or "" if none was set. -CZMQ_EXPORT const char * - zsys_interface (void); - -// Set IPv6 address to use zbeacon socket, particularly for receiving zbeacon. -// This needs to be set IPv6 is enabled as IPv6 can have multiple addresses -// on a given interface. If the environment variable ZSYS_IPV6_ADDRESS is set, -// use that as the default IPv6 address. -CZMQ_EXPORT void - zsys_set_ipv6_address (const char *value); - -// Return IPv6 address to use for zbeacon reception, or "" if none was set. -CZMQ_EXPORT const char * - zsys_ipv6_address (void); - -// Set IPv6 milticast address to use for sending zbeacon messages. This needs -// to be set if IPv6 is enabled. If the environment variable -// ZSYS_IPV6_MCAST_ADDRESS is set, use that as the default IPv6 multicast -// address. -CZMQ_EXPORT void - zsys_set_ipv6_mcast_address (const char *value); - -// Return IPv6 multicast address to use for sending zbeacon, or "" if none was -// set. -CZMQ_EXPORT const char * - zsys_ipv6_mcast_address (void); - -// Configure the automatic use of pre-allocated FDs when creating new sockets. -// If 0 (default), nothing will happen. Else, when a new socket is bound, the -// system API will be used to check if an existing pre-allocated FD with a -// matching port (if TCP) or path (if IPC) exists, and if it does it will be -// set via the ZMQ_USE_FD socket option so that the library will use it -// instead of creating a new socket. -CZMQ_EXPORT void - zsys_set_auto_use_fd (int auto_use_fd); - -// Return use of automatic pre-allocated FDs for zsock instances. -CZMQ_EXPORT int - zsys_auto_use_fd (void); - -// Set log identity, which is a string that prefixes all log messages sent -// by this process. The log identity defaults to the environment variable -// ZSYS_LOGIDENT, if that is set. -CZMQ_EXPORT void - zsys_set_logident (const char *value); - -// Set stream to receive log traffic. By default, log traffic is sent to -// stdout. If you set the stream to NULL, no stream will receive the log -// traffic (it may still be sent to the system facility). -CZMQ_EXPORT void - zsys_set_logstream (FILE *stream); - -// Sends log output to a PUB socket bound to the specified endpoint. To -// collect such log output, create a SUB socket, subscribe to the traffic -// you care about, and connect to the endpoint. Log traffic is sent as a -// single string frame, in the same format as when sent to stdout. The -// log system supports a single sender; multiple calls to this method will -// bind the same sender to multiple endpoints. To disable the sender, call -// this method with a null argument. -CZMQ_EXPORT void - zsys_set_logsender (const char *endpoint); - -// Enable or disable logging to the system facility (syslog on POSIX boxes, -// event log on Windows). By default this is disabled. -CZMQ_EXPORT void - zsys_set_logsystem (bool logsystem); - -// Log error condition - highest priority -CZMQ_EXPORT void - zsys_error (const char *format, ...); - -// Log warning condition - high priority -CZMQ_EXPORT void - zsys_warning (const char *format, ...); - -// Log normal, but significant, condition - normal priority -CZMQ_EXPORT void - zsys_notice (const char *format, ...); - -// Log informational message - low priority -CZMQ_EXPORT void - zsys_info (const char *format, ...); - -// Log debug-level message - lowest priority -CZMQ_EXPORT void - zsys_debug (const char *format, ...); - -// Self test of this class -CZMQ_EXPORT void - zsys_test (bool verbose); - -// Global signal indicator, TRUE when user presses Ctrl-C or the process -// gets a SIGTERM signal. -CZMQ_EXPORT extern volatile int zsys_interrupted; -// Deprecated name for this variable -CZMQ_EXPORT extern volatile int zctx_interrupted; -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/include/zuuid.h b/phonelibs/zmq/aarch64-linux/include/zuuid.h deleted file mode 100644 index afc1104fea..0000000000 --- a/phonelibs/zmq/aarch64-linux/include/zuuid.h +++ /dev/null @@ -1,96 +0,0 @@ -/* ========================================================================= - zuuid - UUID support class - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZUUID_H_INCLUDED__ -#define __ZUUID_H_INCLUDED__ - -#define ZUUID_LEN 16 -#define ZUUID_STR_LEN (ZUUID_LEN * 2) - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zuuid.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Create a new UUID object. -CZMQ_EXPORT zuuid_t * - zuuid_new (void); - -// Create UUID object from supplied ZUUID_LEN-octet value. -CZMQ_EXPORT zuuid_t * - zuuid_new_from (const byte *source); - -// Destroy a specified UUID object. -CZMQ_EXPORT void - zuuid_destroy (zuuid_t **self_p); - -// Set UUID to new supplied ZUUID_LEN-octet value. -CZMQ_EXPORT void - zuuid_set (zuuid_t *self, const byte *source); - -// Set UUID to new supplied string value skipping '-' and '{' '}' -// optional delimiters. Return 0 if OK, else returns -1. -CZMQ_EXPORT int - zuuid_set_str (zuuid_t *self, const char *source); - -// Return UUID binary data. -CZMQ_EXPORT const byte * - zuuid_data (zuuid_t *self); - -// Return UUID binary size -CZMQ_EXPORT size_t - zuuid_size (zuuid_t *self); - -// Returns UUID as string -CZMQ_EXPORT const char * - zuuid_str (zuuid_t *self); - -// Return UUID in the canonical string format: 8-4-4-4-12, in lower -// case. Caller does not modify or free returned value. See -// http://en.wikipedia.org/wiki/Universally_unique_identifier -CZMQ_EXPORT const char * - zuuid_str_canonical (zuuid_t *self); - -// Store UUID blob in target array -CZMQ_EXPORT void - zuuid_export (zuuid_t *self, byte *target); - -// Check if UUID is same as supplied value -CZMQ_EXPORT bool - zuuid_eq (zuuid_t *self, const byte *compare); - -// Check if UUID is different from supplied value -CZMQ_EXPORT bool - zuuid_neq (zuuid_t *self, const byte *compare); - -// Make copy of UUID object; if uuid is null, or memory was exhausted, -// returns null. -CZMQ_EXPORT zuuid_t * - zuuid_dup (zuuid_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zuuid_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64-linux/lib/libczmq.a b/phonelibs/zmq/aarch64-linux/lib/libczmq.a deleted file mode 100644 index ba2b0a3ca6..0000000000 Binary files a/phonelibs/zmq/aarch64-linux/lib/libczmq.a and /dev/null differ diff --git a/phonelibs/zmq/aarch64-linux/lib/libczmq.la b/phonelibs/zmq/aarch64-linux/lib/libczmq.la deleted file mode 100755 index 81ef66bdbb..0000000000 --- a/phonelibs/zmq/aarch64-linux/lib/libczmq.la +++ /dev/null @@ -1,41 +0,0 @@ -# libczmq.la - a libtool library file -# Generated by libtool (GNU libtool) 2.4.2 Debian-2.4.2-1ubuntu1 -# -# Please DO NOT delete this file! -# It is necessary for linking the library. - -# The name that we can dlopen(3). -dlname='libczmq.so.4' - -# Names of this library. -library_names='libczmq.so.4.0.2 libczmq.so.4 libczmq.so' - -# The name of the static archive. -old_library='libczmq.a' - -# Linker flags that can not go in dependency_libs. -inherited_linker_flags=' -pthread' - -# Libraries that this one depends upon. -dependency_libs=' -L/home/nvidia/build/zmq/lib /home/nvidia/build/zmq/lib/libzmq.la -lrt -lpthread -ldl -luuid' - -# Names of additional weak libraries provided by this library -weak_library_names='' - -# Version information for libczmq. -current=4 -age=0 -revision=2 - -# Is this an already installed library? -installed=yes - -# Should we warn about portability when linking against -modules? -shouldnotlink=no - -# Files to dlopen/dlpreopen -dlopen='' -dlpreopen='' - -# Directory that this library needs to be installed in: -libdir='/home/nvidia/build/zmq/lib' diff --git a/phonelibs/zmq/aarch64-linux/lib/libczmq.so b/phonelibs/zmq/aarch64-linux/lib/libczmq.so deleted file mode 120000 index db9aa60f9b..0000000000 --- a/phonelibs/zmq/aarch64-linux/lib/libczmq.so +++ /dev/null @@ -1 +0,0 @@ -libczmq.so.4.0.2 \ No newline at end of file diff --git a/phonelibs/zmq/aarch64-linux/lib/libczmq.so.4 b/phonelibs/zmq/aarch64-linux/lib/libczmq.so.4 deleted file mode 120000 index db9aa60f9b..0000000000 --- a/phonelibs/zmq/aarch64-linux/lib/libczmq.so.4 +++ /dev/null @@ -1 +0,0 @@ -libczmq.so.4.0.2 \ No newline at end of file diff --git a/phonelibs/zmq/aarch64-linux/lib/libczmq.so.4.0.2 b/phonelibs/zmq/aarch64-linux/lib/libczmq.so.4.0.2 deleted file mode 100755 index bb9c2d52eb..0000000000 Binary files a/phonelibs/zmq/aarch64-linux/lib/libczmq.so.4.0.2 and /dev/null differ diff --git a/phonelibs/zmq/aarch64-linux/lib/libzmq.a b/phonelibs/zmq/aarch64-linux/lib/libzmq.a deleted file mode 100644 index 7578d109e4..0000000000 Binary files a/phonelibs/zmq/aarch64-linux/lib/libzmq.a and /dev/null differ diff --git a/phonelibs/zmq/aarch64-linux/lib/libzmq.la b/phonelibs/zmq/aarch64-linux/lib/libzmq.la deleted file mode 100755 index 2aef5c45d0..0000000000 --- a/phonelibs/zmq/aarch64-linux/lib/libzmq.la +++ /dev/null @@ -1,41 +0,0 @@ -# libzmq.la - a libtool library file -# Generated by libtool (GNU libtool) 2.4.2 Debian-2.4.2-1.7ubuntu1 -# -# Please DO NOT delete this file! -# It is necessary for linking the library. - -# The name that we can dlopen(3). -dlname='libzmq.so.5' - -# Names of this library. -library_names='libzmq.so.5.1.2 libzmq.so.5 libzmq.so' - -# The name of the static archive. -old_library='libzmq.a' - -# Linker flags that can not go in dependency_libs. -inherited_linker_flags='' - -# Libraries that this one depends upon. -dependency_libs=' -lrt -lpthread -ldl' - -# Names of additional weak libraries provided by this library -weak_library_names='' - -# Version information for libzmq. -current=6 -age=1 -revision=2 - -# Is this an already installed library? -installed=yes - -# Should we warn about portability when linking against -modules? -shouldnotlink=no - -# Files to dlopen/dlpreopen -dlopen='' -dlpreopen='' - -# Directory that this library needs to be installed in: -libdir='/home/nvidia/build/zmq/lib' diff --git a/phonelibs/zmq/aarch64-linux/lib/libzmq.so b/phonelibs/zmq/aarch64-linux/lib/libzmq.so deleted file mode 120000 index ef44cafc6a..0000000000 --- a/phonelibs/zmq/aarch64-linux/lib/libzmq.so +++ /dev/null @@ -1 +0,0 @@ -libzmq.so.5.1.2 \ No newline at end of file diff --git a/phonelibs/zmq/aarch64-linux/lib/libzmq.so.5 b/phonelibs/zmq/aarch64-linux/lib/libzmq.so.5 deleted file mode 120000 index ef44cafc6a..0000000000 --- a/phonelibs/zmq/aarch64-linux/lib/libzmq.so.5 +++ /dev/null @@ -1 +0,0 @@ -libzmq.so.5.1.2 \ No newline at end of file diff --git a/phonelibs/zmq/aarch64-linux/lib/libzmq.so.5.1.2 b/phonelibs/zmq/aarch64-linux/lib/libzmq.so.5.1.2 deleted file mode 100755 index e96750a8ef..0000000000 Binary files a/phonelibs/zmq/aarch64-linux/lib/libzmq.so.5.1.2 and /dev/null differ diff --git a/phonelibs/zmq/aarch64-linux/lib/pkgconfig/libczmq.pc b/phonelibs/zmq/aarch64-linux/lib/pkgconfig/libczmq.pc deleted file mode 100644 index 7740eec8c0..0000000000 --- a/phonelibs/zmq/aarch64-linux/lib/pkgconfig/libczmq.pc +++ /dev/null @@ -1,24 +0,0 @@ -################################################################################ -# THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY # -# Read the zproject/README.md for information about making permanent changes. # -################################################################################ - -prefix=/home/nvidia/build/zmq -exec_prefix=${prefix} -libdir=${exec_prefix}/lib -includedir=${prefix}/include - -Name: libczmq -Description: The high-level C binding for 0MQ -Version: 4.0.2 - -Requires:libzmq - -Libs: -L${libdir} -lczmq -Cflags: -I${includedir} -Libs.private: -lzmq -luuid - -################################################################################ -# THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY # -# Read the zproject/README.md for information about making permanent changes. # -################################################################################ diff --git a/phonelibs/zmq/aarch64-linux/lib/pkgconfig/libzmq.pc b/phonelibs/zmq/aarch64-linux/lib/pkgconfig/libzmq.pc deleted file mode 100644 index 885271757d..0000000000 --- a/phonelibs/zmq/aarch64-linux/lib/pkgconfig/libzmq.pc +++ /dev/null @@ -1,11 +0,0 @@ -prefix=/home/nvidia/build/zmq -exec_prefix=${prefix} -libdir=${exec_prefix}/lib -includedir=${prefix}/include - -Name: libzmq -Description: 0MQ c++ library -Version: 4.2.2 -Libs: -L${libdir} -lzmq -Libs.private: -lstdc++ -Cflags: -I${includedir} diff --git a/phonelibs/zmq/aarch64-linux/share/man/man1/zmakecert.1 b/phonelibs/zmq/aarch64-linux/share/man/man1/zmakecert.1 deleted file mode 100644 index 7a702496b8..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man1/zmakecert.1 +++ /dev/null @@ -1,73 +0,0 @@ -'\" t -.\" Title: zmakecert -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZMAKECERT" "1" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmakecert \- no title found -.SH "SYNOPSIS" -.sp -.nf -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zmakecert\&.c\*(Aq\&. -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zmakecert\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -Please add \fI@header\fR section in \fI\&./\&.\&./src/zmakecert\&.c\fR\&. -.sp -Please add \fI@discuss\fR section in \fI\&./\&.\&./src/zmakecert\&.c\fR\&. -.SH "EXAMPLE" -.PP -\fBFrom zmakecert_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -Please add \*(Aq@selftest\*(Aq section in \*(Aq\&./\&.\&./src/zmakecert\&.c\*(Aq\&. -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zactor.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zactor.3 deleted file mode 100644 index 481edc396e..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zactor.3 +++ /dev/null @@ -1,127 +0,0 @@ -'\" t -.\" Title: zactor -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZACTOR" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zactor \- simple actor framework -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// Actors get a pipe and arguments from caller -typedef void (zactor_fn) ( - zsock_t *pipe, void *args); - -// Create a new actor passing arbitrary arguments reference\&. -CZMQ_EXPORT zactor_t * - zactor_new (zactor_fn task, void *args); - -// Destroy an actor\&. -CZMQ_EXPORT void - zactor_destroy (zactor_t **self_p); - -// Send a zmsg message to the actor, take ownership of the message -// and destroy when it has been sent\&. -CZMQ_EXPORT int - zactor_send (zactor_t *self, zmsg_t **msg_p); - -// Receive a zmsg message from the actor\&. Returns NULL if the actor -// was interrupted before the message could be received, or if there -// was a timeout on the actor\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zmsg_t * - zactor_recv (zactor_t *self); - -// Probe the supplied object, and report if it looks like a zactor_t\&. -CZMQ_EXPORT bool - zactor_is (void *self); - -// Probe the supplied reference\&. If it looks like a zactor_t instance, -// return the underlying libzmq actor handle; else if it looks like -// a libzmq actor handle, return the supplied value\&. -CZMQ_EXPORT void * - zactor_resolve (void *self); - -// Return the actor\*(Aqs zsock handle\&. Use this when you absolutely need -// to work with the zsock instance rather than the actor\&. -CZMQ_EXPORT zsock_t * - zactor_sock (zactor_t *self); - -// Self test of this class\&. -CZMQ_EXPORT void - zactor_test (bool verbose); - -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zactor\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -The zactor class provides a simple actor framework\&. It replaces the CZMQ zthread class, which had a complex API that did not fit the CLASS standard\&. A CZMQ actor is implemented as a thread plus a PAIR\-PAIR pipe\&. The constructor and destructor are always synchronized, so the caller can be sure all resources are created, and destroyed, when these calls complete\&. (This solves a major problem with zthread, that a caller could not be sure when a child thread had finished\&.) -.sp -A zactor_t instance acts like a zsock_t and you can pass it to any CZMQ method that would take a zsock_t argument, including methods in zframe, zmsg, zstr, and zpoller\&. (zloop somehow escaped and needs catching\&.) -.sp -An actor function MUST call zsock_signal (pipe) when initialized and MUST listen to pipe and exit on $TERM command\&. -.sp -Please add \fI@discuss\fR section in \fI\&./\&.\&./src/zactor\&.c\fR\&. -.SH "EXAMPLE" -.PP -\fBFrom zactor_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -zactor_t *actor = zactor_new (echo_actor, "Hello, World"); -assert (actor); -zstr_sendx (actor, "ECHO", "This is a string", NULL); -char *string = zstr_recv (actor); -assert (streq (string, "This is a string")); -free (string); -zactor_destroy (&actor); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zarmour.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zarmour.3 deleted file mode 100644 index ea80677725..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zarmour.3 +++ /dev/null @@ -1,372 +0,0 @@ -'\" t -.\" Title: zarmour -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZARMOUR" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zarmour \- armoured text encoding and decoding -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -#define ZARMOUR_MODE_BASE64_STD 0 // Standard base 64 -#define ZARMOUR_MODE_BASE64_URL 1 // URL and filename friendly base 64 -#define ZARMOUR_MODE_BASE32_STD 2 // Standard base 32 -#define ZARMOUR_MODE_BASE32_HEX 3 // Extended hex base 32 -#define ZARMOUR_MODE_BASE16 4 // Standard base 16 -#define ZARMOUR_MODE_Z85 5 // Z85 from ZeroMQ RFC 32 - -// Create a new zarmour -CZMQ_EXPORT zarmour_t * - zarmour_new (void); - -// Destroy the zarmour -CZMQ_EXPORT void - zarmour_destroy (zarmour_t **self_p); - -// Encode a stream of bytes into an armoured string\&. Returns the armoured -// string, or NULL if there was insufficient memory available to allocate -// a new string\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zarmour_encode (zarmour_t *self, const byte *data, size_t size); - -// Decode an armoured string into a chunk\&. The decoded output is -// null\-terminated, so it may be treated as a string, if that\*(Aqs what -// it was prior to encoding\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zchunk_t * - zarmour_decode (zarmour_t *self, const char *data); - -// Get the mode property\&. -CZMQ_EXPORT int - zarmour_mode (zarmour_t *self); - -// Get printable string for mode\&. -CZMQ_EXPORT const char * - zarmour_mode_str (zarmour_t *self); - -// Set the mode property\&. -CZMQ_EXPORT void - zarmour_set_mode (zarmour_t *self, int mode); - -// Return true if padding is turned on\&. -CZMQ_EXPORT bool - zarmour_pad (zarmour_t *self); - -// Turn padding on or off\&. Default is on\&. -CZMQ_EXPORT void - zarmour_set_pad (zarmour_t *self, bool pad); - -// Get the padding character\&. -CZMQ_EXPORT char - zarmour_pad_char (zarmour_t *self); - -// Set the padding character\&. -CZMQ_EXPORT void - zarmour_set_pad_char (zarmour_t *self, char pad_char); - -// Return if splitting output into lines is turned on\&. Default is off\&. -CZMQ_EXPORT bool - zarmour_line_breaks (zarmour_t *self); - -// Turn splitting output into lines on or off\&. -CZMQ_EXPORT void - zarmour_set_line_breaks (zarmour_t *self, bool line_breaks); - -// Get the line length used for splitting lines\&. -CZMQ_EXPORT size_t - zarmour_line_length (zarmour_t *self); - -// Set the line length used for splitting lines\&. -CZMQ_EXPORT void - zarmour_set_line_length (zarmour_t *self, size_t line_length); - -// Print properties of object -CZMQ_EXPORT void - zarmour_print (zarmour_t *self); - -// Self test of this class\&. -CZMQ_EXPORT void - zarmour_test (bool verbose); - -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zarmour\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -zarmour \- armoured text encoding and decoding -.sp -The zarmour class implements encoding and decoding of armoured text data\&. The following codecs are implemented: * RFC 4648 (\m[blue]\fBhttp://www\&.ietf\&.org/rfc/rfc4648\&.txt\fR\m[]) \- base64 \- base64url \- base32 \- base32hex \- base16 * Z85 (\m[blue]\fBhttp://rfc\&.zeromq\&.org/spec:32\fR\m[]) All RFC4648 base64 and base32 variants support padding the output\&. The pad character is configurable\&. Default is padding on, with character \fI=\fR\&. Additionally, in some cases (e\&.g\&. MIME), splitting the output into lines of a specific length is required\&. This feature is also supported, though turned off by default\&. The z85 mode does neither padding nor line breaks; it is merely a wrapping of the corresponding libzmq methods\&. Encoding will assert if input length is not divisible by 4 and decoding will assert if input length is not divisible by 5\&. -.SH "EXAMPLE" -.PP -\fBFrom zarmour_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -zarmour_t *self = zarmour_new (); -assert (self); - -int mode = zarmour_mode (self); -assert (mode == ZARMOUR_MODE_BASE64_STD); - -zarmour_set_mode (self, ZARMOUR_MODE_BASE64_URL); -mode = zarmour_mode (self); -assert (mode == ZARMOUR_MODE_BASE64_URL); - -assert (zarmour_pad (self)); -zarmour_set_pad (self, false); -assert (!zarmour_pad (self)); - -assert (zarmour_pad_char (self) == \*(Aq=\*(Aq); -zarmour_set_pad_char (self, \*(Aq!\*(Aq); -assert (zarmour_pad_char (self) == \*(Aq!\*(Aq); -zarmour_set_pad_char (self, \*(Aq=\*(Aq); -assert (zarmour_pad_char (self) == \*(Aq=\*(Aq); - -assert (!zarmour_line_breaks (self)); -zarmour_set_line_breaks (self, true); -assert (zarmour_line_breaks (self)); - -assert (zarmour_line_length (self) == 72); -zarmour_set_line_length (self, 64); -assert (zarmour_line_length (self) == 64); - -// Test against test vectors from RFC4648\&. -zarmour_set_mode (self, ZARMOUR_MODE_BASE64_STD); -if (verbose) - zarmour_print (self); - -s_armour_test (self, "", "", verbose); -s_armour_test (self, "f", "Zg", verbose); -s_armour_test (self, "fo", "Zm8", verbose); -s_armour_test (self, "foo", "Zm9v", verbose); -s_armour_test (self, "foob", "Zm9vYg", verbose); -s_armour_test (self, "fooba", "Zm9vYmE", verbose); -s_armour_test (self, "foobar", "Zm9vYmFy", verbose); -zarmour_set_pad (self, true); -if (verbose) - zarmour_print (self); - -s_armour_test (self, "", "", verbose); -s_armour_test (self, "f", "Zg==", verbose); -s_armour_test (self, "fo", "Zm8=", verbose); -s_armour_test (self, "foo", "Zm9v", verbose); -s_armour_test (self, "foob", "Zm9vYg==", verbose); -s_armour_test (self, "fooba", "Zm9vYmE=", verbose); -s_armour_test (self, "foobar", "Zm9vYmFy", verbose); - -zarmour_set_pad (self, false); -zarmour_set_mode (self, ZARMOUR_MODE_BASE64_URL); -if (verbose) - zarmour_print (self); - -s_armour_test (self, "", "", verbose); -s_armour_test (self, "f", "Zg", verbose); -s_armour_test (self, "fo", "Zm8", verbose); -s_armour_test (self, "foo", "Zm9v", verbose); -s_armour_test (self, "foob", "Zm9vYg", verbose); -s_armour_test (self, "fooba", "Zm9vYmE", verbose); -s_armour_test (self, "foobar", "Zm9vYmFy", verbose); -zarmour_set_pad (self, true); -if (verbose) - zarmour_print (self); - -s_armour_test (self, "", "", verbose); -s_armour_test (self, "f", "Zg==", verbose); -s_armour_test (self, "fo", "Zm8=", verbose); -s_armour_test (self, "foo", "Zm9v", verbose); -s_armour_test (self, "foob", "Zm9vYg==", verbose); -s_armour_test (self, "fooba", "Zm9vYmE=", verbose); -s_armour_test (self, "foobar", "Zm9vYmFy", verbose); - -zarmour_set_pad (self, false); -zarmour_set_mode (self, ZARMOUR_MODE_BASE32_STD); -if (verbose) - zarmour_print (self); - -s_armour_test (self, "", "", verbose); -s_armour_test (self, "f", "MY", verbose); -s_armour_test (self, "fo", "MZXQ", verbose); -s_armour_test (self, "foo", "MZXW6", verbose); -s_armour_test (self, "foob", "MZXW6YQ", verbose); -s_armour_test (self, "fooba", "MZXW6YTB", verbose); -s_armour_test (self, "foobar", "MZXW6YTBOI", verbose); -s_armour_decode (self, "my", "f", verbose); -s_armour_decode (self, "mzxq", "fo", verbose); -s_armour_decode (self, "mzxw6", "foo", verbose); -s_armour_decode (self, "mzxw6yq", "foob", verbose); -s_armour_decode (self, "mzxw6ytb", "fooba", verbose); -s_armour_decode (self, "mzxw6ytboi", "foobar", verbose); -zarmour_set_pad (self, true); -if (verbose) - zarmour_print (self); - -s_armour_test (self, "", "", verbose); -s_armour_test (self, "f", "MY======", verbose); -s_armour_test (self, "fo", "MZXQ====", verbose); -s_armour_test (self, "foo", "MZXW6===", verbose); -s_armour_test (self, "foob", "MZXW6YQ=", verbose); -s_armour_test (self, "fooba", "MZXW6YTB", verbose); -s_armour_test (self, "foobar", "MZXW6YTBOI======", verbose); -s_armour_decode (self, "my======", "f", verbose); -s_armour_decode (self, "mzxq====", "fo", verbose); -s_armour_decode (self, "mzxw6===", "foo", verbose); -s_armour_decode (self, "mzxw6yq=", "foob", verbose); -s_armour_decode (self, "mzxw6ytb", "fooba", verbose); -s_armour_decode (self, "mzxw6ytboi======", "foobar", verbose); - -zarmour_set_pad (self, false); -zarmour_set_mode (self, ZARMOUR_MODE_BASE32_HEX); -if (verbose) - zarmour_print (self); - -s_armour_test (self, "", "", verbose); -s_armour_test (self, "f", "CO", verbose); -s_armour_test (self, "fo", "CPNG", verbose); -s_armour_test (self, "foo", "CPNMU", verbose); -s_armour_test (self, "foob", "CPNMUOG", verbose); -s_armour_test (self, "fooba", "CPNMUOJ1", verbose); -s_armour_test (self, "foobar", "CPNMUOJ1E8", verbose); -s_armour_decode (self, "co", "f", verbose); -s_armour_decode (self, "cpng", "fo", verbose); -s_armour_decode (self, "cpnmu", "foo", verbose); -s_armour_decode (self, "cpnmuog", "foob", verbose); -s_armour_decode (self, "cpnmuoj1", "fooba", verbose); -s_armour_decode (self, "cpnmuoj1e8", "foobar", verbose); -zarmour_set_pad (self, true); -if (verbose) - zarmour_print (self); - -s_armour_test (self, "", "", verbose); -s_armour_test (self, "f", "CO======", verbose); -s_armour_test (self, "fo", "CPNG====", verbose); -s_armour_test (self, "foo", "CPNMU===", verbose); -s_armour_test (self, "foob", "CPNMUOG=", verbose); -s_armour_test (self, "fooba", "CPNMUOJ1", verbose); -s_armour_test (self, "foobar", "CPNMUOJ1E8======", verbose); -s_armour_decode (self, "co======", "f", verbose); -s_armour_decode (self, "cpng====", "fo", verbose); -s_armour_decode (self, "cpnmu===", "foo", verbose); -s_armour_decode (self, "cpnmuog=", "foob", verbose); -s_armour_decode (self, "cpnmuoj1", "fooba", verbose); -s_armour_decode (self, "cpnmuoj1e8======", "foobar", verbose); -zarmour_set_pad (self, true); - -zarmour_set_mode (self, ZARMOUR_MODE_BASE16); -if (verbose) - zarmour_print (self); - -s_armour_test (self, "", "", verbose); -s_armour_test (self, "f", "66", verbose); -s_armour_test (self, "fo", "666F", verbose); -s_armour_test (self, "foo", "666F6F", verbose); -s_armour_test (self, "foob", "666F6F62", verbose); -s_armour_test (self, "fooba", "666F6F6261", verbose); -s_armour_test (self, "foobar", "666F6F626172", verbose); -s_armour_decode (self, "666f", "fo", verbose); -s_armour_decode (self, "666f6f", "foo", verbose); -s_armour_decode (self, "666f6f62", "foob", verbose); -s_armour_decode (self, "666f6f6261", "fooba", verbose); -s_armour_decode (self, "666f6f626172", "foobar", verbose); - -#ifdef _INCLUDE_Z85 -// Z85 test is homemade; using 0, 4 and 8 bytes, with precalculated -// test vectors created with a libzmq test\&. -// \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- - -// Make a fake curve key from hex (base16) string, making sure -// there are no null bytes inside, so we can use our test utility -zarmour_set_mode (self, ZARMOUR_MODE_BASE16); -zarmour_set_line_breaks (self, false); - -zchunk_t *chunk = zarmour_decode (self, - "4E6F87E2FB6EB22A1EF5E257B75D79124949565F0B8B36A878A4F03111C96E0B"); -assert (chunk); - -zarmour_set_mode (self, ZARMOUR_MODE_Z85); // Z85 mode does not support padding or line breaks -zarmour_set_pad (self, false); // so these two are superfluous; -zarmour_set_line_breaks (self, false); // just for consistency -if (verbose) - zarmour_print (self); - -s_armour_test (self, "", "", verbose); -s_armour_test (self, "foob", "w]zP%", verbose); -s_armour_test (self, "foobar!!", "w]zP%vr9Im", verbose); -s_armour_test (self, (char *) zchunk_data (chunk), - "ph+{E}!&X?9}!I]W{sm(nL8@&3Yu{wC+<*\-5Y[[#", verbose); -zchunk_destroy (&chunk); -#endif - -// Armouring longer byte array to test line breaks -zarmour_set_pad (self, true); -zarmour_set_line_breaks (self, true); -byte test_data [256]; -int index; -for (index = 0; index < 256; index++) - test_data [index] = index; - -zarmour_set_mode (self, ZARMOUR_MODE_BASE64_STD); -s_armour_test_long (self, test_data, 256, verbose); -zarmour_set_mode (self, ZARMOUR_MODE_BASE64_URL); -s_armour_test_long (self, test_data, 256, verbose); -zarmour_set_mode (self, ZARMOUR_MODE_BASE32_STD); -s_armour_test_long (self, test_data, 256, verbose); -zarmour_set_mode (self, ZARMOUR_MODE_BASE32_HEX); -s_armour_test_long (self, test_data, 256, verbose); -zarmour_set_mode (self, ZARMOUR_MODE_BASE16); -s_armour_test_long (self, test_data, 256, verbose); -#ifdef _INCLUDE_Z85 -zarmour_set_mode (self, ZARMOUR_MODE_Z85); -s_armour_test_long (self, test_data, 256, verbose); -#endif - -zarmour_destroy (&self); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zauth.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zauth.3 deleted file mode 100644 index b119d13e9a..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zauth.3 +++ /dev/null @@ -1,309 +0,0 @@ -'\" t -.\" Title: zauth -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZAUTH" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zauth \- authentication for ZeroMQ security mechanisms -.SH "SYNOPSIS" -.sp -.nf -#define CURVE_ALLOW_ANY "*" - -// CZMQ v3 API (for use with zsock, not zsocket, which is deprecated)\&. -// -// Create new zauth actor instance\&. This installs authentication on all -// zsock sockets\&. Until you add policies, all incoming NULL connections are -// allowed (classic ZeroMQ behaviour), and all PLAIN and CURVE connections -// are denied: -// -// zactor_t *auth = zactor_new (zauth, NULL); -// -// Destroy zauth instance\&. This removes authentication and allows all -// connections to pass, without authentication: -// -// zactor_destroy (&auth); -// -// Note that all zauth commands are synchronous, so your application always -// waits for a signal from the actor after each command\&. -// -// Enable verbose logging of commands and activity\&. Verbose logging can help -// debug non\-trivial authentication policies: -// -// zstr_send (auth, "VERBOSE"); -// zsock_wait (auth); -// -// Allow (whitelist) a list of IP addresses\&. For NULL, all clients from -// these addresses will be accepted\&. For PLAIN and CURVE, they will be -// allowed to continue with authentication\&. You can call this method -// multiple times to whitelist more IP addresses\&. If you whitelist one -// or more addresses, any non\-whitelisted addresses are treated as -// blacklisted: -// -// zstr_sendx (auth, "ALLOW", "127\&.0\&.0\&.1", "127\&.0\&.0\&.2", NULL); -// zsock_wait (auth); -// -// Deny (blacklist) a list of IP addresses\&. For all security mechanisms, -// this rejects the connection without any further authentication\&. Use -// either a whitelist, or a blacklist, not not both\&. If you define both -// a whitelist and a blacklist, only the whitelist takes effect: -// -// zstr_sendx (auth, "DENY", "192\&.168\&.0\&.1", "192\&.168\&.0\&.2", NULL); -// zsock_wait (auth); -// -// Configure PLAIN authentication using a plain\-text password file\&. You can -// modify the password file at any time; zauth will reload it automatically -// if modified externally: -// -// zstr_sendx (auth, "PLAIN", filename, NULL); -// zsock_wait (auth); -// -// Configure CURVE authentication, using a directory that holds all public -// client certificates, i\&.e\&. their public keys\&. The certificates must be in -// zcert_save format\&. You can add and remove certificates in that directory -// at any time\&. To allow all client keys without checking, specify -// CURVE_ALLOW_ANY for the directory name: -// -// zstr_sendx (auth, "CURVE", directory, NULL); -// zsock_wait (auth); -// -// Configure GSSAPI authentication, using an underlying mechanism (usually -// Kerberos) to establish a secure context and perform mutual authentication: -// -// zstr_sendx (auth, "GSSAPI", NULL); -// zsock_wait (auth); -// -// This is the zauth constructor as a zactor_fn: -CZMQ_EXPORT void - zauth (zsock_t *pipe, void *certstore); - -// Selftest -CZMQ_EXPORT void - zauth_test (bool verbose); -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zauth\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -A zauth actor takes over authentication for all incoming connections in its context\&. You can whitelist or blacklist peers based on IP address, and define policies for securing PLAIN, CURVE, and GSSAPI connections\&. -.sp -This class replaces zauth_v2, and is meant for applications that use the CZMQ v3 API (meaning, zsock)\&. -.SH "EXAMPLE" -.PP -\fBFrom zauth_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Create temporary directory for test files -# define TESTDIR "\&.test_zauth" -zsys_dir_create (TESTDIR); - -// Check there\*(Aqs no authentication -zsock_t *server = zsock_new (ZMQ_PULL); -assert (server); -zsock_t *client = zsock_new (ZMQ_PUSH); -assert (client); -bool success = s_can_connect (&server, &client, true); -assert (success); - -// Install the authenticator -zactor_t *auth = zactor_new (zauth, NULL); -assert (auth); -if (verbose) { - zstr_sendx (auth, "VERBOSE", NULL); - zsock_wait (auth); -} -// Check there\*(Aqs no authentication on a default NULL server -success = s_can_connect (&server, &client, true); -assert (success); - -// When we set a domain on the server, we switch on authentication -// for NULL sockets, but with no policies, the client connection -// will be allowed\&. -zsock_set_zap_domain (server, "global"); -success = s_can_connect (&server, &client, true); -assert (success); - -// Blacklist 127\&.0\&.0\&.1, connection should fail -zsock_set_zap_domain (server, "global"); -zstr_sendx (auth, "DENY", "127\&.0\&.0\&.1", NULL); -zsock_wait (auth); -success = s_can_connect (&server, &client, true); -assert (!success); - -// Whitelist our address, which overrides the blacklist -zsock_set_zap_domain (server, "global"); -zstr_sendx (auth, "ALLOW", "127\&.0\&.0\&.1", NULL); -zsock_wait (auth); -success = s_can_connect (&server, &client, true); -assert (success); - -// Try PLAIN authentication -zsock_set_plain_server (server, 1); -zsock_set_plain_username (client, "admin"); -zsock_set_plain_password (client, "Password"); -success = s_can_connect (&server, &client, true); -assert (!success); - -FILE *password = fopen (TESTDIR "/password\-file", "w"); -assert (password); -fprintf (password, "admin=Password\en"); -fclose (password); -zsock_set_plain_server (server, 1); -zsock_set_plain_username (client, "admin"); -zsock_set_plain_password (client, "Password"); -zstr_sendx (auth, "PLAIN", TESTDIR "/password\-file", NULL); -zsock_wait (auth); -success = s_can_connect (&server, &client, true); -assert (success); - -zsock_set_plain_server (server, 1); -zsock_set_plain_username (client, "admin"); -zsock_set_plain_password (client, "Bogus"); -success = s_can_connect (&server, &client, true); -assert (!success); - -if (zsys_has_curve ()) { - // Try CURVE authentication - // We\*(Aqll create two new certificates and save the client public - // certificate on disk; in a real case we\*(Aqd transfer this securely - // from the client machine to the server machine\&. - zcert_t *server_cert = zcert_new (); - assert (server_cert); - zcert_t *client_cert = zcert_new (); - assert (client_cert); - const char *server_key = zcert_public_txt (server_cert); - - // Test without setting\-up any authentication - zcert_apply (server_cert, server); - zcert_apply (client_cert, client); - zsock_set_curve_server (server, 1); - zsock_set_curve_serverkey (client, server_key); - success = s_can_connect (&server, &client, true); - assert (!success); - - // Test CURVE_ALLOW_ANY - zcert_apply (server_cert, server); - zcert_apply (client_cert, client); - zsock_set_curve_server (server, 1); - zsock_set_curve_serverkey (client, server_key); - zstr_sendx (auth, "CURVE", CURVE_ALLOW_ANY, NULL); - zsock_wait (auth); - success = s_can_connect (&server, &client, true); - assert (success); - - // Test full client authentication using certificates - zcert_set_meta (client_cert, "Hello", "%s", "World!"); - zcert_apply (server_cert, server); - zcert_apply (client_cert, client); - zsock_set_curve_server (server, 1); - zsock_set_curve_serverkey (client, server_key); - zcert_save_public (client_cert, TESTDIR "/mycert\&.txt"); - zstr_sendx (auth, "CURVE", TESTDIR, NULL); - zsock_wait (auth); - success = s_can_connect (&server, &client, false); - assert (success); - -#if (ZMQ_VERSION >= ZMQ_MAKE_VERSION (4, 1, 0)) - // Test send/recv certificate metadata - zframe_t *frame = zframe_recv (server); - assert (frame != NULL); - const char *meta = zframe_meta (frame, "Hello"); - assert (meta != NULL); - assert (streq (meta, "World!")); - zframe_destroy (&frame); - s_renew_sockets(&server, &client); -#endif - - zcert_destroy (&server_cert); - zcert_destroy (&client_cert); - - // Test custom zcertstore - zcertstore_t *certstore = zcertstore_new (NULL); - zcertstore_set_loader (certstore, s_test_loader, NULL, NULL); - zactor_destroy(&auth); - auth = zactor_new (zauth, certstore); - assert (auth); - if (verbose) { - zstr_sendx (auth, "VERBOSE", NULL); - zsock_wait (auth); - } - - byte public_key [32] = { 105, 76, 150, 58, 214, 191, 218, 65, 50, 172, - 131, 188, 247, 211, 136, 170, 227, 26, 57, 170, - 185, 63, 246, 225, 177, 230, 12, 8, 134, 136, - 105, 106 }; - byte secret_key [32] = { 245, 217, 172, 73, 106, 28, 195, 17, 218, 132, - 135, 209, 99, 240, 98, 232, 7, 137, 244, 100, - 242, 23, 29, 114, 70, 223, 83, 1, 113, 207, - 132, 149 }; - zcert_t *shared_cert = zcert_new_from (public_key, secret_key); - assert (shared_cert); - zcert_apply (shared_cert, server); - zcert_apply (shared_cert, client); - zsock_set_curve_server (server, 1); - zsock_set_curve_serverkey (client, "x?T*N/1Y{8goubv{Ts}#&#f}TXJ//DVe#D2HkoLU"); - success = s_can_connect (&server, &client, true); - assert (success); - zcert_destroy (&shared_cert); -} -// Remove the authenticator and check a normal connection works -zactor_destroy (&auth); -success = s_can_connect (&server, &client, true); -assert (success); - -zsock_destroy (&client); -zsock_destroy (&server); - -// Delete all test files -zdir_t *dir = zdir_new (TESTDIR, NULL); -assert (dir); -zdir_remove (dir, true); -zdir_destroy (&dir); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zbeacon.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zbeacon.3 deleted file mode 100644 index 40e3abbac4..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zbeacon.3 +++ /dev/null @@ -1,236 +0,0 @@ -'\" t -.\" Title: zbeacon -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZBEACON" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zbeacon \- LAN discovery and presence -.SH "SYNOPSIS" -.sp -.nf -// Create new zbeacon actor instance: -// -// zactor_t *beacon = zactor_new (zbeacon, NULL); -// -// Destroy zbeacon instance: -// -// zactor_destroy (&beacon); -// -// Enable verbose logging of commands and activity: -// -// zstr_send (beacon, "VERBOSE"); -// -// Configure beacon to run on specified UDP port, and return the name of -// the host, which can be used as endpoint for incoming connections\&. To -// force the beacon to operate on a given interface, set the environment -// variable ZSYS_INTERFACE, or call zsys_set_interface() before creating -// the beacon\&. If the system does not support UDP broadcasts (lacking a -// workable interface), returns an empty hostname: -// -// // Pictures: \*(Aqs\*(Aq = C string, \*(Aqi\*(Aq = int -// zsock_send (beacon, "si", "CONFIGURE", port_number); -// char *hostname = zstr_recv (beacon); -// -// Start broadcasting a beacon at a specified interval in msec\&. The beacon -// data can be at most UDP_FRAME_MAX bytes; this constant is defined in -// zsys\&.h to be 255: -// -// // Pictures: \*(Aqb\*(Aq = byte * data + size_t size -// zsock_send (beacon, "sbi", "PUBLISH", data, size, interval); -// -// Stop broadcasting the beacon: -// -// zstr_sendx (beacon, "SILENCE", NULL); -// -// Start listening to beacons from peers\&. The filter is used to do a prefix -// match on received beacons, to remove junk\&. Note that any received data -// that is identical to our broadcast beacon_data is discarded in any case\&. -// If the filter size is zero, we get all peer beacons: -// -// zsock_send (beacon, "sb", "SUBSCRIBE", filter_data, filter_size); -// -// Stop listening to other peers -// -// zstr_sendx (beacon, "UNSUBSCRIBE", NULL); -// -// Receive next beacon from a peer\&. Received beacons are always a 2\-frame -// message containing the ipaddress of the sender, and then the binary -// beacon data as published by the sender: -// -// zmsg_t *msg = zmsg_recv (beacon); -// -// This is the zbeacon constructor as a zactor_fn: -CZMQ_EXPORT void - zbeacon (zsock_t *pipe, void *unused); - -// Self test of this class -CZMQ_EXPORT void - zbeacon_test (bool verbose); -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zbeacon\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -The zbeacon class implements a peer\-to\-peer discovery service for local networks\&. A beacon can broadcast and/or capture service announcements using UDP messages on the local area network\&. This implementation uses IPv4 UDP broadcasts\&. You can define the format of your outgoing beacons, and set a filter that validates incoming beacons\&. Beacons are sent and received asynchronously in the background\&. -.sp -This class replaces zbeacon_v2, and is meant for applications that use the CZMQ v3 API (meaning, zsock)\&. -.SH "EXAMPLE" -.PP -\fBFrom zbeacon_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Test 1 \- two beacons, one speaking, one listening -// Create speaker beacon to broadcast our service -zactor_t *speaker = zactor_new (zbeacon, NULL); -assert (speaker); -if (verbose) - zstr_sendx (speaker, "VERBOSE", NULL); - -zsock_send (speaker, "si", "CONFIGURE", 9999); -char *hostname = zstr_recv (speaker); -if (!*hostname) { - printf ("OK (skipping test, no UDP broadcasting)\en"); - zactor_destroy (&speaker); - free (hostname); - return; -} -free (hostname); - -// Create listener beacon on port 9999 to lookup service -zactor_t *listener = zactor_new (zbeacon, NULL); -assert (listener); -if (verbose) - zstr_sendx (listener, "VERBOSE", NULL); -zsock_send (listener, "si", "CONFIGURE", 9999); -hostname = zstr_recv (listener); -assert (*hostname); -free (hostname); - -// We will broadcast the magic value 0xCAFE -byte announcement [2] = { 0xCA, 0xFE }; -zsock_send (speaker, "sbi", "PUBLISH", announcement, 2, 100); -// We will listen to anything (empty subscription) -zsock_send (listener, "sb", "SUBSCRIBE", "", 0); - -// Wait for at most 1/2 second if there\*(Aqs no broadcasting -zsock_set_rcvtimeo (listener, 500); -char *ipaddress = zstr_recv (listener); -if (ipaddress) { - zframe_t *content = zframe_recv (listener); - assert (zframe_size (content) == 2); - assert (zframe_data (content) [0] == 0xCA); - assert (zframe_data (content) [1] == 0xFE); - zframe_destroy (&content); - zstr_free (&ipaddress); - zstr_sendx (speaker, "SILENCE", NULL); -} -zactor_destroy (&listener); -zactor_destroy (&speaker); - -// Test subscription filter using a 3\-node setup -zactor_t *node1 = zactor_new (zbeacon, NULL); -assert (node1); -zsock_send (node1, "si", "CONFIGURE", 5670); -hostname = zstr_recv (node1); -assert (*hostname); -free (hostname); - -zactor_t *node2 = zactor_new (zbeacon, NULL); -assert (node2); -zsock_send (node2, "si", "CONFIGURE", 5670); -hostname = zstr_recv (node2); -assert (*hostname); -free (hostname); - -zactor_t *node3 = zactor_new (zbeacon, NULL); -assert (node3); -zsock_send (node3, "si", "CONFIGURE", 5670); -hostname = zstr_recv (node3); -assert (*hostname); -free (hostname); - -zsock_send (node1, "sbi", "PUBLISH", "NODE/1", 6, 250); -zsock_send (node2, "sbi", "PUBLISH", "NODE/2", 6, 250); -zsock_send (node3, "sbi", "PUBLISH", "RANDOM", 6, 250); -zsock_send (node1, "sb", "SUBSCRIBE", "NODE", 4); - -// Poll on three API sockets at once -zpoller_t *poller = zpoller_new (node1, node2, node3, NULL); -assert (poller); -int64_t stop_at = zclock_mono () + 1000; -while (zclock_mono () < stop_at) { - long timeout = (long) (stop_at \- zclock_mono ()); - if (timeout < 0) - timeout = 0; - void *which = zpoller_wait (poller, timeout * ZMQ_POLL_MSEC); - if (which) { - assert (which == node1); - char *ipaddress, *received; - zstr_recvx (node1, &ipaddress, &received, NULL); - assert (streq (received, "NODE/2")); - zstr_free (&ipaddress); - zstr_free (&received); - } -} -zpoller_destroy (&poller); - -// Stop listening -zstr_sendx (node1, "UNSUBSCRIBE", NULL); - -// Stop all node broadcasts -zstr_sendx (node1, "SILENCE", NULL); -zstr_sendx (node2, "SILENCE", NULL); -zstr_sendx (node3, "SILENCE", NULL); - -// Destroy the test nodes -zactor_destroy (&node1); -zactor_destroy (&node2); -zactor_destroy (&node3); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zcert.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zcert.3 deleted file mode 100644 index e2c81dbf10..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zcert.3 +++ /dev/null @@ -1,215 +0,0 @@ -'\" t -.\" Title: zcert -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZCERT" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zcert \- work with CURVE security certificates -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// This class has draft methods, which may change over time\&. They are not -// in stable releases, by default\&. Use \-\-enable\-drafts to enable\&. -// Create and initialize a new certificate in memory -CZMQ_EXPORT zcert_t * - zcert_new (void); - -// Accepts public/secret key pair from caller -CZMQ_EXPORT zcert_t * - zcert_new_from (const byte *public_key, const byte *secret_key); - -// Load certificate from file -CZMQ_EXPORT zcert_t * - zcert_load (const char *filename); - -// Destroy a certificate in memory -CZMQ_EXPORT void - zcert_destroy (zcert_t **self_p); - -// Return public part of key pair as 32\-byte binary string -CZMQ_EXPORT const byte * - zcert_public_key (zcert_t *self); - -// Return secret part of key pair as 32\-byte binary string -CZMQ_EXPORT const byte * - zcert_secret_key (zcert_t *self); - -// Return public part of key pair as Z85 armored string -CZMQ_EXPORT const char * - zcert_public_txt (zcert_t *self); - -// Return secret part of key pair as Z85 armored string -CZMQ_EXPORT const char * - zcert_secret_txt (zcert_t *self); - -// Set certificate metadata from formatted string\&. -CZMQ_EXPORT void - zcert_set_meta (zcert_t *self, const char *name, const char *format, \&.\&.\&.) CHECK_PRINTF (3); - -// Get metadata value from certificate; if the metadata value doesn\*(Aqt -// exist, returns NULL\&. -CZMQ_EXPORT const char * - zcert_meta (zcert_t *self, const char *name); - -// Get list of metadata fields from certificate\&. Caller is responsible for -// destroying list\&. Caller should not modify the values of list items\&. -CZMQ_EXPORT zlist_t * - zcert_meta_keys (zcert_t *self); - -// Save full certificate (public + secret) to file for persistent storage -// This creates one public file and one secret file (filename + "_secret")\&. -CZMQ_EXPORT int - zcert_save (zcert_t *self, const char *filename); - -// Save public certificate only to file for persistent storage -CZMQ_EXPORT int - zcert_save_public (zcert_t *self, const char *filename); - -// Save secret certificate only to file for persistent storage -CZMQ_EXPORT int - zcert_save_secret (zcert_t *self, const char *filename); - -// Apply certificate to socket, i\&.e\&. use for CURVE security on socket\&. -// If certificate was loaded from public file, the secret key will be -// undefined, and this certificate will not work successfully\&. -CZMQ_EXPORT void - zcert_apply (zcert_t *self, void *socket); - -// Return copy of certificate; if certificate is NULL or we exhausted -// heap memory, returns NULL\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zcert_t * - zcert_dup (zcert_t *self); - -// Return true if two certificates have the same keys -CZMQ_EXPORT bool - zcert_eq (zcert_t *self, zcert_t *compare); - -// Print certificate contents to stdout -CZMQ_EXPORT void - zcert_print (zcert_t *self); - -// Self test of this class -CZMQ_EXPORT void - zcert_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Unset certificate metadata\&. -CZMQ_EXPORT void - zcert_unset_meta (zcert_t *self, const char *name); - -#endif // CZMQ_BUILD_DRAFT_API -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zcert\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -The zcert class provides a way to create and work with security certificates for the ZMQ CURVE mechanism\&. A certificate contains a public + secret key pair, plus metadata\&. It can be used as a temporary object in memory, or persisted to disk\&. On disk, a certificate is stored as two files\&. One is public and contains only the public key\&. The second is secret and contains both keys\&. The two have the same filename, with the secret file adding "_secret"\&. To exchange certificates, send the public file via some secure route\&. Certificates are not signed but are text files that can be verified by eye\&. -.sp -Certificates are stored in the ZPL (ZMQ RFC 4) format\&. They have two sections, "metadata" and "curve"\&. The first contains a list of \fIname = value\fR pairs, one per line\&. Values may be enclosed in quotes\&. The curve section has a \fIpublic\-key = keyvalue\fR and, for secret certificates, a \fIsecret\-key = keyvalue\fR line\&. The keyvalue is a Z85\-encoded CURVE key\&. -.SH "EXAMPLE" -.PP -\fBFrom zcert_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Create temporary directory for test files -# define TESTDIR "\&.test_zcert" -zsys_dir_create (TESTDIR); - -// Create a simple certificate with metadata -zcert_t *cert = zcert_new (); -assert (cert); -zcert_set_meta (cert, "email", "ph@imatix\&.com"); -zcert_set_meta (cert, "name", "Pieter Hintjens"); -zcert_set_meta (cert, "organization", "iMatix Corporation"); -zcert_set_meta (cert, "version", "%d", 1); -zcert_set_meta (cert, "delete_me", "now"); -zcert_unset_meta (cert, "delete_me"); -assert (streq (zcert_meta (cert, "email"), "ph@imatix\&.com")); -zlist_t *keys = zcert_meta_keys (cert); -assert (zlist_size (keys) == 4); -zlist_destroy (&keys); - -// Check the dup and eq methods -zcert_t *shadow = zcert_dup (cert); -assert (zcert_eq (cert, shadow)); -zcert_destroy (&shadow); - -// Check we can save and load certificate -zcert_save (cert, TESTDIR "/mycert\&.txt"); -assert (zsys_file_exists (TESTDIR "/mycert\&.txt")); -assert (zsys_file_exists (TESTDIR "/mycert\&.txt_secret")); - -// Load certificate, will in fact load secret one -shadow = zcert_load (TESTDIR "/mycert\&.txt"); -assert (shadow); -assert (zcert_eq (cert, shadow)); -zcert_destroy (&shadow); - -// Delete secret certificate, load public one -int rc = zsys_file_delete (TESTDIR "/mycert\&.txt_secret"); -assert (rc == 0); -shadow = zcert_load (TESTDIR "/mycert\&.txt"); - -// 32\-byte null key encodes as 40 \*(Aq0\*(Aq characters -assert (streq (zcert_secret_txt (shadow), FORTY_ZEROES)); - -zcert_destroy (&shadow); -zcert_destroy (&cert); - -// Delete all test files -zdir_t *dir = zdir_new (TESTDIR, NULL); -assert (dir); -zdir_remove (dir, true); -zdir_destroy (&dir); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zcertstore.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zcertstore.3 deleted file mode 100644 index 5b76f253db..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zcertstore.3 +++ /dev/null @@ -1,173 +0,0 @@ -'\" t -.\" Title: zcertstore -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZCERTSTORE" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zcertstore \- work with CURVE security certificate stores -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// This class has draft methods, which may change over time\&. They are not -// in stable releases, by default\&. Use \-\-enable\-drafts to enable\&. -// Create a new certificate store from a disk directory, loading and -// indexing all certificates in that location\&. The directory itself may be -// absent, and created later, or modified at any time\&. The certificate store -// is automatically refreshed on any zcertstore_lookup() call\&. If the -// location is specified as NULL, creates a pure\-memory store, which you -// can work with by inserting certificates at runtime\&. -CZMQ_EXPORT zcertstore_t * - zcertstore_new (const char *location); - -// Destroy a certificate store object in memory\&. Does not affect anything -// stored on disk\&. -CZMQ_EXPORT void - zcertstore_destroy (zcertstore_t **self_p); - -// Look up certificate by public key, returns zcert_t object if found, -// else returns NULL\&. The public key is provided in Z85 text format\&. -CZMQ_EXPORT zcert_t * - zcertstore_lookup (zcertstore_t *self, const char *public_key); - -// Insert certificate into certificate store in memory\&. Note that this -// does not save the certificate to disk\&. To do that, use zcert_save() -// directly on the certificate\&. Takes ownership of zcert_t object\&. -CZMQ_EXPORT void - zcertstore_insert (zcertstore_t *self, zcert_t **cert_p); - -// Print list of certificates in store to logging facility -CZMQ_EXPORT void - zcertstore_print (zcertstore_t *self); - -// Self test of this class -CZMQ_EXPORT void - zcertstore_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// Loaders retrieve certificates from an arbitrary source\&. -typedef void (zcertstore_loader) ( - zcertstore_t *self); - -// Destructor for loader state\&. -typedef void (zcertstore_destructor) ( - void **self_p); - -// *** Draft method, for development use, may change without warning *** -// Override the default disk loader with a custom loader fn\&. -CZMQ_EXPORT void - zcertstore_set_loader (zcertstore_t *self, zcertstore_loader loader, zcertstore_destructor destructor, void *state); - -// *** Draft method, for development use, may change without warning *** -// Empty certificate hashtable\&. This wrapper exists to be friendly to bindings, -// which don\*(Aqt usually have access to struct internals\&. -CZMQ_EXPORT void - zcertstore_empty (zcertstore_t *self); - -#endif // CZMQ_BUILD_DRAFT_API -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zcertstore\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -To authenticate new clients using the ZeroMQ CURVE security mechanism, we have to check that the client\(cqs public key matches a key we know and accept\&. There are numerous ways to store accepted client public keys\&. The mechanism CZMQ implements is "certificates" (plain text files) held in a "certificate store" (a disk directory)\&. This class works with such certificate stores, and lets you easily load them from disk, and check if a given client public key is known or not\&. The zcert class does the work of managing a single certificate\&. -.sp -The certificate store can be memory\-only, in which case you can load it yourself by inserting certificate objects one by one, or it can be loaded from disk, in which case you can add, modify, or remove certificates on disk at any time, and the store will detect such changes and refresh itself automatically\&. In most applications you won\(cqt use this class directly but through the zauth class, which provides a high\-level API for authentication (and manages certificate stores for you)\&. To actually create certificates on disk, use the zcert class in code, or the tools/zmakecert\&.c command line tool, or any text editor\&. The format of a certificate file is defined in the zcert man page\&. -.SH "EXAMPLE" -.PP -\fBFrom zcertstore_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Create temporary directory for test files -# define TESTDIR "\&.test_zcertstore" -zsys_dir_create (TESTDIR); - -// Load certificate store from disk; it will be empty -zcertstore_t *certstore = zcertstore_new (TESTDIR); -assert (certstore); - -// Create a single new certificate and save to disk -zcert_t *cert = zcert_new (); -assert (cert); -char *client_key = strdup (zcert_public_txt (cert)); -assert (client_key); -zcert_set_meta (cert, "name", "John Doe"); -zcert_save (cert, TESTDIR "/mycert\&.txt"); -zcert_destroy (&cert); - -// Check that certificate store refreshes as expected -cert = zcertstore_lookup (certstore, client_key); -assert (cert); -assert (streq (zcert_meta (cert, "name"), "John Doe")); - -// Test custom loader -test_loader_state *state = (test_loader_state *) zmalloc (sizeof (test_loader_state)); -state\->index = 0; -zcertstore_set_loader (certstore, s_test_loader, s_test_destructor, (void *)state); -#if (ZMQ_VERSION_MAJOR >= 4) -cert = zcertstore_lookup (certstore, client_key); -assert (cert == NULL); -cert = zcertstore_lookup (certstore, "abcdefghijklmnopqrstuvwxyzabcdefghijklmn"); -assert (cert); -#endif - -free (client_key); - -if (verbose) - zcertstore_print (certstore); -zcertstore_destroy (&certstore); - -// Delete all test files -zdir_t *dir = zdir_new (TESTDIR, NULL); -assert (dir); -zdir_remove (dir, true); -zdir_destroy (&dir); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zchunk.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zchunk.3 deleted file mode 100644 index 5b5d437860..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zchunk.3 +++ /dev/null @@ -1,266 +0,0 @@ -'\" t -.\" Title: zchunk -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZCHUNK" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zchunk \- work with memory chunks -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// Create a new chunk of the specified size\&. If you specify the data, it -// is copied into the chunk\&. If you do not specify the data, the chunk is -// allocated and left empty, and you can then add data using zchunk_append\&. -CZMQ_EXPORT zchunk_t * - zchunk_new (const void *data, size_t size); - -// Destroy a chunk -CZMQ_EXPORT void - zchunk_destroy (zchunk_t **self_p); - -// Resizes chunk max_size as requested; chunk_cur size is set to zero -CZMQ_EXPORT void - zchunk_resize (zchunk_t *self, size_t size); - -// Return chunk cur size -CZMQ_EXPORT size_t - zchunk_size (zchunk_t *self); - -// Return chunk max size -CZMQ_EXPORT size_t - zchunk_max_size (zchunk_t *self); - -// Return chunk data -CZMQ_EXPORT byte * - zchunk_data (zchunk_t *self); - -// Set chunk data from user\-supplied data; truncate if too large\&. Data may -// be null\&. Returns actual size of chunk -CZMQ_EXPORT size_t - zchunk_set (zchunk_t *self, const void *data, size_t size); - -// Fill chunk data from user\-supplied octet -CZMQ_EXPORT size_t - zchunk_fill (zchunk_t *self, byte filler, size_t size); - -// Append user\-supplied data to chunk, return resulting chunk size\&. If the -// data would exceeded the available space, it is truncated\&. If you want to -// grow the chunk to accommodate new data, use the zchunk_extend method\&. -CZMQ_EXPORT size_t - zchunk_append (zchunk_t *self, const void *data, size_t size); - -// Append user\-supplied data to chunk, return resulting chunk size\&. If the -// data would exceeded the available space, the chunk grows in size\&. -CZMQ_EXPORT size_t - zchunk_extend (zchunk_t *self, const void *data, size_t size); - -// Copy as much data from \*(Aqsource\*(Aq into the chunk as possible; returns the -// new size of chunk\&. If all data from \*(Aqsource\*(Aq is used, returns exhausted -// on the source chunk\&. Source can be consumed as many times as needed until -// it is exhausted\&. If source was already exhausted, does not change chunk\&. -CZMQ_EXPORT size_t - zchunk_consume (zchunk_t *self, zchunk_t *source); - -// Returns true if the chunk was exhausted by consume methods, or if the -// chunk has a size of zero\&. -CZMQ_EXPORT bool - zchunk_exhausted (zchunk_t *self); - -// Read chunk from an open file descriptor -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zchunk_t * - zchunk_read (FILE *handle, size_t bytes); - -// Write chunk to an open file descriptor -CZMQ_EXPORT int - zchunk_write (zchunk_t *self, FILE *handle); - -// Try to slurp an entire file into a chunk\&. Will read up to maxsize of -// the file\&. If maxsize is 0, will attempt to read the entire file and -// fail with an assertion if that cannot fit into memory\&. Returns a new -// chunk containing the file data, or NULL if the file could not be read\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zchunk_t * - zchunk_slurp (const char *filename, size_t maxsize); - -// Create copy of chunk, as new chunk object\&. Returns a fresh zchunk_t -// object, or null if there was not enough heap memory\&. If chunk is null, -// returns null\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zchunk_t * - zchunk_dup (zchunk_t *self); - -// Return chunk data encoded as printable hex string\&. Caller must free -// string when finished with it\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zchunk_strhex (zchunk_t *self); - -// Return chunk data copied into freshly allocated string -// Caller must free string when finished with it\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zchunk_strdup (zchunk_t *self); - -// Return TRUE if chunk body is equal to string, excluding terminator -CZMQ_EXPORT bool - zchunk_streq (zchunk_t *self, const char *string); - -// Transform zchunk into a zframe that can be sent in a message\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zframe_t * - zchunk_pack (zchunk_t *self); - -// Transform a zframe into a zchunk\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zchunk_t * - zchunk_unpack (zframe_t *frame); - -// Calculate SHA1 digest for chunk, using zdigest class\&. -CZMQ_EXPORT const char * - zchunk_digest (zchunk_t *self); - -// Dump chunk to FILE stream, for debugging and tracing\&. -CZMQ_EXPORT void - zchunk_fprint (zchunk_t *self, FILE *file); - -// Dump message to stderr, for debugging and tracing\&. -// See zchunk_fprint for details -CZMQ_EXPORT void - zchunk_print (zchunk_t *self); - -// Probe the supplied object, and report if it looks like a zchunk_t\&. -CZMQ_EXPORT bool - zchunk_is (void *self); - -// Self test of this class\&. -CZMQ_EXPORT void - zchunk_test (bool verbose); - -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zchunk\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -The zchunk class works with variable sized blobs\&. Not as efficient as ZeroMQ\(cqs messages but they do less weirdness and so are easier to understand\&. The chunk class has methods to read and write chunks from disk\&. -.sp -Please add \fI@discuss\fR section in \fI\&./\&.\&./src/zchunk\&.c\fR\&. -.SH "EXAMPLE" -.PP -\fBFrom zchunk_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -zchunk_t *chunk = zchunk_new ("1234567890", 10); -assert (chunk); -assert (zchunk_size (chunk) == 10); -assert (memcmp (zchunk_data (chunk), "1234567890", 10) == 0); -zchunk_destroy (&chunk); - -chunk = zchunk_new (NULL, 10); -assert (chunk); -zchunk_append (chunk, "12345678", 8); -zchunk_append (chunk, "90ABCDEF", 8); -zchunk_append (chunk, "GHIJKLMN", 8); -assert (memcmp (zchunk_data (chunk), "1234567890", 10) == 0); -assert (zchunk_size (chunk) == 10); -assert (zchunk_streq (chunk, "1234567890")); -assert (streq (zchunk_digest (chunk), "01B307ACBA4F54F55AAFC33BB06BBBF6CA803E9A")); -char *string = zchunk_strdup (chunk); -assert (streq (string, "1234567890")); -free (string); -string = zchunk_strhex (chunk); -assert (streq (string, "31323334353637383930")); -free (string); - -zframe_t *frame = zchunk_pack (chunk); -assert (frame); - -zchunk_t *chunk2 = zchunk_unpack (frame); -assert (chunk2); -assert (memcmp (zchunk_data (chunk2), "1234567890", 10) == 0); -zframe_destroy (&frame); -zchunk_destroy (&chunk2); - -zchunk_t *copy = zchunk_dup (chunk); -assert (copy); -assert (memcmp (zchunk_data (copy), "1234567890", 10) == 0); -assert (zchunk_size (copy) == 10); -zchunk_destroy (©); -zchunk_destroy (&chunk); - -chunk = zchunk_new (NULL, 0); -zchunk_extend (chunk, "12345678", 8); -zchunk_extend (chunk, "90ABCDEF", 8); -zchunk_extend (chunk, "GHIJKLMN", 8); -assert (zchunk_size (chunk) == 24); -assert (zchunk_streq (chunk, "1234567890ABCDEFGHIJKLMN")); -zchunk_destroy (&chunk); - -copy = zchunk_new ("1234567890abcdefghij", 20); -assert (copy); -chunk = zchunk_new (NULL, 8); -assert (chunk); -zchunk_consume (chunk, copy); -assert (!zchunk_exhausted (copy)); -assert (memcmp (zchunk_data (chunk), "12345678", 8) == 0); -zchunk_set (chunk, NULL, 0); -zchunk_consume (chunk, copy); -assert (!zchunk_exhausted (copy)); -assert (memcmp (zchunk_data (chunk), "90abcdef", 8) == 0); -zchunk_set (chunk, NULL, 0); -zchunk_consume (chunk, copy); -assert (zchunk_exhausted (copy)); -assert (zchunk_size (chunk) == 4); -assert (memcmp (zchunk_data (chunk), "ghij", 4) == 0); -zchunk_destroy (©); -zchunk_destroy (&chunk); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zclock.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zclock.3 deleted file mode 100644 index 10691d17aa..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zclock.3 +++ /dev/null @@ -1,116 +0,0 @@ -'\" t -.\" Title: zclock -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZCLOCK" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zclock \- millisecond clocks and delays -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// Sleep for a number of milliseconds -CZMQ_EXPORT void - zclock_sleep (int msecs); - -// Return current system clock as milliseconds\&. Note that this clock can -// jump backwards (if the system clock is changed) so is unsafe to use for -// timers and time offsets\&. Use zclock_mono for that instead\&. -CZMQ_EXPORT int64_t - zclock_time (void); - -// Return current monotonic clock in milliseconds\&. Use this when you compute -// time offsets\&. The monotonic clock is not affected by system changes and -// so will never be reset backwards, unlike a system clock\&. -CZMQ_EXPORT int64_t - zclock_mono (void); - -// Return current monotonic clock in microseconds\&. Use this when you compute -// time offsets\&. The monotonic clock is not affected by system changes and -// so will never be reset backwards, unlike a system clock\&. -CZMQ_EXPORT int64_t - zclock_usecs (void); - -// Return formatted date/time as fresh string\&. Free using zstr_free()\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zclock_timestr (void); - -// Self test of this class\&. -CZMQ_EXPORT void - zclock_test (bool verbose); - -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zclock\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -The zclock class provides essential sleep and system time functions, used to slow down threads for testing, and calculate timers for polling\&. Wraps the non\-portable system calls in a simple portable API\&. -.sp -The Win32 Sleep() call defaults to 16ms resolution unless the system timer resolution is increased with a call to timeBeginPeriod() permitting 1ms granularity\&. -.SH "EXAMPLE" -.PP -\fBFrom zclock_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -int64_t start = zclock_time (); -zclock_sleep (10); -assert ((zclock_time () \- start) >= 10); -start = zclock_mono (); -int64_t usecs = zclock_usecs (); -zclock_sleep (10); -assert ((zclock_mono () \- start) >= 10); -assert ((zclock_usecs () \- usecs) >= 10000); -char *timestr = zclock_timestr (); -if (verbose) - puts (timestr); -free (timestr); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zconfig.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zconfig.3 deleted file mode 100644 index 5cd00c9707..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zconfig.3 +++ /dev/null @@ -1,342 +0,0 @@ -'\" t -.\" Title: zconfig -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZCONFIG" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zconfig \- work with config files written in rfc\&.zeromq\&.org/spec:4/ZPL\&. -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// -typedef int (zconfig_fct) ( - zconfig_t *self, void *arg, int level); - -// Create new config item -CZMQ_EXPORT zconfig_t * - zconfig_new (const char *name, zconfig_t *parent); - -// Load a config tree from a specified ZPL text file; returns a zconfig_t -// reference for the root, if the file exists and is readable\&. Returns NULL -// if the file does not exist\&. -CZMQ_EXPORT zconfig_t * - zconfig_load (const char *filename); - -// Equivalent to zconfig_load, taking a format string instead of a fixed -// filename\&. -CZMQ_EXPORT zconfig_t * - zconfig_loadf (const char *format, \&.\&.\&.) CHECK_PRINTF (1); - -// Destroy a config item and all its children -CZMQ_EXPORT void - zconfig_destroy (zconfig_t **self_p); - -// Return name of config item -CZMQ_EXPORT char * - zconfig_name (zconfig_t *self); - -// Return value of config item -CZMQ_EXPORT char * - zconfig_value (zconfig_t *self); - -// Insert or update configuration key with value -CZMQ_EXPORT void - zconfig_put (zconfig_t *self, const char *path, const char *value); - -// Equivalent to zconfig_put, accepting a format specifier and variable -// argument list, instead of a single string value\&. -CZMQ_EXPORT void - zconfig_putf (zconfig_t *self, const char *path, const char *format, \&.\&.\&.) CHECK_PRINTF (3); - -// Get value for config item into a string value; leading slash is optional -// and ignored\&. -CZMQ_EXPORT char * - zconfig_get (zconfig_t *self, const char *path, const char *default_value); - -// Set config item name, name may be NULL -CZMQ_EXPORT void - zconfig_set_name (zconfig_t *self, const char *name); - -// Set new value for config item\&. The new value may be a string, a printf -// format, or NULL\&. Note that if string may possibly contain \*(Aq%\*(Aq, or if it -// comes from an insecure source, you must use \*(Aq%s\*(Aq as the format, followed -// by the string\&. -CZMQ_EXPORT void - zconfig_set_value (zconfig_t *self, const char *format, \&.\&.\&.) CHECK_PRINTF (2); - -// Find our first child, if any -CZMQ_EXPORT zconfig_t * - zconfig_child (zconfig_t *self); - -// Find our first sibling, if any -CZMQ_EXPORT zconfig_t * - zconfig_next (zconfig_t *self); - -// Find a config item along a path; leading slash is optional and ignored\&. -CZMQ_EXPORT zconfig_t * - zconfig_locate (zconfig_t *self, const char *path); - -// Locate the last config item at a specified depth -CZMQ_EXPORT zconfig_t * - zconfig_at_depth (zconfig_t *self, int level); - -// Execute a callback for each config item in the tree; returns zero if -// successful, else \-1\&. -CZMQ_EXPORT int - zconfig_execute (zconfig_t *self, zconfig_fct handler, void *arg); - -// Add comment to config item before saving to disk\&. You can add as many -// comment lines as you like\&. If you use a null format, all comments are -// deleted\&. -CZMQ_EXPORT void - zconfig_set_comment (zconfig_t *self, const char *format, \&.\&.\&.) CHECK_PRINTF (2); - -// Return comments of config item, as zlist\&. -CZMQ_EXPORT zlist_t * - zconfig_comments (zconfig_t *self); - -// Save a config tree to a specified ZPL text file, where a filename -// "\-" means dump to standard output\&. -CZMQ_EXPORT int - zconfig_save (zconfig_t *self, const char *filename); - -// Equivalent to zconfig_save, taking a format string instead of a fixed -// filename\&. -CZMQ_EXPORT int - zconfig_savef (zconfig_t *self, const char *format, \&.\&.\&.) CHECK_PRINTF (2); - -// Report filename used during zconfig_load, or NULL if none -CZMQ_EXPORT const char * - zconfig_filename (zconfig_t *self); - -// Reload config tree from same file that it was previously loaded from\&. -// Returns 0 if OK, \-1 if there was an error (and then does not change -// existing data)\&. -CZMQ_EXPORT int - zconfig_reload (zconfig_t **self_p); - -// Load a config tree from a memory chunk -CZMQ_EXPORT zconfig_t * - zconfig_chunk_load (zchunk_t *chunk); - -// Save a config tree to a new memory chunk -CZMQ_EXPORT zchunk_t * - zconfig_chunk_save (zconfig_t *self); - -// Load a config tree from a null\-terminated string -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zconfig_t * - zconfig_str_load (const char *string); - -// Save a config tree to a new null terminated string -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zconfig_str_save (zconfig_t *self); - -// Return true if a configuration tree was loaded from a file and that -// file has changed in since the tree was loaded\&. -CZMQ_EXPORT bool - zconfig_has_changed (zconfig_t *self); - -// Print the config file to open stream -CZMQ_EXPORT void - zconfig_fprint (zconfig_t *self, FILE *file); - -// Print properties of object -CZMQ_EXPORT void - zconfig_print (zconfig_t *self); - -// Self test of this class -CZMQ_EXPORT void - zconfig_test (bool verbose); - -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zconfig\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -Lets applications load, work with, and save configuration files\&. This implements rfc\&.zeromq\&.org/spec:4/ZPL, which is a simple structured text format for configuration files\&. -.sp -Here is an example ZPL stream and corresponding config structure: -.sp -.if n \{\ -.RS 4 -.\} -.nf -context - iothreads = 1 - verbose = 1 # Ask for a trace -main - type = zqueue # ZMQ_DEVICE type - frontend - option - hwm = 1000 - swap = 25000000 # 25MB - bind = \*(Aqinproc://addr1\*(Aq - bind = \*(Aqipc://addr2\*(Aq - backend - bind = inproc://addr3 -.fi -.if n \{\ -.RE -.\} -.sp -.if n \{\ -.RS 4 -.\} -.nf -root Down = child -| Across = next -v -context\-\->main -| | -| v -| type=queue\-\->frontend\-\->backend -| | | -| | v -| | bind=inproc://addr3 -| v -| option\-\->bind=inproc://addr1\-\->bind=ipc://addr2 -| | -| v -| hwm=1000\-\->swap=25000000 -v -iothreads=1\-\->verbose=false -.fi -.if n \{\ -.RE -.\} -.SH "EXAMPLE" -.PP -\fBFrom zconfig_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Create temporary directory for test files -# define TESTDIR "\&.test_zconfig" -zsys_dir_create (TESTDIR); - -zconfig_t *root = zconfig_new ("root", NULL); -assert (root); -zconfig_t *section, *item; - -section = zconfig_new ("headers", root); -assert (section); -item = zconfig_new ("email", section); -assert (item); -zconfig_set_value (item, "some@random\&.com"); -item = zconfig_new ("name", section); -assert (item); -zconfig_set_value (item, "Justin Kayce"); -zconfig_putf (root, "/curve/secret\-key", "%s", "Top Secret"); -zconfig_set_comment (root, " CURVE certificate"); -zconfig_set_comment (root, " \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-"); -assert (zconfig_comments (root)); -zconfig_save (root, TESTDIR "/test\&.cfg"); -zconfig_destroy (&root); -root = zconfig_load (TESTDIR "/test\&.cfg"); -if (verbose) - zconfig_save (root, "\-"); -assert (streq (zconfig_filename (root), TESTDIR "/test\&.cfg")); - -char *email = zconfig_get (root, "/headers/email", NULL); -assert (email); -assert (streq (email, "some@random\&.com")); -char *passwd = zconfig_get (root, "/curve/secret\-key", NULL); -assert (passwd); -assert (streq (passwd, "Top Secret")); - -zconfig_savef (root, "%s/%s", TESTDIR, "test\&.cfg"); -assert (!zconfig_has_changed (root)); -int rc = zconfig_reload (&root); -assert (rc == 0); -assert (!zconfig_has_changed (root)); -zconfig_destroy (&root); - -// Test chunk load/save -root = zconfig_new ("root", NULL); -assert (root); -section = zconfig_new ("section", root); -assert (section); -item = zconfig_new ("value", section); -assert (item); -zconfig_set_value (item, "somevalue"); -zconfig_t *search = zconfig_locate (root, "section/value"); -assert (search == item); -zchunk_t *chunk = zconfig_chunk_save (root); -assert (strlen ((char *) zchunk_data (chunk)) == 32); -char *string = zconfig_str_save (root); -assert (string); -assert (streq (string, (char *) zchunk_data (chunk))); -free (string); -assert (chunk); -zconfig_destroy (&root); - -root = zconfig_chunk_load (chunk); -assert (root); -char *value = zconfig_get (root, "/section/value", NULL); -assert (value); -assert (streq (value, "somevalue")); - -// Test config can\*(Aqt be saved to a file in a path that doesn\*(Aqt -// exist or isn\*(Aqt writable -rc = zconfig_savef (root, "%s/path/that/doesnt/exist/%s", TESTDIR, "test\&.cfg"); -assert (rc == \-1); - -zconfig_destroy (&root); -zchunk_destroy (&chunk); - -// Delete all test files -zdir_t *dir = zdir_new (TESTDIR, NULL); -assert (dir); -zdir_remove (dir, true); -zdir_destroy (&dir); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zdigest.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zdigest.3 deleted file mode 100644 index cabae72d05..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zdigest.3 +++ /dev/null @@ -1,120 +0,0 @@ -'\" t -.\" Title: zdigest -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZDIGEST" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zdigest \- provides hashing functions (SHA\-1 at present) -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// Constructor \- creates new digest object, which you use to build up a -// digest by repeatedly calling zdigest_update() on chunks of data\&. -CZMQ_EXPORT zdigest_t * - zdigest_new (void); - -// Destroy a digest object -CZMQ_EXPORT void - zdigest_destroy (zdigest_t **self_p); - -// Add buffer into digest calculation -CZMQ_EXPORT void - zdigest_update (zdigest_t *self, const byte *buffer, size_t length); - -// Return final digest hash data\&. If built without crypto support, -// returns NULL\&. -CZMQ_EXPORT const byte * - zdigest_data (zdigest_t *self); - -// Return final digest hash size -CZMQ_EXPORT size_t - zdigest_size (zdigest_t *self); - -// Return digest as printable hex string; caller should not modify nor -// free this string\&. After calling this, you may not use zdigest_update() -// on the same digest\&. If built without crypto support, returns NULL\&. -CZMQ_EXPORT char * - zdigest_string (zdigest_t *self); - -// Self test of this class\&. -CZMQ_EXPORT void - zdigest_test (bool verbose); - -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zdigest\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -The zdigest class generates a hash from zchunks of data\&. The current algorithm is SHA\-1, chosen for speed\&. We are aiming to generate a unique digest for a file, and there are no security issues in this use case\&. -.sp -The current code depends on OpenSSL, which might be replaced by hard coded SHA\-1 implementation to reduce build dependencies\&. -.SH "EXAMPLE" -.PP -\fBFrom zdigest_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -byte *buffer = (byte *) zmalloc (1024); -memset (buffer, 0xAA, 1024); - -zdigest_t *digest = zdigest_new (); -assert (digest); -zdigest_update (digest, buffer, 1024); -const byte *data = zdigest_data (digest); -assert (data [0] == 0xDE); -assert (data [1] == 0xB2); -assert (data [2] == 0x38); -assert (data [3] == 0x07); -assert (streq (zdigest_string (digest), - "DEB23807D4FE025E900FE9A9C7D8410C3DDE9671")); -zdigest_destroy (&digest); -free (buffer); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zdir.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zdir.3 deleted file mode 100644 index 04cbc80542..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zdir.3 +++ /dev/null @@ -1,287 +0,0 @@ -'\" t -.\" Title: zdir -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZDIR" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zdir \- work with file\-system directories -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// Create a new directory item that loads in the full tree of the specified -// path, optionally located under some parent path\&. If parent is "\-", then -// loads only the top\-level directory, and does not use parent as a path\&. -CZMQ_EXPORT zdir_t * - zdir_new (const char *path, const char *parent); - -// Destroy a directory tree and all children it contains\&. -CZMQ_EXPORT void - zdir_destroy (zdir_t **self_p); - -// Return directory path -CZMQ_EXPORT const char * - zdir_path (zdir_t *self); - -// Return last modification time for directory\&. -CZMQ_EXPORT time_t - zdir_modified (zdir_t *self); - -// Return total hierarchy size, in bytes of data contained in all files -// in the directory tree\&. -CZMQ_EXPORT off_t - zdir_cursize (zdir_t *self); - -// Return directory count -CZMQ_EXPORT size_t - zdir_count (zdir_t *self); - -// Returns a sorted list of zfile objects; Each entry in the list is a pointer -// to a zfile_t item already allocated in the zdir tree\&. Do not destroy the -// original zdir tree until you are done with this list\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zlist_t * - zdir_list (zdir_t *self); - -// Remove directory, optionally including all files that it contains, at -// all levels\&. If force is false, will only remove the directory if empty\&. -// If force is true, will remove all files and all subdirectories\&. -CZMQ_EXPORT void - zdir_remove (zdir_t *self, bool force); - -// Calculate differences between two versions of a directory tree\&. -// Returns a list of zdir_patch_t patches\&. Either older or newer may -// be null, indicating the directory is empty/absent\&. If alias is set, -// generates virtual filename (minus path, plus alias)\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zlist_t * - zdir_diff (zdir_t *older, zdir_t *newer, const char *alias); - -// Return full contents of directory as a zdir_patch list\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zlist_t * - zdir_resync (zdir_t *self, const char *alias); - -// Load directory cache; returns a hash table containing the SHA\-1 digests -// of every file in the tree\&. The cache is saved between runs in \&.cache\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zhash_t * - zdir_cache (zdir_t *self); - -// Print contents of directory to open stream -CZMQ_EXPORT void - zdir_fprint (zdir_t *self, FILE *file, int indent); - -// Print contents of directory to stdout -CZMQ_EXPORT void - zdir_print (zdir_t *self, int indent); - -// Create a new zdir_watch actor instance: -// -// zactor_t *watch = zactor_new (zdir_watch, NULL); -// -// Destroy zdir_watch instance: -// -// zactor_destroy (&watch); -// -// Enable verbose logging of commands and activity: -// -// zstr_send (watch, "VERBOSE"); -// -// Subscribe to changes to a directory path: -// -// zsock_send (watch, "ss", "SUBSCRIBE", "directory_path"); -// -// Unsubscribe from changes to a directory path: -// -// zsock_send (watch, "ss", "UNSUBSCRIBE", "directory_path"); -// -// Receive directory changes: -// zsock_recv (watch, "sp", &path, &patches); -// -// // Delete the received data\&. -// free (path); -// zlist_destroy (&patches); -CZMQ_EXPORT void - zdir_watch (zsock_t *pipe, void *unused); - -// Self test of this class\&. -CZMQ_EXPORT void - zdir_test (bool verbose); - -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zdir\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -The zdir class gives access to the file system index\&. It will load a directory tree (a directory plus all child directories) into a zdir structure and then let you navigate that structure\&. It exists mainly to wrap non\-portable OS functions to do this\&. -.sp -Please add \fI@discuss\fR section in \fI\&./\&.\&./src/zdir\&.c\fR\&. -.SH "EXAMPLE" -.PP -\fBFrom zdir_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// need to create a file in the test directory we\*(Aqre watching -// in order to ensure the directory exists -zfile_t *initfile = zfile_new ("\&./zdir\-test\-dir", "initial_file"); -assert (initfile); -zfile_output (initfile); -fprintf (zfile_handle (initfile), "initial file\en"); -zfile_close (initfile); -zfile_destroy (&initfile); - -zdir_t *older = zdir_new ("zdir\-test\-dir", NULL); -assert (older); -if (verbose) { - printf ("\en"); - zdir_dump (older, 0); -} -zdir_t *newer = zdir_new ("\&.", NULL); -assert (newer); -zlist_t *patches = zdir_diff (older, newer, "/"); -assert (patches); -while (zlist_size (patches)) { - zdir_patch_t *patch = (zdir_patch_t *) zlist_pop (patches); - zdir_patch_destroy (&patch); -} -zlist_destroy (&patches); -zdir_destroy (&older); -zdir_destroy (&newer); - -zdir_t *nosuch = zdir_new ("does\-not\-exist", NULL); -assert (nosuch == NULL); - -// zdir_watch test: -zactor_t *watch = zactor_new (zdir_watch, NULL); -assert (watch); - -if (verbose) { - zsock_send (watch, "s", "VERBOSE"); - assert (zsock_wait (watch) == 0); -} - -zclock_sleep (1001); // wait for initial file to become \*(Aqstable\*(Aq - -zsock_send (watch, "si", "TIMEOUT", 100); -assert (zsock_wait (watch) == 0); - -zsock_send (watch, "ss", "SUBSCRIBE", "zdir\-test\-dir"); -assert (zsock_wait (watch) == 0); - -zsock_send (watch, "ss", "UNSUBSCRIBE", "zdir\-test\-dir"); -assert (zsock_wait (watch) == 0); - -zsock_send (watch, "ss", "SUBSCRIBE", "zdir\-test\-dir"); -assert (zsock_wait (watch) == 0); - -zfile_t *newfile = zfile_new ("zdir\-test\-dir", "test_abc"); -zfile_output (newfile); -fprintf (zfile_handle (newfile), "test file\en"); -zfile_close (newfile); - -zpoller_t *watch_poll = zpoller_new (watch, NULL); - -// poll for a certain timeout before giving up and failing the test\&. -assert (zpoller_wait (watch_poll, 1001) == watch); - -// wait for notification of the file being added -char *path; -int rc = zsock_recv (watch, "sp", &path, &patches); -assert (rc == 0); - -assert (streq (path, "zdir\-test\-dir")); -free (path); - -assert (zlist_size (patches) == 1); - -zdir_patch_t *patch = (zdir_patch_t *) zlist_pop (patches); -assert (streq (zdir_patch_path (patch), "zdir\-test\-dir")); - -zfile_t *patch_file = zdir_patch_file (patch); -assert (streq (zfile_filename (patch_file, ""), "zdir\-test\-dir/test_abc")); - -zdir_patch_destroy (&patch); -zlist_destroy (&patches); - -// remove the file -zfile_remove (newfile); -zfile_destroy (&newfile); - -// poll for a certain timeout before giving up and failing the test\&. -assert (zpoller_wait (watch_poll, 1001) == watch); - -// wait for notification of the file being removed -rc = zsock_recv (watch, "sp", &path, &patches); -assert (rc == 0); - -assert (streq (path, "zdir\-test\-dir")); -free (path); - -assert (zlist_size (patches) == 1); - -patch = (zdir_patch_t *) zlist_pop (patches); -assert (streq (zdir_patch_path (patch), "zdir\-test\-dir")); - -patch_file = zdir_patch_file (patch); -assert (streq (zfile_filename (patch_file, ""), "zdir\-test\-dir/test_abc")); - -zdir_patch_destroy (&patch); -zlist_destroy (&patches); - -zpoller_destroy (&watch_poll); -zactor_destroy (&watch); - -// clean up by removing the test directory\&. -zdir_t *testdir = zdir_new ("zdir\-test\-dir", NULL); -zdir_remove (testdir, true); -zdir_destroy (&testdir); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zdir_patch.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zdir_patch.3 deleted file mode 100644 index 61789b32c0..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zdir_patch.3 +++ /dev/null @@ -1,129 +0,0 @@ -'\" t -.\" Title: zdir_patch -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZDIR_PATCH" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zdir_patch \- work with directory patches -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -#define ZDIR_PATCH_CREATE 1 // Creates a new file -#define ZDIR_PATCH_DELETE 2 // Delete a file - -// Create new patch -CZMQ_EXPORT zdir_patch_t * - zdir_patch_new (const char *path, zfile_t *file, int op, const char *alias); - -// Destroy a patch -CZMQ_EXPORT void - zdir_patch_destroy (zdir_patch_t **self_p); - -// Create copy of a patch\&. If the patch is null, or memory was exhausted, -// returns null\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zdir_patch_t * - zdir_patch_dup (zdir_patch_t *self); - -// Return patch file directory path -CZMQ_EXPORT const char * - zdir_patch_path (zdir_patch_t *self); - -// Return patch file item -CZMQ_EXPORT zfile_t * - zdir_patch_file (zdir_patch_t *self); - -// Return operation -CZMQ_EXPORT int - zdir_patch_op (zdir_patch_t *self); - -// Return patch virtual file path -CZMQ_EXPORT const char * - zdir_patch_vpath (zdir_patch_t *self); - -// Calculate hash digest for file (create only) -CZMQ_EXPORT void - zdir_patch_digest_set (zdir_patch_t *self); - -// Return hash digest for patch file -CZMQ_EXPORT const char * - zdir_patch_digest (zdir_patch_t *self); - -// Self test of this class\&. -CZMQ_EXPORT void - zdir_patch_test (bool verbose); - -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zdir_patch\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -The zdir_patch class works with one patch, which says "create this file" or "delete this file" (referring to a zfile item each time)\&. -.sp -Please add \fI@discuss\fR section in \fI\&./\&.\&./src/zdir_patch\&.c\fR\&. -.SH "EXAMPLE" -.PP -\fBFrom zdir_patch_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -zfile_t *file = zfile_new ("\&.", "bilbo"); -assert (file); -zdir_patch_t *patch = zdir_patch_new ("\&.", file, patch_create, "/"); -assert (patch); -zfile_destroy (&file); - -file = zdir_patch_file (patch); -assert (file); -assert (streq (zfile_filename (file, "\&."), "bilbo")); -assert (streq (zdir_patch_vpath (patch), "/bilbo")); -zdir_patch_destroy (&patch); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zfile.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zfile.3 deleted file mode 100644 index f3b6591812..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zfile.3 +++ /dev/null @@ -1,340 +0,0 @@ -'\" t -.\" Title: zfile -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZFILE" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zfile \- provides methods to work with files in a portable fashion\&. -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// If file exists, populates properties\&. CZMQ supports portable symbolic -// links, which are files with the extension "\&.ln"\&. A symbolic link is a -// text file containing one line, the filename of a target file\&. Reading -// data from the symbolic link actually reads from the target file\&. Path -// may be NULL, in which case it is not used\&. -CZMQ_EXPORT zfile_t * - zfile_new (const char *path, const char *name); - -// Destroy a file item -CZMQ_EXPORT void - zfile_destroy (zfile_t **self_p); - -// Duplicate a file item, returns a newly constructed item\&. If the file -// is null, or memory was exhausted, returns null\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zfile_t * - zfile_dup (zfile_t *self); - -// Return file name, remove path if provided -CZMQ_EXPORT const char * - zfile_filename (zfile_t *self, const char *path); - -// Refresh file properties from disk; this is not done automatically -// on access methods, otherwise it is not possible to compare directory -// snapshots\&. -CZMQ_EXPORT void - zfile_restat (zfile_t *self); - -// Return when the file was last modified\&. If you want this to reflect the -// current situation, call zfile_restat before checking this property\&. -CZMQ_EXPORT time_t - zfile_modified (zfile_t *self); - -// Return the last\-known size of the file\&. If you want this to reflect the -// current situation, call zfile_restat before checking this property\&. -CZMQ_EXPORT off_t - zfile_cursize (zfile_t *self); - -// Return true if the file is a directory\&. If you want this to reflect -// any external changes, call zfile_restat before checking this property\&. -CZMQ_EXPORT bool - zfile_is_directory (zfile_t *self); - -// Return true if the file is a regular file\&. If you want this to reflect -// any external changes, call zfile_restat before checking this property\&. -CZMQ_EXPORT bool - zfile_is_regular (zfile_t *self); - -// Return true if the file is readable by this process\&. If you want this to -// reflect any external changes, call zfile_restat before checking this -// property\&. -CZMQ_EXPORT bool - zfile_is_readable (zfile_t *self); - -// Return true if the file is writeable by this process\&. If you want this -// to reflect any external changes, call zfile_restat before checking this -// property\&. -CZMQ_EXPORT bool - zfile_is_writeable (zfile_t *self); - -// Check if file has stopped changing and can be safely processed\&. -// Updates the file statistics from disk at every call\&. -CZMQ_EXPORT bool - zfile_is_stable (zfile_t *self); - -// Return true if the file was changed on disk since the zfile_t object -// was created, or the last zfile_restat() call made on it\&. -CZMQ_EXPORT bool - zfile_has_changed (zfile_t *self); - -// Remove the file from disk -CZMQ_EXPORT void - zfile_remove (zfile_t *self); - -// Open file for reading -// Returns 0 if OK, \-1 if not found or not accessible -CZMQ_EXPORT int - zfile_input (zfile_t *self); - -// Open file for writing, creating directory if needed -// File is created if necessary; chunks can be written to file at any -// location\&. Returns 0 if OK, \-1 if error\&. -CZMQ_EXPORT int - zfile_output (zfile_t *self); - -// Read chunk from file at specified position\&. If this was the last chunk, -// sets the eof property\&. Returns a null chunk in case of error\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zchunk_t * - zfile_read (zfile_t *self, size_t bytes, off_t offset); - -// Returns true if zfile_read() just read the last chunk in the file\&. -CZMQ_EXPORT bool - zfile_eof (zfile_t *self); - -// Write chunk to file at specified position -// Return 0 if OK, else \-1 -CZMQ_EXPORT int - zfile_write (zfile_t *self, zchunk_t *chunk, off_t offset); - -// Read next line of text from file\&. Returns a pointer to the text line, -// or NULL if there was nothing more to read from the file\&. -CZMQ_EXPORT const char * - zfile_readln (zfile_t *self); - -// Close file, if open -CZMQ_EXPORT void - zfile_close (zfile_t *self); - -// Return file handle, if opened -CZMQ_EXPORT FILE * - zfile_handle (zfile_t *self); - -// Calculate SHA1 digest for file, using zdigest class\&. -CZMQ_EXPORT const char * - zfile_digest (zfile_t *self); - -// Self test of this class\&. -CZMQ_EXPORT void - zfile_test (bool verbose); - -// These methods are deprecated, and now moved to zsys class\&. -CZMQ_EXPORT bool - zfile_exists (const char *filename); -CZMQ_EXPORT ssize_t - zfile_size (const char *filename); -CZMQ_EXPORT mode_t - zfile_mode (const char *filename); -CZMQ_EXPORT int - zfile_delete (const char *filename); -CZMQ_EXPORT bool - zfile_stable (const char *filename); -CZMQ_EXPORT int - zfile_mkdir (const char *pathname); -CZMQ_EXPORT int - zfile_rmdir (const char *pathname); -CZMQ_EXPORT void - zfile_mode_private (void); -CZMQ_EXPORT void - zfile_mode_default (void); -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zfile\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -The zfile class provides methods to work with disk files\&. A file object provides the modified date, current size, and type of the file\&. You can create a file object for a filename that does not yet exist\&. To read or write data from the file, use the input and output methods, and then read and write chunks\&. The output method lets you both read and write chunks, at any offset\&. Finally, this class provides portable symbolic links\&. If a filename ends in "\&.ln", the first line of text in the file is read, and used as the underlying file for read/write operations\&. This lets you manipulate (e\&.g\&.) copy symbolic links without copying the perhaps very large files they point to\&. -.sp -This class is a new API, deprecating the old zfile class (which still exists but is implemented in zsys now)\&. -.SH "EXAMPLE" -.PP -\fBFrom zfile_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -zfile_t *file = zfile_new (NULL, "bilbo"); -assert (file); -assert (streq (zfile_filename (file, "\&."), "bilbo")); -assert (zfile_is_readable (file) == false); -zfile_destroy (&file); - -// Create a test file in some random subdirectory -file = zfile_new ("\&./this/is/a/test", "bilbo"); -assert (file); -int rc = zfile_output (file); -assert (rc == 0); -zchunk_t *chunk = zchunk_new (NULL, 100); -assert (chunk); -zchunk_fill (chunk, 0, 100); - -// Write 100 bytes at position 1,000,000 in the file -rc = zfile_write (file, chunk, 1000000); -assert (rc == 0); -zchunk_destroy (&chunk); -zfile_close (file); -assert (zfile_is_readable (file)); -assert (zfile_cursize (file) == 1000100); -assert (!zfile_is_stable (file)); -assert (zfile_digest (file)); - -// Now truncate file from outside -int handle = open ("\&./this/is/a/test/bilbo", O_WRONLY | O_TRUNC | O_BINARY, 0); -assert (handle >= 0); -rc = write (handle, "Hello, World\en", 13); -assert (rc == 13); -close (handle); -assert (zfile_has_changed (file)); -zclock_sleep (1001); -assert (zfile_has_changed (file)); - -assert (!zfile_is_stable (file)); -zfile_restat (file); -assert (zfile_is_stable (file)); -assert (streq (zfile_digest (file), "4AB299C8AD6ED14F31923DD94F8B5F5CB89DFB54")); - -// Check we can read from file -rc = zfile_input (file); -assert (rc == 0); -chunk = zfile_read (file, 1000100, 0); -assert (chunk); -assert (zchunk_size (chunk) == 13); -zchunk_destroy (&chunk); -zfile_close (file); - -// Check we can read lines from file -rc = zfile_input (file); -assert (rc == 0); -const char *line = zfile_readln (file); -assert (streq (line, "Hello, World")); -line = zfile_readln (file); -assert (line == NULL); -zfile_close (file); - -// Try some fun with symbolic links -zfile_t *link = zfile_new ("\&./this/is/a/test", "bilbo\&.ln"); -assert (link); -rc = zfile_output (link); -assert (rc == 0); -fprintf (zfile_handle (link), "\&./this/is/a/test/bilbo\en"); -zfile_destroy (&link); - -link = zfile_new ("\&./this/is/a/test", "bilbo\&.ln"); -assert (link); -rc = zfile_input (link); -assert (rc == 0); -chunk = zfile_read (link, 1000100, 0); -assert (chunk); -assert (zchunk_size (chunk) == 13); -zchunk_destroy (&chunk); -zfile_destroy (&link); - -// Remove file and directory -zdir_t *dir = zdir_new ("\&./this", NULL); -assert (dir); -assert (zdir_cursize (dir) == 26); -zdir_remove (dir, true); -assert (zdir_cursize (dir) == 0); -zdir_destroy (&dir); - -// Check we can no longer read from file -assert (zfile_is_readable (file)); -zfile_restat (file); -assert (!zfile_is_readable (file)); -rc = zfile_input (file); -assert (rc == \-1); -zfile_destroy (&file); - -file = zfile_new ("\&./", "eof_checkfile"); -assert (file); -// 1\&. Write something first -rc = zfile_output (file); -assert (rc == 0); -chunk = zchunk_new ("123456789", 9); -assert (chunk); - -rc = zfile_write (file, chunk, 0); -assert (rc == 0); -zchunk_destroy (&chunk); -zfile_close (file); -assert (zfile_cursize (file) == 9); - -// 2\&. Read the written something -rc = zfile_input (file); -assert (rc != \-1); -// try to read more bytes than there is in the file -chunk = zfile_read (file, 1000, 0); -assert (zfile_eof(file)); -assert (zchunk_streq (chunk, "123456789")); -zchunk_destroy (&chunk); - -// reading is ok -chunk = zfile_read (file, 5, 0); -assert (!zfile_eof(file)); -assert (zchunk_streq (chunk, "12345")); -zchunk_destroy (&chunk); - -// read from non zero offset until the end -chunk = zfile_read (file, 5, 5); -assert (zfile_eof(file)); -assert (zchunk_streq (chunk, "6789")); -zchunk_destroy (&chunk); -zfile_remove (file); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zframe.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zframe.3 deleted file mode 100644 index f723dd6105..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zframe.3 +++ /dev/null @@ -1,357 +0,0 @@ -'\" t -.\" Title: zframe -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZFRAME" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zframe \- working with single message frames -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// This class has draft methods, which may change over time\&. They are not -// in stable releases, by default\&. Use \-\-enable\-drafts to enable\&. -#define ZFRAME_MORE 1 // -#define ZFRAME_REUSE 2 // -#define ZFRAME_DONTWAIT 4 // - -// Create a new frame\&. If size is not null, allocates the frame data -// to the specified size\&. If additionally, data is not null, copies -// size octets from the specified data into the frame body\&. -CZMQ_EXPORT zframe_t * - zframe_new (const void *data, size_t size); - -// Create an empty (zero\-sized) frame -CZMQ_EXPORT zframe_t * - zframe_new_empty (void); - -// Create a frame with a specified string content\&. -CZMQ_EXPORT zframe_t * - zframe_from (const char *string); - -// Receive frame from socket, returns zframe_t object or NULL if the recv -// was interrupted\&. Does a blocking recv, if you want to not block then use -// zpoller or zloop\&. -CZMQ_EXPORT zframe_t * - zframe_recv (void *source); - -// Destroy a frame -CZMQ_EXPORT void - zframe_destroy (zframe_t **self_p); - -// Send a frame to a socket, destroy frame after sending\&. -// Return \-1 on error, 0 on success\&. -CZMQ_EXPORT int - zframe_send (zframe_t **self_p, void *dest, int flags); - -// Return number of bytes in frame data -CZMQ_EXPORT size_t - zframe_size (zframe_t *self); - -// Return address of frame data -CZMQ_EXPORT byte * - zframe_data (zframe_t *self); - -// Return meta data property for frame -// Caller must free string when finished with it\&. -CZMQ_EXPORT const char * - zframe_meta (zframe_t *self, const char *property); - -// Create a new frame that duplicates an existing frame\&. If frame is null, -// or memory was exhausted, returns null\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zframe_t * - zframe_dup (zframe_t *self); - -// Return frame data encoded as printable hex string, useful for 0MQ UUIDs\&. -// Caller must free string when finished with it\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zframe_strhex (zframe_t *self); - -// Return frame data copied into freshly allocated string -// Caller must free string when finished with it\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zframe_strdup (zframe_t *self); - -// Return TRUE if frame body is equal to string, excluding terminator -CZMQ_EXPORT bool - zframe_streq (zframe_t *self, const char *string); - -// Return frame MORE indicator (1 or 0), set when reading frame from socket -// or by the zframe_set_more() method -CZMQ_EXPORT int - zframe_more (zframe_t *self); - -// Set frame MORE indicator (1 or 0)\&. Note this is NOT used when sending -// frame to socket, you have to specify flag explicitly\&. -CZMQ_EXPORT void - zframe_set_more (zframe_t *self, int more); - -// Return TRUE if two frames have identical size and data -// If either frame is NULL, equality is always false\&. -CZMQ_EXPORT bool - zframe_eq (zframe_t *self, zframe_t *other); - -// Set new contents for frame -CZMQ_EXPORT void - zframe_reset (zframe_t *self, const void *data, size_t size); - -// Send message to zsys log sink (may be stdout, or system facility as -// configured by zsys_set_logstream)\&. Prefix shows before frame, if not null\&. -CZMQ_EXPORT void - zframe_print (zframe_t *self, const char *prefix); - -// Probe the supplied object, and report if it looks like a zframe_t\&. -CZMQ_EXPORT bool - zframe_is (void *self); - -// Self test of this class\&. -CZMQ_EXPORT void - zframe_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Return frame routing ID, if the frame came from a ZMQ_SERVER socket\&. -// Else returns zero\&. -CZMQ_EXPORT uint32_t - zframe_routing_id (zframe_t *self); - -// *** Draft method, for development use, may change without warning *** -// Set routing ID on frame\&. This is used if/when the frame is sent to a -// ZMQ_SERVER socket\&. -CZMQ_EXPORT void - zframe_set_routing_id (zframe_t *self, uint32_t routing_id); - -// *** Draft method, for development use, may change without warning *** -// Return frame group of radio\-dish pattern\&. -CZMQ_EXPORT const char * - zframe_group (zframe_t *self); - -// *** Draft method, for development use, may change without warning *** -// Set group on frame\&. This is used if/when the frame is sent to a -// ZMQ_RADIO socket\&. -// Return \-1 on error, 0 on success\&. -CZMQ_EXPORT int - zframe_set_group (zframe_t *self, const char *group); - -#endif // CZMQ_BUILD_DRAFT_API -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zframe\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -The zframe class provides methods to send and receive single message frames across 0MQ sockets\&. A \fIframe\fR corresponds to one zmq_msg_t\&. When you read a frame from a socket, the zframe_more() method indicates if the frame is part of an unfinished multipart message\&. The zframe_send method normally destroys the frame, but with the ZFRAME_REUSE flag, you can send the same frame many times\&. Frames are binary, and this class has no special support for text data\&. -.sp -Please add \fI@discuss\fR section in \fI\&./\&.\&./src/zframe\&.c\fR\&. -.SH "EXAMPLE" -.PP -\fBFrom zframe_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Create two PAIR sockets and connect over inproc -zsock_t *output = zsock_new_pair ("@tcp://127\&.0\&.0\&.1:9001"); -assert (output); -zsock_t *input = zsock_new_pair (">tcp://127\&.0\&.0\&.1:9001"); -assert (input); - -// Send five different frames, test ZFRAME_MORE -int frame_nbr; -for (frame_nbr = 0; frame_nbr < 5; frame_nbr++) { - frame = zframe_new ("Hello", 5); - assert (frame); - rc = zframe_send (&frame, output, ZFRAME_MORE); - assert (rc == 0); -} -// Send same frame five times, test ZFRAME_REUSE -frame = zframe_new ("Hello", 5); -assert (frame); -for (frame_nbr = 0; frame_nbr < 5; frame_nbr++) { - rc = zframe_send (&frame, output, ZFRAME_MORE + ZFRAME_REUSE); - assert (rc == 0); -} -assert (frame); -zframe_t *copy = zframe_dup (frame); -assert (zframe_eq (frame, copy)); -zframe_destroy (&frame); -assert (!zframe_eq (frame, copy)); -assert (zframe_size (copy) == 5); -zframe_destroy (©); -assert (!zframe_eq (frame, copy)); - -// Test zframe_new_empty -frame = zframe_new_empty (); -assert (frame); -assert (zframe_size (frame) == 0); -zframe_destroy (&frame); - -// Send END frame -frame = zframe_new ("NOT", 3); -assert (frame); -zframe_reset (frame, "END", 3); -char *string = zframe_strhex (frame); -assert (streq (string, "454E44")); -free (string); -string = zframe_strdup (frame); -assert (streq (string, "END")); -free (string); -rc = zframe_send (&frame, output, 0); -assert (rc == 0); - -// Read and count until we receive END -frame_nbr = 0; -for (frame_nbr = 0;; frame_nbr++) { - zframe_t *frame = zframe_recv (input); - if (zframe_streq (frame, "END")) { - zframe_destroy (&frame); - break; - } - assert (zframe_more (frame)); - zframe_set_more (frame, 0); - assert (zframe_more (frame) == 0); - zframe_destroy (&frame); -} -assert (frame_nbr == 10); - -#if (ZMQ_VERSION >= ZMQ_MAKE_VERSION (4, 1, 0)) -// Test zframe_meta -frame = zframe_new ("Hello", 5); -assert (frame); -rc = zframe_send (&frame, output, 0); -assert (rc == 0); -frame = zframe_recv (input); -const char *meta = zframe_meta (frame, "Socket\-Type"); -assert (meta != NULL); -assert (streq (meta, "PAIR")); -assert (zframe_meta (frame, "nonexistent") == NULL); -zframe_destroy (&frame); -#endif - -zsock_destroy (&input); -zsock_destroy (&output); - -#if defined (ZMQ_SERVER) -// Create server and client sockets and connect over inproc -zsock_t *server = zsock_new_server ("inproc://zframe\-test\-routing"); -assert (server); -zsock_t *client = zsock_new_client ("inproc://zframe\-test\-routing"); -assert (client); - -// Send request from client to server -zframe_t *request = zframe_new ("Hello", 5); -assert (request); -rc = zframe_send (&request, client, 0); -assert (rc == 0); -assert (!request); - -// Read request and send reply -request = zframe_recv (server); -assert (request); -assert (zframe_streq (request, "Hello")); -assert (zframe_routing_id (request)); - -zframe_t *reply = zframe_new ("World", 5); -assert (reply); -zframe_set_routing_id (reply, zframe_routing_id (request)); -rc = zframe_send (&reply, server, 0); -assert (rc == 0); -zframe_destroy (&request); - -// Read reply -reply = zframe_recv (client); -assert (zframe_streq (reply, "World")); -assert (zframe_routing_id (reply) == 0); -zframe_destroy (&reply); - -// Client and server disallow multipart -frame = zframe_new ("Hello", 5); -rc = zframe_send (&frame, client, ZFRAME_MORE); -assert (rc == \-1); -rc = zframe_send (&frame, server, ZFRAME_MORE); -assert (rc == \-1); -zframe_destroy (&frame); - -zsock_destroy (&client); -zsock_destroy (&server); -#endif - -#ifdef ZMQ_RADIO -// Create radio and dish sockets and connect over inproc -zsock_t *radio = zsock_new_radio ("inproc://zframe\-test\-radio"); -assert (radio); -zsock_t *dish = zsock_new_dish ("inproc://zframe\-test\-radio"); -assert (dish); - -// Join the group -rc = zsock_join (dish, "World"); -assert (rc == 0); - -// Publish message from radio -zframe_t *message = zframe_new ("Hello", 5); -assert (message); -rc = zframe_set_group (message, "World"); -assert (rc == 0); -rc = zframe_send (&message, radio, 0); -assert (rc == 0); -assert (!message); - -// Receive the message from dish -message = zframe_recv (dish); -assert (message); -assert (zframe_streq (message, "Hello")); -assert (strcmp("World", zframe_group (message)) == 0); -zframe_destroy (&message); - -zsock_destroy (&dish); -zsock_destroy (&radio); -#endif -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zgossip.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zgossip.3 deleted file mode 100644 index 170d3a2271..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zgossip.3 +++ /dev/null @@ -1,338 +0,0 @@ -'\" t -.\" Title: zgossip -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZGOSSIP" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zgossip \- decentralized configuration management -.SH "SYNOPSIS" -.sp -.nf -// To work with zgossip, use the CZMQ zactor API: -// -// Create new zgossip instance, passing logging prefix: -// -// zactor_t *zgossip = zactor_new (zgossip, "myname"); -// -// Destroy zgossip instance -// -// zactor_destroy (&zgossip); -// -// Enable verbose logging of commands and activity: -// -// zstr_send (zgossip, "VERBOSE"); -// -// Bind zgossip to specified endpoint\&. TCP endpoints may specify -// the port number as "*" to aquire an ephemeral port: -// -// zstr_sendx (zgossip, "BIND", endpoint, NULL); -// -// Return assigned port number, specifically when BIND was done using an -// an ephemeral port: -// -// zstr_sendx (zgossip, "PORT", NULL); -// char *command, *port_str; -// zstr_recvx (zgossip, &command, &port_str, NULL); -// assert (streq (command, "PORT")); -// -// Specify configuration file to load, overwriting any previous loaded -// configuration file or options: -// -// zstr_sendx (zgossip, "LOAD", filename, NULL); -// -// Set configuration path value: -// -// zstr_sendx (zgossip, "SET", path, value, NULL); -// -// Save configuration data to config file on disk: -// -// zstr_sendx (zgossip, "SAVE", filename, NULL); -// -// Send zmsg_t instance to zgossip: -// -// zactor_send (zgossip, &msg); -// -// Receive zmsg_t instance from zgossip: -// -// zmsg_t *msg = zactor_recv (zgossip); -// -// This is the zgossip constructor as a zactor_fn: -// -CZMQ_EXPORT void - zgossip (zsock_t *pipe, void *args); - -// Self test of this class -CZMQ_EXPORT void - zgossip_test (bool verbose); -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zgossip\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -Implements a gossip protocol for decentralized configuration management\&. Your applications nodes form a loosely connected network (which can have cycles), and publish name/value tuples\&. Each node re\-distributes the new tuples it receives, so that the entire network eventually achieves a consistent state\&. The current design does not expire tuples\&. -.sp -Provides these commands (sent as multipart strings to the actor): -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -BIND endpoint \(em binds the gossip service to specified endpoint -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -PORT \(em returns the last TCP port, if any, used for binding -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -LOAD configfile \(em load configuration from specified file -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -SET configpath value \(em set configuration path = value -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -SAVE configfile \(em save configuration to specified file -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -CONNECT endpoint \(em connect the gossip service to the specified peer -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -PUBLISH key value \(em publish a key/value pair to the gossip cluster -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -STATUS \(em return number of key/value pairs held by gossip service -.RE -.sp -Returns these messages: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -PORT number \(em reply to PORT command -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -STATUS number \(em reply to STATUS command -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -DELIVER key value \(em new tuple delivered from network -.RE -.sp -The gossip protocol distributes information around a loosely\-connected network of gossip services\&. The information consists of name/value pairs published by applications at any point in the network\&. The goal of the gossip protocol is to create eventual consistency between all the using applications\&. -.sp -The name/value pairs (tuples) can be used for configuration data, for status updates, for presence, or for discovery\&. When used for discovery, the gossip protocol works as an alternative to e\&.g\&. UDP beaconing\&. -.sp -The gossip network consists of a set of loosely\-coupled nodes that exchange tuples\&. Nodes can be connected across arbitrary transports, so the gossip network can have nodes that communicate over inproc, over IPC, and/or over TCP, at the same time\&. -.sp -Each node runs the same stack, which is a server\-client hybrid using a modified Harmony pattern (from Chapter 8 of the Guide): \m[blue]\fBhttp://zguide\&.zeromq\&.org/page:all#True\-Peer\-Connectivity\-Harmony\-Pattern\fR\m[] -.sp -Each node provides a ROUTER socket that accepts client connections on an key defined by the application via a BIND command\&. The state machine for these connections is in zgossip\&.xml, and the generated code is in zgossip_engine\&.inc\&. -.sp -Each node additionally creates outbound connections via DEALER sockets to a set of servers ("remotes"), and under control of the calling app, which sends CONNECT commands for each configured remote\&. -.sp -The messages between client and server are defined in zgossip_msg\&.xml\&. We built this stack using the zeromq/zproto toolkit\&. -.sp -To join the gossip network, a node connects to one or more peers\&. Each peer acts as a forwarder\&. This loosely\-coupled network can scale to thousands of nodes\&. However the gossip protocol is NOT designed to be efficient, and should not be used for application data, as the same tuples may be sent many times across the network\&. -.sp -The basic logic of the gossip service is to accept PUBLISH messages from its owning application, and to forward these to every remote, and every client it talks to\&. When a node gets a duplicate tuple, it throws it away\&. When a node gets a new tuple, it stores it, and fowards it as just described\&. At any point the application can access the node\(cqs set of tuples\&. -.sp -At present there is no way to expire tuples from the network\&. -.sp -The assumptions in this design are: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -The data set is slow\-changing\&. Thus, the cost of the gossip protocol is irrelevant with respect to other traffic\&. -.RE -.SH "EXAMPLE" -.PP -\fBFrom zgossip_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Test basic client\-to\-server operation of the protocol -zactor_t *server = zactor_new (zgossip, "server"); -assert (server); -if (verbose) - zstr_send (server, "VERBOSE"); -zstr_sendx (server, "BIND", "inproc://zgossip", NULL); - -zsock_t *client = zsock_new (ZMQ_DEALER); -assert (client); -zsock_set_rcvtimeo (client, 2000); -int rc = zsock_connect (client, "inproc://zgossip"); -assert (rc == 0); - -// Send HELLO, which gets no message -zgossip_msg_t *message = zgossip_msg_new (); -zgossip_msg_set_id (message, ZGOSSIP_MSG_HELLO); -zgossip_msg_send (message, client); - -// Send PING, expect PONG back -zgossip_msg_set_id (message, ZGOSSIP_MSG_PING); -zgossip_msg_send (message, client); -zgossip_msg_recv (message, client); -assert (zgossip_msg_id (message) == ZGOSSIP_MSG_PONG); -zgossip_msg_destroy (&message); - -zactor_destroy (&server); -zsock_destroy (&client); - -// Test peer\-to\-peer operations -zactor_t *base = zactor_new (zgossip, "base"); -assert (base); -if (verbose) - zstr_send (base, "VERBOSE"); -// Set a 100msec timeout on clients so we can test expiry -zstr_sendx (base, "SET", "server/timeout", "100", NULL); -zstr_sendx (base, "BIND", "inproc://base", NULL); - -zactor_t *alpha = zactor_new (zgossip, "alpha"); -assert (alpha); -zstr_sendx (alpha, "CONNECT", "inproc://base", NULL); -zstr_sendx (alpha, "PUBLISH", "inproc://alpha\-1", "service1", NULL); -zstr_sendx (alpha, "PUBLISH", "inproc://alpha\-2", "service2", NULL); - -zactor_t *beta = zactor_new (zgossip, "beta"); -assert (beta); -zstr_sendx (beta, "CONNECT", "inproc://base", NULL); -zstr_sendx (beta, "PUBLISH", "inproc://beta\-1", "service1", NULL); -zstr_sendx (beta, "PUBLISH", "inproc://beta\-2", "service2", NULL); - -// got nothing -zclock_sleep (200); - -zactor_destroy (&base); -zactor_destroy (&alpha); -zactor_destroy (&beta); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zhash.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zhash.3 deleted file mode 100644 index 8d0d45ab3f..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zhash.3 +++ /dev/null @@ -1,382 +0,0 @@ -'\" t -.\" Title: zhash -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZHASH" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zhash \- simple generic hash container -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// Callback function for zhash_freefn method -typedef void (zhash_free_fn) ( - void *data); - -// Create a new, empty hash container -CZMQ_EXPORT zhash_t * - zhash_new (void); - -// Unpack binary frame into a new hash table\&. Packed data must follow format -// defined by zhash_pack\&. Hash table is set to autofree\&. An empty frame -// unpacks to an empty hash table\&. -CZMQ_EXPORT zhash_t * - zhash_unpack (zframe_t *frame); - -// Destroy a hash container and all items in it -CZMQ_EXPORT void - zhash_destroy (zhash_t **self_p); - -// Insert item into hash table with specified key and item\&. -// If key is already present returns \-1 and leaves existing item unchanged -// Returns 0 on success\&. -CZMQ_EXPORT int - zhash_insert (zhash_t *self, const char *key, void *item); - -// Update item into hash table with specified key and item\&. -// If key is already present, destroys old item and inserts new one\&. -// Use free_fn method to ensure deallocator is properly called on item\&. -CZMQ_EXPORT void - zhash_update (zhash_t *self, const char *key, void *item); - -// Remove an item specified by key from the hash table\&. If there was no such -// item, this function does nothing\&. -CZMQ_EXPORT void - zhash_delete (zhash_t *self, const char *key); - -// Return the item at the specified key, or null -CZMQ_EXPORT void * - zhash_lookup (zhash_t *self, const char *key); - -// Reindexes an item from an old key to a new key\&. If there was no such -// item, does nothing\&. Returns 0 if successful, else \-1\&. -CZMQ_EXPORT int - zhash_rename (zhash_t *self, const char *old_key, const char *new_key); - -// Set a free function for the specified hash table item\&. When the item is -// destroyed, the free function, if any, is called on that item\&. -// Use this when hash items are dynamically allocated, to ensure that -// you don\*(Aqt have memory leaks\&. You can pass \*(Aqfree\*(Aq or NULL as a free_fn\&. -// Returns the item, or NULL if there is no such item\&. -CZMQ_EXPORT void * - zhash_freefn (zhash_t *self, const char *key, zhash_free_fn free_fn); - -// Return the number of keys/items in the hash table -CZMQ_EXPORT size_t - zhash_size (zhash_t *self); - -// Make copy of hash table; if supplied table is null, returns null\&. -// Does not copy items themselves\&. Rebuilds new table so may be slow on -// very large tables\&. NOTE: only works with item values that are strings -// since there\*(Aqs no other way to know how to duplicate the item value\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zhash_t * - zhash_dup (zhash_t *self); - -// Return keys for items in table -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zlist_t * - zhash_keys (zhash_t *self); - -// Simple iterator; returns first item in hash table, in no given order, -// or NULL if the table is empty\&. This method is simpler to use than the -// foreach() method, which is deprecated\&. To access the key for this item -// use zhash_cursor()\&. NOTE: do NOT modify the table while iterating\&. -CZMQ_EXPORT void * - zhash_first (zhash_t *self); - -// Simple iterator; returns next item in hash table, in no given order, -// or NULL if the last item was already returned\&. Use this together with -// zhash_first() to process all items in a hash table\&. If you need the -// items in sorted order, use zhash_keys() and then zlist_sort()\&. To -// access the key for this item use zhash_cursor()\&. NOTE: do NOT modify -// the table while iterating\&. -CZMQ_EXPORT void * - zhash_next (zhash_t *self); - -// After a successful first/next method, returns the key for the item that -// was returned\&. This is a constant string that you may not modify or -// deallocate, and which lasts as long as the item in the hash\&. After an -// unsuccessful first/next, returns NULL\&. -CZMQ_EXPORT const char * - zhash_cursor (zhash_t *self); - -// Add a comment to hash table before saving to disk\&. You can add as many -// comment lines as you like\&. These comment lines are discarded when loading -// the file\&. If you use a null format, all comments are deleted\&. -CZMQ_EXPORT void - zhash_comment (zhash_t *self, const char *format, \&.\&.\&.) CHECK_PRINTF (2); - -// Serialize hash table to a binary frame that can be sent in a message\&. -// The packed format is compatible with the \*(Aqdictionary\*(Aq type defined in -// http://rfc\&.zeromq\&.org/spec:35/FILEMQ, and implemented by zproto: -// -// ; A list of name/value pairs -// dictionary = dict\-count *( dict\-name dict\-value ) -// dict\-count = number\-4 -// dict\-value = longstr -// dict\-name = string -// -// ; Strings are always length + text contents -// longstr = number\-4 *VCHAR -// string = number\-1 *VCHAR -// -// ; Numbers are unsigned integers in network byte order -// number\-1 = 1OCTET -// number\-4 = 4OCTET -// -// Comments are not included in the packed data\&. Item values MUST be -// strings\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zframe_t * - zhash_pack (zhash_t *self); - -// Save hash table to a text file in name=value format\&. Hash values must be -// printable strings; keys may not contain \*(Aq=\*(Aq character\&. Returns 0 if OK, -// else \-1 if a file error occurred\&. -CZMQ_EXPORT int - zhash_save (zhash_t *self, const char *filename); - -// Load hash table from a text file in name=value format; hash table must -// already exist\&. Hash values must printable strings; keys may not contain -// \*(Aq=\*(Aq character\&. Returns 0 if OK, else \-1 if a file was not readable\&. -CZMQ_EXPORT int - zhash_load (zhash_t *self, const char *filename); - -// When a hash table was loaded from a file by zhash_load, this method will -// reload the file if it has been modified since, and is "stable", i\&.e\&. not -// still changing\&. Returns 0 if OK, \-1 if there was an error reloading the -// file\&. -CZMQ_EXPORT int - zhash_refresh (zhash_t *self); - -// Set hash for automatic value destruction -CZMQ_EXPORT void - zhash_autofree (zhash_t *self); - -// Self test of this class\&. -CZMQ_EXPORT void - zhash_test (bool verbose); - -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zhash\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -zhash is an expandable hash table container\&. This is a simple container\&. For heavy\-duty applications we recommend using zhashx\&. -.sp -Note that it\(cqs relatively slow (50K insertions/deletes per second), so don\(cqt do inserts/updates on the critical path for message I/O\&. It can do 2\&.5M lookups per second for 16\-char keys\&. Timed on a 1\&.6GHz CPU\&. -.SH "EXAMPLE" -.PP -\fBFrom zhash_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -zhash_t *hash = zhash_new (); -assert (hash); -assert (zhash_size (hash) == 0); -assert (zhash_first (hash) == NULL); -assert (zhash_cursor (hash) == NULL); - -// Insert some items -int rc; -rc = zhash_insert (hash, "DEADBEEF", "dead beef"); -char *item = (char *) zhash_first (hash); -assert (streq (zhash_cursor (hash), "DEADBEEF")); -assert (streq (item, "dead beef")); -assert (rc == 0); -rc = zhash_insert (hash, "ABADCAFE", "a bad cafe"); -assert (rc == 0); -rc = zhash_insert (hash, "C0DEDBAD", "coded bad"); -assert (rc == 0); -rc = zhash_insert (hash, "DEADF00D", "dead food"); -assert (rc == 0); -assert (zhash_size (hash) == 4); - -// Look for existing items -item = (char *) zhash_lookup (hash, "DEADBEEF"); -assert (streq (item, "dead beef")); -item = (char *) zhash_lookup (hash, "ABADCAFE"); -assert (streq (item, "a bad cafe")); -item = (char *) zhash_lookup (hash, "C0DEDBAD"); -assert (streq (item, "coded bad")); -item = (char *) zhash_lookup (hash, "DEADF00D"); -assert (streq (item, "dead food")); - -// Look for non\-existent items -item = (char *) zhash_lookup (hash, "foo"); -assert (item == NULL); - -// Try to insert duplicate items -rc = zhash_insert (hash, "DEADBEEF", "foo"); -assert (rc == \-1); -item = (char *) zhash_lookup (hash, "DEADBEEF"); -assert (streq (item, "dead beef")); - -// Some rename tests - -// Valid rename, key is now LIVEBEEF -rc = zhash_rename (hash, "DEADBEEF", "LIVEBEEF"); -assert (rc == 0); -item = (char *) zhash_lookup (hash, "LIVEBEEF"); -assert (streq (item, "dead beef")); - -// Trying to rename an unknown item to a non\-existent key -rc = zhash_rename (hash, "WHATBEEF", "NONESUCH"); -assert (rc == \-1); - -// Trying to rename an unknown item to an existing key -rc = zhash_rename (hash, "WHATBEEF", "LIVEBEEF"); -assert (rc == \-1); -item = (char *) zhash_lookup (hash, "LIVEBEEF"); -assert (streq (item, "dead beef")); - -// Trying to rename an existing item to another existing item -rc = zhash_rename (hash, "LIVEBEEF", "ABADCAFE"); -assert (rc == \-1); -item = (char *) zhash_lookup (hash, "LIVEBEEF"); -assert (streq (item, "dead beef")); -item = (char *) zhash_lookup (hash, "ABADCAFE"); -assert (streq (item, "a bad cafe")); - -// Test keys method -zlist_t *keys = zhash_keys (hash); -assert (zlist_size (keys) == 4); -zlist_destroy (&keys); - -// Test dup method -zhash_t *copy = zhash_dup (hash); -assert (zhash_size (copy) == 4); -item = (char *) zhash_lookup (copy, "LIVEBEEF"); -assert (item); -assert (streq (item, "dead beef")); -zhash_destroy (©); - -// Test pack/unpack methods -zframe_t *frame = zhash_pack (hash); -copy = zhash_unpack (frame); -zframe_destroy (&frame); -assert (zhash_size (copy) == 4); -item = (char *) zhash_lookup (copy, "LIVEBEEF"); -assert (item); -assert (streq (item, "dead beef")); -zhash_destroy (©); - -// Test save and load -zhash_comment (hash, "This is a test file"); -zhash_comment (hash, "Created by %s", "czmq_selftest"); -zhash_save (hash, "\&.cache"); -copy = zhash_new (); -assert (copy); -zhash_load (copy, "\&.cache"); -item = (char *) zhash_lookup (copy, "LIVEBEEF"); -assert (item); -assert (streq (item, "dead beef")); -zhash_destroy (©); -zsys_file_delete ("\&.cache"); - -// Delete a item -zhash_delete (hash, "LIVEBEEF"); -item = (char *) zhash_lookup (hash, "LIVEBEEF"); -assert (item == NULL); -assert (zhash_size (hash) == 3); - -// Check that the queue is robust against random usage -struct { - char name [100]; - bool exists; -} testset [200]; -memset (testset, 0, sizeof (testset)); -int testmax = 200, testnbr, iteration; - -srandom ((unsigned) time (NULL)); -for (iteration = 0; iteration < 25000; iteration++) { - testnbr = randof (testmax); - assert (testnbr != testmax); - assert (testnbr < testmax); - if (testset [testnbr]\&.exists) { - item = (char *) zhash_lookup (hash, testset [testnbr]\&.name); - assert (item); - zhash_delete (hash, testset [testnbr]\&.name); - testset [testnbr]\&.exists = false; - } - else { - sprintf (testset [testnbr]\&.name, "%x\-%x", rand (), rand ()); - if (zhash_insert (hash, testset [testnbr]\&.name, "") == 0) - testset [testnbr]\&.exists = true; - } -} -// Test 10K lookups -for (iteration = 0; iteration < 10000; iteration++) - item = (char *) zhash_lookup (hash, "DEADBEEFABADCAFE"); - -// Destructor should be safe to call twice -zhash_destroy (&hash); -zhash_destroy (&hash); -assert (hash == NULL); - -// Test autofree; automatically copies and frees string values -hash = zhash_new (); -assert (hash); -zhash_autofree (hash); -char value [255]; -strcpy (value, "This is a string"); -rc = zhash_insert (hash, "key1", value); -assert (rc == 0); -strcpy (value, "Inserting with the same key will fail"); -rc = zhash_insert (hash, "key1", value); -assert (rc == \-1); -strcpy (value, "Ring a ding ding"); -rc = zhash_insert (hash, "key2", value); -assert (rc == 0); -assert (streq ((char *) zhash_lookup (hash, "key1"), "This is a string")); -assert (streq ((char *) zhash_lookup (hash, "key2"), "Ring a ding ding")); -zhash_destroy (&hash); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zhashx.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zhashx.3 deleted file mode 100644 index d78b29a431..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zhashx.3 +++ /dev/null @@ -1,498 +0,0 @@ -'\" t -.\" Title: zhashx -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZHASHX" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zhashx \- extended generic hash container -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// This class has draft methods, which may change over time\&. They are not -// in stable releases, by default\&. Use \-\-enable\-drafts to enable\&. -// Destroy an item -typedef void (zhashx_destructor_fn) ( - void **item); - -// Duplicate an item -typedef void * (zhashx_duplicator_fn) ( - const void *item); - -// Compare two items, for sorting -typedef int (zhashx_comparator_fn) ( - const void *item1, const void *item2); - -// compare two items, for sorting -typedef void (zhashx_free_fn) ( - void *data); - -// compare two items, for sorting -typedef size_t (zhashx_hash_fn) ( - const void *key); - -// Serializes an item to a longstr\&. -// The caller takes ownership of the newly created object\&. -typedef char * (zhashx_serializer_fn) ( - const void *item); - -// Deserializes a longstr into an item\&. -// The caller takes ownership of the newly created object\&. -typedef void * (zhashx_deserializer_fn) ( - const char *item_str); - -// Create a new, empty hash container -CZMQ_EXPORT zhashx_t * - zhashx_new (void); - -// Unpack binary frame into a new hash table\&. Packed data must follow format -// defined by zhashx_pack\&. Hash table is set to autofree\&. An empty frame -// unpacks to an empty hash table\&. -CZMQ_EXPORT zhashx_t * - zhashx_unpack (zframe_t *frame); - -// Destroy a hash container and all items in it -CZMQ_EXPORT void - zhashx_destroy (zhashx_t **self_p); - -// Insert item into hash table with specified key and item\&. -// If key is already present returns \-1 and leaves existing item unchanged -// Returns 0 on success\&. -CZMQ_EXPORT int - zhashx_insert (zhashx_t *self, const void *key, void *item); - -// Update or insert item into hash table with specified key and item\&. If the -// key is already present, destroys old item and inserts new one\&. If you set -// a container item destructor, this is called on the old value\&. If the key -// was not already present, inserts a new item\&. Sets the hash cursor to the -// new item\&. -CZMQ_EXPORT void - zhashx_update (zhashx_t *self, const void *key, void *item); - -// Remove an item specified by key from the hash table\&. If there was no such -// item, this function does nothing\&. -CZMQ_EXPORT void - zhashx_delete (zhashx_t *self, const void *key); - -// Delete all items from the hash table\&. If the key destructor is -// set, calls it on every key\&. If the item destructor is set, calls -// it on every item\&. -CZMQ_EXPORT void - zhashx_purge (zhashx_t *self); - -// Return the item at the specified key, or null -CZMQ_EXPORT void * - zhashx_lookup (zhashx_t *self, const void *key); - -// Reindexes an item from an old key to a new key\&. If there was no such -// item, does nothing\&. Returns 0 if successful, else \-1\&. -CZMQ_EXPORT int - zhashx_rename (zhashx_t *self, const void *old_key, const void *new_key); - -// Set a free function for the specified hash table item\&. When the item is -// destroyed, the free function, if any, is called on that item\&. -// Use this when hash items are dynamically allocated, to ensure that -// you don\*(Aqt have memory leaks\&. You can pass \*(Aqfree\*(Aq or NULL as a free_fn\&. -// Returns the item, or NULL if there is no such item\&. -CZMQ_EXPORT void * - zhashx_freefn (zhashx_t *self, const void *key, zhashx_free_fn free_fn); - -// Return the number of keys/items in the hash table -CZMQ_EXPORT size_t - zhashx_size (zhashx_t *self); - -// Return a zlistx_t containing the keys for the items in the -// table\&. Uses the key_duplicator to duplicate all keys and sets the -// key_destructor as destructor for the list\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zlistx_t * - zhashx_keys (zhashx_t *self); - -// Return a zlistx_t containing the values for the items in the -// table\&. Uses the duplicator to duplicate all items and sets the -// destructor as destructor for the list\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zlistx_t * - zhashx_values (zhashx_t *self); - -// Simple iterator; returns first item in hash table, in no given order, -// or NULL if the table is empty\&. This method is simpler to use than the -// foreach() method, which is deprecated\&. To access the key for this item -// use zhashx_cursor()\&. NOTE: do NOT modify the table while iterating\&. -CZMQ_EXPORT void * - zhashx_first (zhashx_t *self); - -// Simple iterator; returns next item in hash table, in no given order, -// or NULL if the last item was already returned\&. Use this together with -// zhashx_first() to process all items in a hash table\&. If you need the -// items in sorted order, use zhashx_keys() and then zlistx_sort()\&. To -// access the key for this item use zhashx_cursor()\&. NOTE: do NOT modify -// the table while iterating\&. -CZMQ_EXPORT void * - zhashx_next (zhashx_t *self); - -// After a successful first/next method, returns the key for the item that -// was returned\&. This is a constant string that you may not modify or -// deallocate, and which lasts as long as the item in the hash\&. After an -// unsuccessful first/next, returns NULL\&. -CZMQ_EXPORT const void * - zhashx_cursor (zhashx_t *self); - -// Add a comment to hash table before saving to disk\&. You can add as many -// comment lines as you like\&. These comment lines are discarded when loading -// the file\&. If you use a null format, all comments are deleted\&. -CZMQ_EXPORT void - zhashx_comment (zhashx_t *self, const char *format, \&.\&.\&.) CHECK_PRINTF (2); - -// Save hash table to a text file in name=value format\&. Hash values must be -// printable strings; keys may not contain \*(Aq=\*(Aq character\&. Returns 0 if OK, -// else \-1 if a file error occurred\&. -CZMQ_EXPORT int - zhashx_save (zhashx_t *self, const char *filename); - -// Load hash table from a text file in name=value format; hash table must -// already exist\&. Hash values must printable strings; keys may not contain -// \*(Aq=\*(Aq character\&. Returns 0 if OK, else \-1 if a file was not readable\&. -CZMQ_EXPORT int - zhashx_load (zhashx_t *self, const char *filename); - -// When a hash table was loaded from a file by zhashx_load, this method will -// reload the file if it has been modified since, and is "stable", i\&.e\&. not -// still changing\&. Returns 0 if OK, \-1 if there was an error reloading the -// file\&. -CZMQ_EXPORT int - zhashx_refresh (zhashx_t *self); - -// Serialize hash table to a binary frame that can be sent in a message\&. -// The packed format is compatible with the \*(Aqdictionary\*(Aq type defined in -// http://rfc\&.zeromq\&.org/spec:35/FILEMQ, and implemented by zproto: -// -// ; A list of name/value pairs -// dictionary = dict\-count *( dict\-name dict\-value ) -// dict\-count = number\-4 -// dict\-value = longstr -// dict\-name = string -// -// ; Strings are always length + text contents -// longstr = number\-4 *VCHAR -// string = number\-1 *VCHAR -// -// ; Numbers are unsigned integers in network byte order -// number\-1 = 1OCTET -// number\-4 = 4OCTET -// -// Comments are not included in the packed data\&. Item values MUST be -// strings\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zframe_t * - zhashx_pack (zhashx_t *self); - -// Make a copy of the list; items are duplicated if you set a duplicator -// for the list, otherwise not\&. Copying a null reference returns a null -// reference\&. Note that this method\*(Aqs behavior changed slightly for CZMQ -// v3\&.x, as it does not set nor respect autofree\&. It does however let you -// duplicate any hash table safely\&. The old behavior is in zhashx_dup_v2\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zhashx_t * - zhashx_dup (zhashx_t *self); - -// Set a user\-defined deallocator for hash items; by default items are not -// freed when the hash is destroyed\&. -CZMQ_EXPORT void - zhashx_set_destructor (zhashx_t *self, zhashx_destructor_fn destructor); - -// Set a user\-defined duplicator for hash items; by default items are not -// copied when the hash is duplicated\&. -CZMQ_EXPORT void - zhashx_set_duplicator (zhashx_t *self, zhashx_duplicator_fn duplicator); - -// Set a user\-defined deallocator for keys; by default keys are freed -// when the hash is destroyed using free()\&. -CZMQ_EXPORT void - zhashx_set_key_destructor (zhashx_t *self, zhashx_destructor_fn destructor); - -// Set a user\-defined duplicator for keys; by default keys are duplicated -// using strdup\&. -CZMQ_EXPORT void - zhashx_set_key_duplicator (zhashx_t *self, zhashx_duplicator_fn duplicator); - -// Set a user\-defined comparator for keys; by default keys are -// compared using strcmp\&. -CZMQ_EXPORT void - zhashx_set_key_comparator (zhashx_t *self, zhashx_comparator_fn comparator); - -// Set a user\-defined comparator for keys; by default keys are -// compared using strcmp\&. -CZMQ_EXPORT void - zhashx_set_key_hasher (zhashx_t *self, zhashx_hash_fn hasher); - -// Make copy of hash table; if supplied table is null, returns null\&. -// Does not copy items themselves\&. Rebuilds new table so may be slow on -// very large tables\&. NOTE: only works with item values that are strings -// since there\*(Aqs no other way to know how to duplicate the item value\&. -CZMQ_EXPORT zhashx_t * - zhashx_dup_v2 (zhashx_t *self); - -// Self test of this class\&. -CZMQ_EXPORT void - zhashx_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Same as unpack but uses a user\-defined deserializer function to convert -// a longstr back into item format\&. -CZMQ_EXPORT zhashx_t * - zhashx_unpack_own (zframe_t *frame, zhashx_deserializer_fn deserializer); - -// *** Draft method, for development use, may change without warning *** -// Same as pack but uses a user\-defined serializer function to convert items -// into longstr\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zframe_t * - zhashx_pack_own (zhashx_t *self, zhashx_serializer_fn serializer); - -#endif // CZMQ_BUILD_DRAFT_API -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zhashx\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -zhashx is an extended hash table container with more functionality than zhash, its simpler cousin\&. -.sp -The hash table always has a size that is prime and roughly doubles its size when 75% full\&. In case of hash collisions items are chained in a linked list\&. The hash table size is increased slightly (up to 5 times before roughly doubling the size) when an overly long chain (between 1 and 63 items depending on table size) is detected\&. -.SH "EXAMPLE" -.PP -\fBFrom zhashx_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -zhashx_t *hash = zhashx_new (); -assert (hash); -assert (zhashx_size (hash) == 0); -assert (zhashx_first (hash) == NULL); -assert (zhashx_cursor (hash) == NULL); - -// Insert some items -int rc; -rc = zhashx_insert (hash, "DEADBEEF", "dead beef"); -char *item = (char *) zhashx_first (hash); -assert (streq ((char *) zhashx_cursor (hash), "DEADBEEF")); -assert (streq (item, "dead beef")); -assert (rc == 0); -rc = zhashx_insert (hash, "ABADCAFE", "a bad cafe"); -assert (rc == 0); -rc = zhashx_insert (hash, "C0DEDBAD", "coded bad"); -assert (rc == 0); -rc = zhashx_insert (hash, "DEADF00D", "dead food"); -assert (rc == 0); -assert (zhashx_size (hash) == 4); - -// Look for existing items -item = (char *) zhashx_lookup (hash, "DEADBEEF"); -assert (streq (item, "dead beef")); -item = (char *) zhashx_lookup (hash, "ABADCAFE"); -assert (streq (item, "a bad cafe")); -item = (char *) zhashx_lookup (hash, "C0DEDBAD"); -assert (streq (item, "coded bad")); -item = (char *) zhashx_lookup (hash, "DEADF00D"); -assert (streq (item, "dead food")); - -// Look for non\-existent items -item = (char *) zhashx_lookup (hash, "foo"); -assert (item == NULL); - -// Try to insert duplicate items -rc = zhashx_insert (hash, "DEADBEEF", "foo"); -assert (rc == \-1); -item = (char *) zhashx_lookup (hash, "DEADBEEF"); -assert (streq (item, "dead beef")); - -// Some rename tests - -// Valid rename, key is now LIVEBEEF -rc = zhashx_rename (hash, "DEADBEEF", "LIVEBEEF"); -assert (rc == 0); -item = (char *) zhashx_lookup (hash, "LIVEBEEF"); -assert (streq (item, "dead beef")); - -// Trying to rename an unknown item to a non\-existent key -rc = zhashx_rename (hash, "WHATBEEF", "NONESUCH"); -assert (rc == \-1); - -// Trying to rename an unknown item to an existing key -rc = zhashx_rename (hash, "WHATBEEF", "LIVEBEEF"); -assert (rc == \-1); -item = (char *) zhashx_lookup (hash, "LIVEBEEF"); -assert (streq (item, "dead beef")); - -// Trying to rename an existing item to another existing item -rc = zhashx_rename (hash, "LIVEBEEF", "ABADCAFE"); -assert (rc == \-1); -item = (char *) zhashx_lookup (hash, "LIVEBEEF"); -assert (streq (item, "dead beef")); -item = (char *) zhashx_lookup (hash, "ABADCAFE"); -assert (streq (item, "a bad cafe")); - -// Test keys method -zlistx_t *keys = zhashx_keys (hash); -assert (zlistx_size (keys) == 4); -zlistx_destroy (&keys); - -zlistx_t *values = zhashx_values(hash); -assert (zlistx_size (values) == 4); -zlistx_destroy (&values); - -// Test dup method -zhashx_t *copy = zhashx_dup (hash); -assert (zhashx_size (copy) == 4); -item = (char *) zhashx_lookup (copy, "LIVEBEEF"); -assert (item); -assert (streq (item, "dead beef")); -zhashx_destroy (©); - -// Test pack/unpack methods -zframe_t *frame = zhashx_pack (hash); -copy = zhashx_unpack (frame); -zframe_destroy (&frame); -assert (zhashx_size (copy) == 4); -item = (char *) zhashx_lookup (copy, "LIVEBEEF"); -assert (item); -assert (streq (item, "dead beef")); -zhashx_destroy (©); - -#ifdef CZMQ_BUILD_DRAFT_API -// Test own pack/unpack methods -zhashx_t *own_hash = zhashx_new (); -zhashx_set_destructor (own_hash, s_test_destroy_int); -assert (own_hash); -int *val1 = (int *) zmalloc (sizeof (int)); -int *val2 = (int *) zmalloc (sizeof (int)); -*val1 = 25; -*val2 = 100; -zhashx_insert (own_hash, "val1", val1); -zhashx_insert (own_hash, "val2", val2); -frame = zhashx_pack_own (own_hash, s_test_serialize_int); -copy = zhashx_unpack_own (frame, s_test_deserialze_int); -zhashx_set_destructor (copy, s_test_destroy_int); -zframe_destroy (&frame); -assert (zhashx_size (copy) == 2); -assert (*((int *) zhashx_lookup (copy, "val1")) == 25); -assert (*((int *) zhashx_lookup (copy, "val2")) == 100); -zhashx_destroy (©); -zhashx_destroy (&own_hash); -#endif // CZMQ_BUILD_DRAFT_API - -// Test save and load -zhashx_comment (hash, "This is a test file"); -zhashx_comment (hash, "Created by %s", "czmq_selftest"); -zhashx_save (hash, "\&.cache"); -copy = zhashx_new (); -assert (copy); -zhashx_load (copy, "\&.cache"); -item = (char *) zhashx_lookup (copy, "LIVEBEEF"); -assert (item); -assert (streq (item, "dead beef")); -zhashx_destroy (©); -zsys_file_delete ("\&.cache"); - -// Delete a item -zhashx_delete (hash, "LIVEBEEF"); -item = (char *) zhashx_lookup (hash, "LIVEBEEF"); -assert (item == NULL); -assert (zhashx_size (hash) == 3); - -// Check that the queue is robust against random usage -struct { - char name [100]; - bool exists; -} testset [200]; -memset (testset, 0, sizeof (testset)); -int testmax = 200, testnbr, iteration; - -srandom ((unsigned) time (NULL)); -for (iteration = 0; iteration < 25000; iteration++) { - testnbr = randof (testmax); - if (testset [testnbr]\&.exists) { - item = (char *) zhashx_lookup (hash, testset [testnbr]\&.name); - assert (item); - zhashx_delete (hash, testset [testnbr]\&.name); - testset [testnbr]\&.exists = false; - } - else { - sprintf (testset [testnbr]\&.name, "%x\-%x", rand (), rand ()); - if (zhashx_insert (hash, testset [testnbr]\&.name, "") == 0) - testset [testnbr]\&.exists = true; - } -} -// Test 10K lookups -for (iteration = 0; iteration < 10000; iteration++) - item = (char *) zhashx_lookup (hash, "DEADBEEFABADCAFE"); - -// Destructor should be safe to call twice -zhashx_destroy (&hash); -zhashx_destroy (&hash); -assert (hash == NULL); - -// Test destructor; automatically copies and frees string values -hash = zhashx_new (); -assert (hash); -zhashx_set_destructor (hash, (zhashx_destructor_fn *) zstr_free); -zhashx_set_duplicator (hash, (zhashx_duplicator_fn *) strdup); -char value [255]; -strcpy (value, "This is a string"); -rc = zhashx_insert (hash, "key1", value); -assert (rc == 0); -strcpy (value, "Ring a ding ding"); -rc = zhashx_insert (hash, "key2", value); -assert (rc == 0); -assert (streq ((char *) zhashx_lookup (hash, "key1"), "This is a string")); -assert (streq ((char *) zhashx_lookup (hash, "key2"), "Ring a ding ding")); -zhashx_destroy (&hash); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/ziflist.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/ziflist.3 deleted file mode 100644 index b50b06c0f3..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/ziflist.3 +++ /dev/null @@ -1,134 +0,0 @@ -'\" t -.\" Title: ziflist -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZIFLIST" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -ziflist \- list of network interfaces available on system -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// Get a list of network interfaces currently defined on the system -CZMQ_EXPORT ziflist_t * - ziflist_new (void); - -// Destroy a ziflist instance -CZMQ_EXPORT void - ziflist_destroy (ziflist_t **self_p); - -// Reload network interfaces from system -CZMQ_EXPORT void - ziflist_reload (ziflist_t *self); - -// Return the number of network interfaces on system -CZMQ_EXPORT size_t - ziflist_size (ziflist_t *self); - -// Get first network interface, return NULL if there are none -CZMQ_EXPORT const char * - ziflist_first (ziflist_t *self); - -// Get next network interface, return NULL if we hit the last one -CZMQ_EXPORT const char * - ziflist_next (ziflist_t *self); - -// Return the current interface IP address as a printable string -CZMQ_EXPORT const char * - ziflist_address (ziflist_t *self); - -// Return the current interface broadcast address as a printable string -CZMQ_EXPORT const char * - ziflist_broadcast (ziflist_t *self); - -// Return the current interface network mask as a printable string -CZMQ_EXPORT const char * - ziflist_netmask (ziflist_t *self); - -// Return the list of interfaces\&. -CZMQ_EXPORT void - ziflist_print (ziflist_t *self); - -// Self test of this class\&. -CZMQ_EXPORT void - ziflist_test (bool verbose); - -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/ziflist\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -The ziflist class takes a snapshot of the network interfaces that the system currently supports (this can change arbitrarily, especially on mobile devices)\&. The caller can then access the network interface information using an iterator that works like zlistx\&. Only stores those interfaces with broadcast capability, and ignores the loopback interface\&. -.sp -Please add \fI@discuss\fR section in \fI\&./\&.\&./src/ziflist\&.c\fR\&. -.SH "EXAMPLE" -.PP -\fBFrom ziflist_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -ziflist_t *iflist = ziflist_new (); -assert (iflist); - -size_t items = ziflist_size (iflist); - -if (verbose) { - printf ("ziflist: interfaces=%zu\en", ziflist_size (iflist)); - const char *name = ziflist_first (iflist); - while (name) { - printf (" \- name=%s address=%s netmask=%s broadcast=%s\en", - name, ziflist_address (iflist), ziflist_netmask (iflist), ziflist_broadcast (iflist)); - name = ziflist_next (iflist); - } -} -ziflist_reload (iflist); -assert (items == ziflist_size (iflist)); -ziflist_destroy (&iflist); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zlist.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zlist.3 deleted file mode 100644 index a7131f40e0..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zlist.3 +++ /dev/null @@ -1,316 +0,0 @@ -'\" t -.\" Title: zlist -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZLIST" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zlist \- simple generic list container -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// Comparison function e\&.g\&. for sorting and removing\&. -typedef int (zlist_compare_fn) ( - void *item1, void *item2); - -// Callback function for zlist_freefn method -typedef void (zlist_free_fn) ( - void *data); - -// Create a new list container -CZMQ_EXPORT zlist_t * - zlist_new (void); - -// Destroy a list container -CZMQ_EXPORT void - zlist_destroy (zlist_t **self_p); - -// Return the item at the head of list\&. If the list is empty, returns NULL\&. -// Leaves cursor pointing at the head item, or NULL if the list is empty\&. -CZMQ_EXPORT void * - zlist_first (zlist_t *self); - -// Return the next item\&. If the list is empty, returns NULL\&. To move to -// the start of the list call zlist_first ()\&. Advances the cursor\&. -CZMQ_EXPORT void * - zlist_next (zlist_t *self); - -// Return the item at the tail of list\&. If the list is empty, returns NULL\&. -// Leaves cursor pointing at the tail item, or NULL if the list is empty\&. -CZMQ_EXPORT void * - zlist_last (zlist_t *self); - -// Return first item in the list, or null, leaves the cursor -CZMQ_EXPORT void * - zlist_head (zlist_t *self); - -// Return last item in the list, or null, leaves the cursor -CZMQ_EXPORT void * - zlist_tail (zlist_t *self); - -// Return the current item of list\&. If the list is empty, returns NULL\&. -// Leaves cursor pointing at the current item, or NULL if the list is empty\&. -CZMQ_EXPORT void * - zlist_item (zlist_t *self); - -// Append an item to the end of the list, return 0 if OK or \-1 if this -// failed for some reason (out of memory)\&. Note that if a duplicator has -// been set, this method will also duplicate the item\&. -CZMQ_EXPORT int - zlist_append (zlist_t *self, void *item); - -// Push an item to the start of the list, return 0 if OK or \-1 if this -// failed for some reason (out of memory)\&. Note that if a duplicator has -// been set, this method will also duplicate the item\&. -CZMQ_EXPORT int - zlist_push (zlist_t *self, void *item); - -// Pop the item off the start of the list, if any -CZMQ_EXPORT void * - zlist_pop (zlist_t *self); - -// Checks if an item already is present\&. Uses compare method to determine if -// items are equal\&. If the compare method is NULL the check will only compare -// pointers\&. Returns true if item is present else false\&. -CZMQ_EXPORT bool - zlist_exists (zlist_t *self, void *item); - -// Remove the specified item from the list if present -CZMQ_EXPORT void - zlist_remove (zlist_t *self, void *item); - -// Make a copy of list\&. If the list has autofree set, the copied list will -// duplicate all items, which must be strings\&. Otherwise, the list will hold -// pointers back to the items in the original list\&. If list is null, returns -// NULL\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zlist_t * - zlist_dup (zlist_t *self); - -// Purge all items from list -CZMQ_EXPORT void - zlist_purge (zlist_t *self); - -// Return number of items in the list -CZMQ_EXPORT size_t - zlist_size (zlist_t *self); - -// Sort the list\&. If the compare function is null, sorts the list by -// ascending key value using a straight ASCII comparison\&. If you specify -// a compare function, this decides how items are sorted\&. The sort is not -// stable, so may reorder items with the same keys\&. The algorithm used is -// combsort, a compromise between performance and simplicity\&. -CZMQ_EXPORT void - zlist_sort (zlist_t *self, zlist_compare_fn compare); - -// Set list for automatic item destruction; item values MUST be strings\&. -// By default a list item refers to a value held elsewhere\&. When you set -// this, each time you append or push a list item, zlist will take a copy -// of the string value\&. Then, when you destroy the list, it will free all -// item values automatically\&. If you use any other technique to allocate -// list values, you must free them explicitly before destroying the list\&. -// The usual technique is to pop list items and destroy them, until the -// list is empty\&. -CZMQ_EXPORT void - zlist_autofree (zlist_t *self); - -// Sets a compare function for this list\&. The function compares two items\&. -// It returns an integer less than, equal to, or greater than zero if the -// first item is found, respectively, to be less than, to match, or be -// greater than the second item\&. -// This function is used for sorting, removal and exists checking\&. -CZMQ_EXPORT void - zlist_comparefn (zlist_t *self, zlist_compare_fn fn); - -// Set a free function for the specified list item\&. When the item is -// destroyed, the free function, if any, is called on that item\&. -// Use this when list items are dynamically allocated, to ensure that -// you don\*(Aqt have memory leaks\&. You can pass \*(Aqfree\*(Aq or NULL as a free_fn\&. -// Returns the item, or NULL if there is no such item\&. -CZMQ_EXPORT void * - zlist_freefn (zlist_t *self, void *item, zlist_free_fn fn, bool at_tail); - -// Self test of this class\&. -CZMQ_EXPORT void - zlist_test (bool verbose); - -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zlist\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -Provides a generic container implementing a fast singly\-linked list\&. You can use this to construct multi\-dimensional lists, and other structures together with other generic containers like zhash\&. This is a simple class\&. For demanding applications we recommend using zlistx\&. -.sp -To iterate through a list, use zlist_first to get the first item, then loop while not null, and do zlist_next at the end of each iteration\&. -.SH "EXAMPLE" -.PP -\fBFrom zlist_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -zlist_t *list = zlist_new (); -assert (list); -assert (zlist_size (list) == 0); - -// Three items we\*(Aqll use as test data -// List items are void *, not particularly strings -char *cheese = "boursin"; -char *bread = "baguette"; -char *wine = "bordeaux"; - -zlist_append (list, cheese); -assert (zlist_size (list) == 1); -assert ( zlist_exists (list, cheese)); -assert (!zlist_exists (list, bread)); -assert (!zlist_exists (list, wine)); -zlist_append (list, bread); -assert (zlist_size (list) == 2); -assert ( zlist_exists (list, cheese)); -assert ( zlist_exists (list, bread)); -assert (!zlist_exists (list, wine)); -zlist_append (list, wine); -assert (zlist_size (list) == 3); -assert ( zlist_exists (list, cheese)); -assert ( zlist_exists (list, bread)); -assert ( zlist_exists (list, wine)); - -assert (zlist_head (list) == cheese); -assert (zlist_next (list) == cheese); - -assert (zlist_first (list) == cheese); -assert (zlist_tail (list) == wine); -assert (zlist_next (list) == bread); - -assert (zlist_first (list) == cheese); -assert (zlist_next (list) == bread); -assert (zlist_next (list) == wine); -assert (zlist_next (list) == NULL); -// After we reach end of list, next wraps around -assert (zlist_next (list) == cheese); -assert (zlist_size (list) == 3); - -zlist_remove (list, wine); -assert (zlist_size (list) == 2); - -assert (zlist_first (list) == cheese); -zlist_remove (list, cheese); -assert (zlist_size (list) == 1); -assert (zlist_first (list) == bread); - -zlist_remove (list, bread); -assert (zlist_size (list) == 0); - -zlist_append (list, cheese); -zlist_append (list, bread); -assert (zlist_last (list) == bread); -zlist_remove (list, bread); -assert (zlist_last (list) == cheese); -zlist_remove (list, cheese); -assert (zlist_last (list) == NULL); - -zlist_push (list, cheese); -assert (zlist_size (list) == 1); -assert (zlist_first (list) == cheese); - -zlist_push (list, bread); -assert (zlist_size (list) == 2); -assert (zlist_first (list) == bread); -assert (zlist_item (list) == bread); - -zlist_append (list, wine); -assert (zlist_size (list) == 3); -assert (zlist_first (list) == bread); - -zlist_t *sub_list = zlist_dup (list); -assert (sub_list); -assert (zlist_size (sub_list) == 3); - -zlist_sort (list, NULL); -char *item; -item = (char *) zlist_pop (list); -assert (item == bread); -item = (char *) zlist_pop (list); -assert (item == wine); -item = (char *) zlist_pop (list); -assert (item == cheese); -assert (zlist_size (list) == 0); - -assert (zlist_size (sub_list) == 3); -zlist_push (list, sub_list); -zlist_t *sub_list_2 = zlist_dup (sub_list); -zlist_append (list, sub_list_2); -assert (zlist_freefn (list, sub_list, &s_zlist_free, false) == sub_list); -assert (zlist_freefn (list, sub_list_2, &s_zlist_free, true) == sub_list_2); -zlist_destroy (&list); - -// Test autofree functionality -list = zlist_new (); -assert (list); -zlist_autofree (list); -// Set equals function otherwise equals will not work as autofree copies strings -zlist_comparefn (list, (zlist_compare_fn *) strcmp); -zlist_push (list, bread); -zlist_append (list, cheese); -assert (zlist_size (list) == 2); -zlist_append (list, wine); -assert (zlist_exists (list, wine)); -zlist_remove (list, wine); -assert (!zlist_exists (list, wine)); -assert (streq ((const char *) zlist_first (list), bread)); -item = (char *) zlist_pop (list); -assert (streq (item, bread)); -free (item); -item = (char *) zlist_pop (list); -assert (streq (item, cheese)); -free (item); - -zlist_destroy (&list); -assert (list == NULL); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zlistx.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zlistx.3 deleted file mode 100644 index 2e1068554b..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zlistx.3 +++ /dev/null @@ -1,346 +0,0 @@ -'\" t -.\" Title: zlistx -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZLISTX" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zlistx \- extended generic list container -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// Destroy an item -typedef void (zlistx_destructor_fn) ( - void **item); - -// Duplicate an item -typedef void * (zlistx_duplicator_fn) ( - const void *item); - -// Compare two items, for sorting -typedef int (zlistx_comparator_fn) ( - const void *item1, const void *item2); - -// Create a new, empty list\&. -CZMQ_EXPORT zlistx_t * - zlistx_new (void); - -// Destroy a list\&. If an item destructor was specified, all items in the -// list are automatically destroyed as well\&. -CZMQ_EXPORT void - zlistx_destroy (zlistx_t **self_p); - -// Add an item to the head of the list\&. Calls the item duplicator, if any, -// on the item\&. Resets cursor to list head\&. Returns an item handle on -// success, NULL if memory was exhausted\&. -CZMQ_EXPORT void * - zlistx_add_start (zlistx_t *self, void *item); - -// Add an item to the tail of the list\&. Calls the item duplicator, if any, -// on the item\&. Resets cursor to list head\&. Returns an item handle on -// success, NULL if memory was exhausted\&. -CZMQ_EXPORT void * - zlistx_add_end (zlistx_t *self, void *item); - -// Return the number of items in the list -CZMQ_EXPORT size_t - zlistx_size (zlistx_t *self); - -// Return first item in the list, or null, leaves the cursor -CZMQ_EXPORT void * - zlistx_head (zlistx_t *self); - -// Return last item in the list, or null, leaves the cursor -CZMQ_EXPORT void * - zlistx_tail (zlistx_t *self); - -// Return the item at the head of list\&. If the list is empty, returns NULL\&. -// Leaves cursor pointing at the head item, or NULL if the list is empty\&. -CZMQ_EXPORT void * - zlistx_first (zlistx_t *self); - -// Return the next item\&. At the end of the list (or in an empty list), -// returns NULL\&. Use repeated zlistx_next () calls to work through the list -// from zlistx_first ()\&. First time, acts as zlistx_first()\&. -CZMQ_EXPORT void * - zlistx_next (zlistx_t *self); - -// Return the previous item\&. At the start of the list (or in an empty list), -// returns NULL\&. Use repeated zlistx_prev () calls to work through the list -// backwards from zlistx_last ()\&. First time, acts as zlistx_last()\&. -CZMQ_EXPORT void * - zlistx_prev (zlistx_t *self); - -// Return the item at the tail of list\&. If the list is empty, returns NULL\&. -// Leaves cursor pointing at the tail item, or NULL if the list is empty\&. -CZMQ_EXPORT void * - zlistx_last (zlistx_t *self); - -// Returns the value of the item at the cursor, or NULL if the cursor is -// not pointing to an item\&. -CZMQ_EXPORT void * - zlistx_item (zlistx_t *self); - -// Returns the handle of the item at the cursor, or NULL if the cursor is -// not pointing to an item\&. -CZMQ_EXPORT void * - zlistx_cursor (zlistx_t *self); - -// Returns the item associated with the given list handle, or NULL if passed -// in handle is NULL\&. Asserts that the passed in handle points to a list element\&. -CZMQ_EXPORT void * - zlistx_handle_item (void *handle); - -// Find an item in the list, searching from the start\&. Uses the item -// comparator, if any, else compares item values directly\&. Returns the -// item handle found, or NULL\&. Sets the cursor to the found item, if any\&. -CZMQ_EXPORT void * - zlistx_find (zlistx_t *self, void *item); - -// Detach an item from the list, using its handle\&. The item is not modified, -// and the caller is responsible for destroying it if necessary\&. If handle is -// null, detaches the first item on the list\&. Returns item that was detached, -// or null if none was\&. If cursor was at item, moves cursor to previous item, -// so you can detach items while iterating forwards through a list\&. -CZMQ_EXPORT void * - zlistx_detach (zlistx_t *self, void *handle); - -// Detach item at the cursor, if any, from the list\&. The item is not modified, -// and the caller is responsible for destroying it as necessary\&. Returns item -// that was detached, or null if none was\&. Moves cursor to previous item, so -// you can detach items while iterating forwards through a list\&. -CZMQ_EXPORT void * - zlistx_detach_cur (zlistx_t *self); - -// Delete an item, using its handle\&. Calls the item destructor is any is -// set\&. If handle is null, deletes the first item on the list\&. Returns 0 -// if an item was deleted, \-1 if not\&. If cursor was at item, moves cursor -// to previous item, so you can delete items while iterating forwards -// through a list\&. -CZMQ_EXPORT int - zlistx_delete (zlistx_t *self, void *handle); - -// Move an item to the start of the list, via its handle\&. -CZMQ_EXPORT void - zlistx_move_start (zlistx_t *self, void *handle); - -// Move an item to the end of the list, via its handle\&. -CZMQ_EXPORT void - zlistx_move_end (zlistx_t *self, void *handle); - -// Remove all items from the list, and destroy them if the item destructor -// is set\&. -CZMQ_EXPORT void - zlistx_purge (zlistx_t *self); - -// Sort the list\&. If an item comparator was set, calls that to compare -// items, otherwise compares on item value\&. The sort is not stable, so may -// reorder equal items\&. -CZMQ_EXPORT void - zlistx_sort (zlistx_t *self); - -// Create a new node and insert it into a sorted list\&. Calls the item -// duplicator, if any, on the item\&. If low_value is true, starts searching -// from the start of the list, otherwise searches from the end\&. Use the item -// comparator, if any, to find where to place the new node\&. Returns a handle -// to the new node, or NULL if memory was exhausted\&. Resets the cursor to the -// list head\&. -CZMQ_EXPORT void * - zlistx_insert (zlistx_t *self, void *item, bool low_value); - -// Move an item, specified by handle, into position in a sorted list\&. Uses -// the item comparator, if any, to determine the new location\&. If low_value -// is true, starts searching from the start of the list, otherwise searches -// from the end\&. -CZMQ_EXPORT void - zlistx_reorder (zlistx_t *self, void *handle, bool low_value); - -// Make a copy of the list; items are duplicated if you set a duplicator -// for the list, otherwise not\&. Copying a null reference returns a null -// reference\&. -CZMQ_EXPORT zlistx_t * - zlistx_dup (zlistx_t *self); - -// Set a user\-defined deallocator for list items; by default items are not -// freed when the list is destroyed\&. -CZMQ_EXPORT void - zlistx_set_destructor (zlistx_t *self, zlistx_destructor_fn destructor); - -// Set a user\-defined duplicator for list items; by default items are not -// copied when the list is duplicated\&. -CZMQ_EXPORT void - zlistx_set_duplicator (zlistx_t *self, zlistx_duplicator_fn duplicator); - -// Set a user\-defined comparator for zlistx_find and zlistx_sort; the method -// must return \-1, 0, or 1 depending on whether item1 is less than, equal to, -// or greater than, item2\&. -CZMQ_EXPORT void - zlistx_set_comparator (zlistx_t *self, zlistx_comparator_fn comparator); - -// Self test of this class\&. -CZMQ_EXPORT void - zlistx_test (bool verbose); - -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zlistx\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -Provides a generic doubly\-linked list container\&. This container provides hooks for duplicator, comparator, and destructor functions\&. These tie into CZMQ and standard C semantics, so e\&.g\&. for string items you can use strdup, strcmp, and zstr_free\&. To store custom objects, define your own duplicator and comparator, and use the standard object destructor\&. -.sp -This is a reworking of the simpler zlist container\&. It is faster to insert and delete items anywhere in the list, and to keep ordered lists\&. -.SH "EXAMPLE" -.PP -\fBFrom zlistx_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -zlistx_t *list = zlistx_new (); -assert (list); -assert (zlistx_size (list) == 0); - -// Test operations on an empty list -assert (zlistx_first (list) == NULL); -assert (zlistx_last (list) == NULL); -assert (zlistx_next (list) == NULL); -assert (zlistx_prev (list) == NULL); -assert (zlistx_find (list, "hello") == NULL); -assert (zlistx_delete (list, NULL) == \-1); -assert (zlistx_detach (list, NULL) == NULL); -assert (zlistx_delete (list, NULL) == \-1); -assert (zlistx_detach (list, NULL) == NULL); -zlistx_purge (list); -zlistx_sort (list); - -// Use item handlers -zlistx_set_destructor (list, (zlistx_destructor_fn *) zstr_free); -zlistx_set_duplicator (list, (zlistx_duplicator_fn *) strdup); -zlistx_set_comparator (list, (zlistx_comparator_fn *) strcmp); - -// Try simple insert/sort/delete/next -assert (zlistx_next (list) == NULL); -zlistx_add_end (list, "world"); -assert (streq ((char *) zlistx_next (list), "world")); -zlistx_add_end (list, "hello"); -assert (streq ((char *) zlistx_prev (list), "hello")); -zlistx_sort (list); -assert (zlistx_size (list) == 2); -void *handle = zlistx_find (list, "hello"); -char *item1 = (char *) zlistx_item (list); -char *item2 = (char *) zlistx_handle_item (handle); -assert (item1 == item2); -assert (streq (item1, "hello")); -zlistx_delete (list, handle); -assert (zlistx_size (list) == 1); -char *string = (char *) zlistx_detach (list, NULL); -assert (streq (string, "world")); -free (string); -assert (zlistx_size (list) == 0); - -// Check next/back work -// Now populate the list with items -zlistx_add_start (list, "five"); -zlistx_add_end (list, "six"); -zlistx_add_start (list, "four"); -zlistx_add_end (list, "seven"); -zlistx_add_start (list, "three"); -zlistx_add_end (list, "eight"); -zlistx_add_start (list, "two"); -zlistx_add_end (list, "nine"); -zlistx_add_start (list, "one"); -zlistx_add_end (list, "ten"); - -// Test our navigation skills -assert (zlistx_size (list) == 10); -assert (streq ((char *) zlistx_last (list), "ten")); -assert (streq ((char *) zlistx_prev (list), "nine")); -assert (streq ((char *) zlistx_prev (list), "eight")); -assert (streq ((char *) zlistx_prev (list), "seven")); -assert (streq ((char *) zlistx_prev (list), "six")); -assert (streq ((char *) zlistx_prev (list), "five")); -assert (streq ((char *) zlistx_first (list), "one")); -assert (streq ((char *) zlistx_next (list), "two")); -assert (streq ((char *) zlistx_next (list), "three")); -assert (streq ((char *) zlistx_next (list), "four")); - -// Sort by alphabetical order -zlistx_sort (list); -assert (streq ((char *) zlistx_first (list), "eight")); -assert (streq ((char *) zlistx_last (list), "two")); - -// Moving items around -handle = zlistx_find (list, "six"); -zlistx_move_start (list, handle); -assert (streq ((char *) zlistx_first (list), "six")); -zlistx_move_end (list, handle); -assert (streq ((char *) zlistx_last (list), "six")); -zlistx_sort (list); -assert (streq ((char *) zlistx_last (list), "two")); - -// Copying a list -zlistx_t *copy = zlistx_dup (list); -assert (copy); -assert (zlistx_size (copy) == 10); -assert (streq ((char *) zlistx_first (copy), "eight")); -assert (streq ((char *) zlistx_last (copy), "two")); -zlistx_destroy (©); - -// Delete items while iterating -string = (char *) zlistx_first (list); -assert (streq (string, "eight")); -string = (char *) zlistx_next (list); -assert (streq (string, "five")); -zlistx_delete (list, zlistx_cursor (list)); -string = (char *) zlistx_next (list); -assert (streq (string, "four")); - -zlistx_purge (list); -zlistx_destroy (&list); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zloop.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zloop.3 deleted file mode 100644 index 7d5c84949f..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zloop.3 +++ /dev/null @@ -1,261 +0,0 @@ -'\" t -.\" Title: zloop -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZLOOP" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zloop \- event\-driven reactor -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// Callback function for reactor socket activity -typedef int (zloop_reader_fn) ( - zloop_t *loop, zsock_t *reader, void *arg); - -// Callback function for reactor events (low\-level) -typedef int (zloop_fn) ( - zloop_t *loop, zmq_pollitem_t *item, void *arg); - -// Callback for reactor timer events -typedef int (zloop_timer_fn) ( - zloop_t *loop, int timer_id, void *arg); - -// Create a new zloop reactor -CZMQ_EXPORT zloop_t * - zloop_new (void); - -// Destroy a reactor -CZMQ_EXPORT void - zloop_destroy (zloop_t **self_p); - -// Register socket reader with the reactor\&. When the reader has messages, -// the reactor will call the handler, passing the arg\&. Returns 0 if OK, \-1 -// if there was an error\&. If you register the same socket more than once, -// each instance will invoke its corresponding handler\&. -CZMQ_EXPORT int - zloop_reader (zloop_t *self, zsock_t *sock, zloop_reader_fn handler, void *arg); - -// Cancel a socket reader from the reactor\&. If multiple readers exist for -// same socket, cancels ALL of them\&. -CZMQ_EXPORT void - zloop_reader_end (zloop_t *self, zsock_t *sock); - -// Configure a registered reader to ignore errors\&. If you do not set this, -// then readers that have errors are removed from the reactor silently\&. -CZMQ_EXPORT void - zloop_reader_set_tolerant (zloop_t *self, zsock_t *sock); - -// Register low\-level libzmq pollitem with the reactor\&. When the pollitem -// is ready, will call the handler, passing the arg\&. Returns 0 if OK, \-1 -// if there was an error\&. If you register the pollitem more than once, each -// instance will invoke its corresponding handler\&. A pollitem with -// socket=NULL and fd=0 means \*(Aqpoll on FD zero\*(Aq\&. -CZMQ_EXPORT int - zloop_poller (zloop_t *self, zmq_pollitem_t *item, zloop_fn handler, void *arg); - -// Cancel a pollitem from the reactor, specified by socket or FD\&. If both -// are specified, uses only socket\&. If multiple poll items exist for same -// socket/FD, cancels ALL of them\&. -CZMQ_EXPORT void - zloop_poller_end (zloop_t *self, zmq_pollitem_t *item); - -// Configure a registered poller to ignore errors\&. If you do not set this, -// then poller that have errors are removed from the reactor silently\&. -CZMQ_EXPORT void - zloop_poller_set_tolerant (zloop_t *self, zmq_pollitem_t *item); - -// Register a timer that expires after some delay and repeats some number of -// times\&. At each expiry, will call the handler, passing the arg\&. To run a -// timer forever, use 0 times\&. Returns a timer_id that is used to cancel the -// timer in the future\&. Returns \-1 if there was an error\&. -CZMQ_EXPORT int - zloop_timer (zloop_t *self, size_t delay, size_t times, zloop_timer_fn handler, void *arg); - -// Cancel a specific timer identified by a specific timer_id (as returned by -// zloop_timer)\&. -CZMQ_EXPORT int - zloop_timer_end (zloop_t *self, int timer_id); - -// Register a ticket timer\&. Ticket timers are very fast in the case where -// you use a lot of timers (thousands), and frequently remove and add them\&. -// The main use case is expiry timers for servers that handle many clients, -// and which reset the expiry timer for each message received from a client\&. -// Whereas normal timers perform poorly as the number of clients grows, the -// cost of ticket timers is constant, no matter the number of clients\&. You -// must set the ticket delay using zloop_set_ticket_delay before creating a -// ticket\&. Returns a handle to the timer that you should use in -// zloop_ticket_reset and zloop_ticket_delete\&. -CZMQ_EXPORT void * - zloop_ticket (zloop_t *self, zloop_timer_fn handler, void *arg); - -// Reset a ticket timer, which moves it to the end of the ticket list and -// resets its execution time\&. This is a very fast operation\&. -CZMQ_EXPORT void - zloop_ticket_reset (zloop_t *self, void *handle); - -// Delete a ticket timer\&. We do not actually delete the ticket here, as -// other code may still refer to the ticket\&. We mark as deleted, and remove -// later and safely\&. -CZMQ_EXPORT void - zloop_ticket_delete (zloop_t *self, void *handle); - -// Set the ticket delay, which applies to all tickets\&. If you lower the -// delay and there are already tickets created, the results are undefined\&. -CZMQ_EXPORT void - zloop_set_ticket_delay (zloop_t *self, size_t ticket_delay); - -// Set hard limit on number of timers allowed\&. Setting more than a small -// number of timers (10\-100) can have a dramatic impact on the performance -// of the reactor\&. For high\-volume cases, use ticket timers\&. If the hard -// limit is reached, the reactor stops creating new timers and logs an -// error\&. -CZMQ_EXPORT void - zloop_set_max_timers (zloop_t *self, size_t max_timers); - -// Set verbose tracing of reactor on/off\&. The default verbose setting is -// off (false)\&. -CZMQ_EXPORT void - zloop_set_verbose (zloop_t *self, bool verbose); - -// By default the reactor stops if the process receives a SIGINT or SIGTERM -// signal\&. This makes it impossible to shut\-down message based architectures -// like zactors\&. This method lets you switch off break handling\&. The default -// nonstop setting is off (false)\&. -CZMQ_EXPORT void - zloop_set_nonstop (zloop_t *self, bool nonstop); - -// Start the reactor\&. Takes control of the thread and returns when the 0MQ -// context is terminated or the process is interrupted, or any event handler -// returns \-1\&. Event handlers may register new sockets and timers, and -// cancel sockets\&. Returns 0 if interrupted, \-1 if canceled by a handler\&. -CZMQ_EXPORT int - zloop_start (zloop_t *self); - -// Self test of this class\&. -CZMQ_EXPORT void - zloop_test (bool verbose); - -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zloop\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -The zloop class provides an event\-driven reactor pattern\&. The reactor handles zmq_pollitem_t items (pollers or writers, sockets or fds), and once\-off or repeated timers\&. Its resolution is 1 msec\&. It uses a tickless timer to reduce CPU interrupts in inactive processes\&. -.sp -Please add \fI@discuss\fR section in \fI\&./\&.\&./src/zloop\&.c\fR\&. -.SH "EXAMPLE" -.PP -\fBFrom zloop_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Create two PAIR sockets and connect over inproc -zsock_t *output = zsock_new (ZMQ_PAIR); -assert (output); -zsock_bind (output, "inproc://zloop\&.test"); - -zsock_t *input = zsock_new (ZMQ_PAIR); -assert (input); -zsock_connect (input, "inproc://zloop\&.test"); - -zloop_t *loop = zloop_new (); -assert (loop); -zloop_set_verbose (loop, verbose); - -// Create a timer that will be cancelled -int timer_id = zloop_timer (loop, 1000, 1, s_timer_event, NULL); -zloop_timer (loop, 5, 1, s_cancel_timer_event, &timer_id); - -// After 20 msecs, send a ping message to output3 -zloop_timer (loop, 20, 1, s_timer_event, output); - -// Set up some tickets that will never expire -zloop_set_ticket_delay (loop, 10000); -void *ticket1 = zloop_ticket (loop, s_timer_event, NULL); -void *ticket2 = zloop_ticket (loop, s_timer_event, NULL); -void *ticket3 = zloop_ticket (loop, s_timer_event, NULL); - -// When we get the ping message, end the reactor -rc = zloop_reader (loop, input, s_socket_event, NULL); -assert (rc == 0); -zloop_reader_set_tolerant (loop, input); -zloop_start (loop); - -zloop_ticket_delete (loop, ticket1); -zloop_ticket_delete (loop, ticket2); -zloop_ticket_delete (loop, ticket3); - -// Check whether loop properly ignores zsys_interrupted flag -// when asked to -zloop_destroy (&loop); -loop = zloop_new (); - -bool timer_event_called = false; -zloop_timer (loop, 1, 1, s_timer_event3, &timer_event_called); - -zsys_interrupted = 1; -zloop_start (loop); -// zloop returns immediately without giving any handler a chance to run -assert (!timer_event_called); - -zloop_set_nonstop (loop, true); -zloop_start (loop); -// zloop runs the handler which will terminate the loop -assert (timer_event_called); -zsys_interrupted = 0; - -// cleanup -zloop_destroy (&loop); -assert (loop == NULL); - -zsock_destroy (&input); -zsock_destroy (&output); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmonitor.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmonitor.3 deleted file mode 100644 index 8d716863d4..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmonitor.3 +++ /dev/null @@ -1,157 +0,0 @@ -'\" t -.\" Title: zmonitor -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZMONITOR" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmonitor \- socket event monitor -.SH "SYNOPSIS" -.sp -.nf -// Create new zmonitor actor instance to monitor a zsock_t socket: -// -// zactor_t *monitor = zactor_new (zmonitor, mysocket); -// -// Destroy zmonitor instance\&. -// -// zactor_destroy (&monitor); -// -// Enable verbose logging of commands and activity\&. -// -// zstr_send (monitor, "VERBOSE"); -// -// Listen to monitor event type (zero or types, ending in NULL): -// zstr_sendx (monitor, "LISTEN", type, \&.\&.\&., NULL); -// -// Events: -// CONNECTED -// CONNECT_DELAYED -// CONNECT_RETRIED -// LISTENING -// BIND_FAILED -// ACCEPTED -// ACCEPT_FAILED -// CLOSED -// CLOSE_FAILED -// DISCONNECTED -// MONITOR_STOPPED -// ALL -// -// Start monitor; after this, any further LISTEN commands are ignored\&. -// -// zstr_send (monitor, "START"); -// zsock_wait (monitor); -// -// Receive next monitor event: -// -// zmsg_t *msg = zmsg_recv (monitor); -// -// This is the zmonitor constructor as a zactor_fn; the argument can be -// a zactor_t, zsock_t, or libzmq void * socket: -CZMQ_EXPORT void - zmonitor (zsock_t *pipe, void *sock); - -// Selftest -CZMQ_EXPORT void - zmonitor_test (bool verbose); -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zmonitor\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -The zmonitor actor provides an API for obtaining socket events such as connected, listen, disconnected, etc\&. Socket events are only available for sockets connecting or bound to ipc:// and tcp:// endpoints\&. -.sp -This class wraps the ZMQ socket monitor API, see zmq_socket_monitor for details\&. Works on all versions of libzmq from 3\&.2 onwards\&. This class replaces zproxy_v2, and is meant for applications that use the CZMQ v3 API (meaning, zsock)\&. -.SH "EXAMPLE" -.PP -\fBFrom zmonitor_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -zsock_t *client = zsock_new (ZMQ_DEALER); -assert (client); -zactor_t *clientmon = zactor_new (zmonitor, client); -assert (clientmon); -if (verbose) - zstr_sendx (clientmon, "VERBOSE", NULL); -zstr_sendx (clientmon, "LISTEN", "LISTENING", "ACCEPTED", NULL); -zstr_sendx (clientmon, "START", NULL); -zsock_wait (clientmon); - -zsock_t *server = zsock_new (ZMQ_DEALER); -assert (server); -zactor_t *servermon = zactor_new (zmonitor, server); -assert (servermon); -if (verbose) - zstr_sendx (servermon, "VERBOSE", NULL); -zstr_sendx (servermon, "LISTEN", "CONNECTED", "DISCONNECTED", NULL); -zstr_sendx (servermon, "START", NULL); -zsock_wait (servermon); - -// Allow a brief time for the message to get there\&.\&.\&. -zmq_poll (NULL, 0, 200); - -// Check client is now listening -int port_nbr = zsock_bind (client, "tcp://127\&.0\&.0\&.1:*"); -assert (port_nbr != \-1); -s_assert_event (clientmon, "LISTENING"); - -// Check server connected to client -zsock_connect (server, "tcp://127\&.0\&.0\&.1:%d", port_nbr); -s_assert_event (servermon, "CONNECTED"); - -// Check client accepted connection -s_assert_event (clientmon, "ACCEPTED"); - -zactor_destroy (&clientmon); -zactor_destroy (&servermon); -zsock_destroy (&client); -zsock_destroy (&server); -#endif -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_atomic_counter_dec.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_atomic_counter_dec.3 deleted file mode 100644 index 40fde8be8d..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_atomic_counter_dec.3 +++ /dev/null @@ -1,73 +0,0 @@ -'\" t -.\" Title: zmq_atomic_counter_dec -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_ATOMIC_COUNTER_D" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_atomic_counter_dec \- decrement an atomic counter -.SH "SYNOPSIS" -.sp -\fBint zmq_atomic_counter_dec (void *counter);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_atomic_counter_dec\fR function decrements an atomic counter in a threadsafe fashion\&. This function uses platform specific atomic operations\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_atomic_counter_dec()\fR function returns 1 if the counter is greater than zero after decrementing, or zero if the counter reached zero\&. -.SH "EXAMPLE" -.PP -\fBTest code for atomic counters\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -void *counter = zmq_atomic_counter_new (); -assert (zmq_atomic_counter_value (counter) == 0); -assert (zmq_atomic_counter_inc (counter) == 0); -assert (zmq_atomic_counter_inc (counter) == 1); -assert (zmq_atomic_counter_inc (counter) == 2); -assert (zmq_atomic_counter_value (counter) == 3); -assert (zmq_atomic_counter_dec (counter) == 1); -assert (zmq_atomic_counter_dec (counter) == 1); -assert (zmq_atomic_counter_dec (counter) == 0); -zmq_atomic_counter_set (counter, 2); -assert (zmq_atomic_counter_dec (counter) == 1); -assert (zmq_atomic_counter_dec (counter) == 0); -zmq_atomic_counter_destroy (&counter); -return 0; -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_atomic_counter_new\fR(3) \fBzmq_atomic_counter_set\fR(3) \fBzmq_atomic_counter_inc\fR(3) \fBzmq_atomic_counter_value\fR(3) \fBzmq_atomic_counter_destroy\fR(3) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_atomic_counter_destroy.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_atomic_counter_destroy.3 deleted file mode 100644 index b37bd42407..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_atomic_counter_destroy.3 +++ /dev/null @@ -1,73 +0,0 @@ -'\" t -.\" Title: zmq_atomic_counter_destroy -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_ATOMIC_COUNTER_D" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_atomic_counter_destroy \- destroy an atomic counter -.SH "SYNOPSIS" -.sp -\fBvoid zmq_atomic_counter_destroy (void **counter_p);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_atomic_counter_destroy\fR function destroys an atomic counter and nullifies its reference\&. Pass the address of an atomic counter (void **) rather than the counter itself\&. You must destroy all counters that you create, to avoid memory leakage\&. This function uses platform specific atomic operations\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_atomic_counter_destroy()\fR function has no return value\&. -.SH "EXAMPLE" -.PP -\fBTest code for atomic counters\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -void *counter = zmq_atomic_counter_new (); -assert (zmq_atomic_counter_value (counter) == 0); -assert (zmq_atomic_counter_inc (counter) == 0); -assert (zmq_atomic_counter_inc (counter) == 1); -assert (zmq_atomic_counter_inc (counter) == 2); -assert (zmq_atomic_counter_value (counter) == 3); -assert (zmq_atomic_counter_dec (counter) == 1); -assert (zmq_atomic_counter_dec (counter) == 1); -assert (zmq_atomic_counter_dec (counter) == 0); -zmq_atomic_counter_set (counter, 2); -assert (zmq_atomic_counter_dec (counter) == 1); -assert (zmq_atomic_counter_dec (counter) == 0); -zmq_atomic_counter_destroy (&counter); -return 0; -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_atomic_counter_new\fR(3) \fBzmq_atomic_counter_set\fR(3) \fBzmq_atomic_counter_inc\fR(3) \fBzmq_atomic_counter_dec\fR(3) \fBzmq_atomic_counter_value\fR(3) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_atomic_counter_inc.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_atomic_counter_inc.3 deleted file mode 100644 index 8d7064f9cc..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_atomic_counter_inc.3 +++ /dev/null @@ -1,73 +0,0 @@ -'\" t -.\" Title: zmq_atomic_counter_inc -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_ATOMIC_COUNTER_I" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_atomic_counter_inc \- increment an atomic counter -.SH "SYNOPSIS" -.sp -\fBint zmq_atomic_counter_inc (void *counter);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_atomic_counter_inc\fR function increments an atomic counter in a threadsafe fashion\&. This function uses platform specific atomic operations\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_atomic_counter_inc()\fR function returns the old value of the counter, before incrementing\&. -.SH "EXAMPLE" -.PP -\fBTest code for atomic counters\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -void *counter = zmq_atomic_counter_new (); -assert (zmq_atomic_counter_value (counter) == 0); -assert (zmq_atomic_counter_inc (counter) == 0); -assert (zmq_atomic_counter_inc (counter) == 1); -assert (zmq_atomic_counter_inc (counter) == 2); -assert (zmq_atomic_counter_value (counter) == 3); -assert (zmq_atomic_counter_dec (counter) == 1); -assert (zmq_atomic_counter_dec (counter) == 1); -assert (zmq_atomic_counter_dec (counter) == 0); -zmq_atomic_counter_set (counter, 2); -assert (zmq_atomic_counter_dec (counter) == 1); -assert (zmq_atomic_counter_dec (counter) == 0); -zmq_atomic_counter_destroy (&counter); -return 0; -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_atomic_counter_new\fR(3) \fBzmq_atomic_counter_set\fR(3) \fBzmq_atomic_counter_dec\fR(3) \fBzmq_atomic_counter_value\fR(3) \fBzmq_atomic_counter_destroy\fR(3) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_atomic_counter_new.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_atomic_counter_new.3 deleted file mode 100644 index 124130917b..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_atomic_counter_new.3 +++ /dev/null @@ -1,73 +0,0 @@ -'\" t -.\" Title: zmq_atomic_counter_new -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_ATOMIC_COUNTER_N" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_atomic_counter_new \- create a new atomic counter -.SH "SYNOPSIS" -.sp -\fBvoid *zmq_atomic_counter_new (void);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_atomic_counter_new\fR function creates a new atomic counter\&. You can use this in multithreaded applications to do, for example, reference counting of shared objects\&. The atomic counter is at least 32 bits large\&. This function uses platform specific atomic operations\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_atomic_counter_new()\fR function returns the new atomic counter if successful\&. Otherwise it returns NULL\&. -.SH "EXAMPLE" -.PP -\fBTest code for atomic counters\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -void *counter = zmq_atomic_counter_new (); -assert (zmq_atomic_counter_value (counter) == 0); -assert (zmq_atomic_counter_inc (counter) == 0); -assert (zmq_atomic_counter_inc (counter) == 1); -assert (zmq_atomic_counter_inc (counter) == 2); -assert (zmq_atomic_counter_value (counter) == 3); -assert (zmq_atomic_counter_dec (counter) == 1); -assert (zmq_atomic_counter_dec (counter) == 1); -assert (zmq_atomic_counter_dec (counter) == 0); -zmq_atomic_counter_set (counter, 2); -assert (zmq_atomic_counter_dec (counter) == 1); -assert (zmq_atomic_counter_dec (counter) == 0); -zmq_atomic_counter_destroy (&counter); -return 0; -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_atomic_counter_set\fR(3) \fBzmq_atomic_counter_inc\fR(3) \fBzmq_atomic_counter_dec\fR(3) \fBzmq_atomic_counter_value\fR(3) \fBzmq_atomic_counter_destroy\fR(3) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_atomic_counter_set.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_atomic_counter_set.3 deleted file mode 100644 index 5cdac995d6..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_atomic_counter_set.3 +++ /dev/null @@ -1,73 +0,0 @@ -'\" t -.\" Title: zmq_atomic_counter_set -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_ATOMIC_COUNTER_S" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_atomic_counter_set \- set atomic counter to new value -.SH "SYNOPSIS" -.sp -\fBvoid zmq_atomic_counter_set (void *counter, int value);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_atomic_counter_set\fR function sets the counter to a new value, in a threadsafe fashion\&. The largest value that is guaranteed to work across all platforms is 2^31\-1\&. This function uses platform specific atomic operations\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_atomic_counter_set()\fR function has no return value\&. -.SH "EXAMPLE" -.PP -\fBTest code for atomic counters\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -void *counter = zmq_atomic_counter_new (); -assert (zmq_atomic_counter_value (counter) == 0); -assert (zmq_atomic_counter_inc (counter) == 0); -assert (zmq_atomic_counter_inc (counter) == 1); -assert (zmq_atomic_counter_inc (counter) == 2); -assert (zmq_atomic_counter_value (counter) == 3); -assert (zmq_atomic_counter_dec (counter) == 1); -assert (zmq_atomic_counter_dec (counter) == 1); -assert (zmq_atomic_counter_dec (counter) == 0); -zmq_atomic_counter_set (counter, 2); -assert (zmq_atomic_counter_dec (counter) == 1); -assert (zmq_atomic_counter_dec (counter) == 0); -zmq_atomic_counter_destroy (&counter); -return 0; -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_atomic_counter_new\fR(3) \fBzmq_atomic_counter_inc\fR(3) \fBzmq_atomic_counter_dec\fR(3) \fBzmq_atomic_counter_value\fR(3) \fBzmq_atomic_counter_destroy\fR(3) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_atomic_counter_value.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_atomic_counter_value.3 deleted file mode 100644 index f62f8b4714..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_atomic_counter_value.3 +++ /dev/null @@ -1,73 +0,0 @@ -'\" t -.\" Title: zmq_atomic_counter_value -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_ATOMIC_COUNTER_V" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_atomic_counter_value \- return value of atomic counter -.SH "SYNOPSIS" -.sp -\fBint zmq_atomic_counter_value (void *counter);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_atomic_counter_value\fR function returns the value of an atomic counter\&. This function uses platform specific atomic operations\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_atomic_counter_value()\fR function returns the new atomic counter if successful\&. Otherwise it returns NULL\&. -.SH "EXAMPLE" -.PP -\fBTest code for atomic counters\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -void *counter = zmq_atomic_counter_new (); -assert (zmq_atomic_counter_value (counter) == 0); -assert (zmq_atomic_counter_inc (counter) == 0); -assert (zmq_atomic_counter_inc (counter) == 1); -assert (zmq_atomic_counter_inc (counter) == 2); -assert (zmq_atomic_counter_value (counter) == 3); -assert (zmq_atomic_counter_dec (counter) == 1); -assert (zmq_atomic_counter_dec (counter) == 1); -assert (zmq_atomic_counter_dec (counter) == 0); -zmq_atomic_counter_set (counter, 2); -assert (zmq_atomic_counter_dec (counter) == 1); -assert (zmq_atomic_counter_dec (counter) == 0); -zmq_atomic_counter_destroy (&counter); -return 0; -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_atomic_counter_new\fR(3) \fBzmq_atomic_counter_set\fR(3) \fBzmq_atomic_counter_inc\fR(3) \fBzmq_atomic_counter_dec\fR(3) \fBzmq_atomic_counter_destroy\fR(3) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_bind.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_bind.3 deleted file mode 100644 index 4729611865..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_bind.3 +++ /dev/null @@ -1,200 +0,0 @@ -'\" t -.\" Title: zmq_bind -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_BIND" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_bind \- accept incoming connections on a socket -.SH "SYNOPSIS" -.sp -\fBint zmq_bind (void \fR\fB\fI*socket\fR\fR\fB, const char \fR\fB\fI*endpoint\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_bind()\fR function binds the \fIsocket\fR to a local \fIendpoint\fR and then accepts incoming connections on that endpoint\&. -.sp -The \fIendpoint\fR is a string consisting of a \fItransport\fR:// followed by an \fIaddress\fR\&. The \fItransport\fR specifies the underlying protocol to use\&. The \fIaddress\fR specifies the transport\-specific address to bind to\&. -.sp -0MQ provides the the following transports: -.PP -\fItcp\fR -.RS 4 -unicast transport using TCP, see -\fBzmq_tcp\fR(7) -.RE -.PP -\fIipc\fR -.RS 4 -local inter\-process communication transport, see -\fBzmq_ipc\fR(7) -.RE -.PP -\fIinproc\fR -.RS 4 -local in\-process (inter\-thread) communication transport, see -\fBzmq_inproc\fR(7) -.RE -.PP -\fIpgm\fR, \fIepgm\fR -.RS 4 -reliable multicast transport using PGM, see -\fBzmq_pgm\fR(7) -.RE -.PP -\fIvmci\fR -.RS 4 -virtual machine communications interface (VMCI), see -\fBzmq_vmci\fR(7) -.RE -.sp -Every 0MQ socket type except \fIZMQ_PAIR\fR supports one\-to\-many and many\-to\-one semantics\&. The precise semantics depend on the socket type and are defined in \fBzmq_socket\fR(3)\&. -.sp -The \fIipc\fR, \fItcp\fR and \fIvmci\fR transports accept wildcard addresses: see \fBzmq_ipc\fR(7), \fBzmq_tcp\fR(7) and \fBzmq_vmci\fR(7) for details\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -the address syntax may be different for \fIzmq_bind()\fR and \fIzmq_connect()\fR especially for the \fItcp\fR, \fIpgm\fR and \fIepgm\fR transports\&. -.sp .5v -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -following a \fIzmq_bind()\fR, the socket enters a \fImute\fR state unless or until at least one incoming or outgoing connection is made, at which point the socket enters a \fIready\fR state\&. In the mute state, the socket blocks or drops messages according to the socket type, as defined in \fBzmq_socket\fR(3)\&. By contrast, following a libzmq:zmq_connect[3], the socket enters the \fIready\fR state\&. -.sp .5v -.RE -.SH "RETURN VALUE" -.sp -The \fIzmq_bind()\fR function returns zero if successful\&. Otherwise it returns \-1 and sets \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEINVAL\fR -.RS 4 -The endpoint supplied is invalid\&. -.RE -.PP -\fBEPROTONOSUPPORT\fR -.RS 4 -The requested -\fItransport\fR -protocol is not supported\&. -.RE -.PP -\fBENOCOMPATPROTO\fR -.RS 4 -The requested -\fItransport\fR -protocol is not compatible with the socket type\&. -.RE -.PP -\fBEADDRINUSE\fR -.RS 4 -The requested -\fIaddress\fR -is already in use\&. -.RE -.PP -\fBEADDRNOTAVAIL\fR -.RS 4 -The requested -\fIaddress\fR -was not local\&. -.RE -.PP -\fBENODEV\fR -.RS 4 -The requested -\fIaddress\fR -specifies a nonexistent interface\&. -.RE -.PP -\fBETERM\fR -.RS 4 -The 0MQ -\fIcontext\fR -associated with the specified -\fIsocket\fR -was terminated\&. -.RE -.PP -\fBENOTSOCK\fR -.RS 4 -The provided -\fIsocket\fR -was invalid\&. -.RE -.PP -\fBEMTHREAD\fR -.RS 4 -No I/O thread is available to accomplish the task\&. -.RE -.SH "EXAMPLE" -.PP -\fBBinding a publisher socket to an in-process and a TCP transport\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -/* Create a ZMQ_PUB socket */ -void *socket = zmq_socket (context, ZMQ_PUB); -assert (socket); -/* Bind it to a in\-process transport with the address \*(Aqmy_publisher\*(Aq */ -int rc = zmq_bind (socket, "inproc://my_publisher"); -assert (rc == 0); -/* Bind it to a TCP transport on port 5555 of the \*(Aqeth0\*(Aq interface */ -rc = zmq_bind (socket, "tcp://eth0:5555"); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_connect\fR(3) \fBzmq_socket\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_close.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_close.3 deleted file mode 100644 index f3b45dc49e..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_close.3 +++ /dev/null @@ -1,70 +0,0 @@ -'\" t -.\" Title: zmq_close -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_CLOSE" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_close \- close 0MQ socket -.SH "SYNOPSIS" -.sp -\fBint zmq_close (void \fR\fB\fI*socket\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_close()\fR function shall destroy the socket referenced by the \fIsocket\fR argument\&. Any outstanding messages physically received from the network but not yet received by the application with \fIzmq_recv()\fR shall be discarded\&. The behaviour for discarding messages sent by the application with \fIzmq_send()\fR but not yet physically transferred to the network depends on the value of the \fIZMQ_LINGER\fR socket option for the specified \fIsocket\fR\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -The default setting of \fIZMQ_LINGER\fR does not discard unsent messages; this behaviour may cause the application to block when calling \fIzmq_ctx_term()\fR\&. For details refer to \fBzmq_setsockopt\fR(3) and \fBzmq_ctx_term\fR(3)\&. -.sp .5v -.RE -.SH "RETURN VALUE" -.sp -The \fIzmq_close()\fR function shall return zero if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBENOTSOCK\fR -.RS 4 -The provided -\fIsocket\fR -was invalid\&. -.RE -.SH "SEE ALSO" -.sp -\fBzmq_socket\fR(3) \fBzmq_ctx_term\fR(3) \fBzmq_setsockopt\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_connect.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_connect.3 deleted file mode 100644 index ba263b85f8..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_connect.3 +++ /dev/null @@ -1,177 +0,0 @@ -'\" t -.\" Title: zmq_connect -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_CONNECT" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_connect \- create outgoing connection from socket -.SH "SYNOPSIS" -.sp -\fBint zmq_connect (void \fR\fB\fI*socket\fR\fR\fB, const char \fR\fB\fI*endpoint\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_connect()\fR function connects the \fIsocket\fR to an \fIendpoint\fR and then accepts incoming connections on that endpoint\&. -.sp -The \fIendpoint\fR is a string consisting of a \fItransport\fR:// followed by an \fIaddress\fR\&. The \fItransport\fR specifies the underlying protocol to use\&. The \fIaddress\fR specifies the transport\-specific address to connect to\&. -.sp -0MQ provides the the following transports: -.PP -\fItcp\fR -.RS 4 -unicast transport using TCP, see -\fBzmq_tcp\fR(7) -.RE -.PP -\fIipc\fR -.RS 4 -local inter\-process communication transport, see -\fBzmq_ipc\fR(7) -.RE -.PP -\fIinproc\fR -.RS 4 -local in\-process (inter\-thread) communication transport, see -\fBzmq_inproc\fR(7) -.RE -.PP -\fIpgm\fR, \fIepgm\fR -.RS 4 -reliable multicast transport using PGM, see -\fBzmq_pgm\fR(7) -.RE -.PP -\fIvmci\fR -.RS 4 -virtual machine communications interface (VMCI), see -\fBzmq_vmci\fR(7) -.RE -.sp -Every 0MQ socket type except \fIZMQ_PAIR\fR supports one\-to\-many and many\-to\-one semantics\&. The precise semantics depend on the socket type and are defined in \fBzmq_socket\fR(3)\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -for most transports and socket types the connection is not performed immediately but as needed by 0MQ\&. Thus a successful call to \fIzmq_connect()\fR does not mean that the connection was or could actually be established\&. Because of this, for most transports and socket types the order in which a \fIserver\fR socket is bound and a \fIclient\fR socket is connected to it does not matter\&. The first exception is when using the inproc:// transport: you must call \fIzmq_bind()\fR before calling \fIzmq_connect()\fR\&. The second exception are \fIZMQ_PAIR\fR sockets, which do not automatically reconnect to endpoints\&. -.sp .5v -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -following a \fIzmq_connect()\fR, for socket types except for ZMQ_ROUTER, the socket enters its normal \fIready\fR state\&. By contrast, following a \fIzmq_bind()\fR alone, the socket enters a \fImute\fR state in which the socket blocks or drops messages according to the socket type, as defined in \fBzmq_socket\fR(3)\&. A ZMQ_ROUTER socket enters its normal \fIready\fR state for a specific peer only when handshaking is complete for that peer, which may take an arbitrary time\&. -.sp .5v -.RE -.SH "RETURN VALUE" -.sp -The \fIzmq_connect()\fR function returns zero if successful\&. Otherwise it returns \-1 and sets \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEINVAL\fR -.RS 4 -The endpoint supplied is invalid\&. -.RE -.PP -\fBEPROTONOSUPPORT\fR -.RS 4 -The requested -\fItransport\fR -protocol is not supported\&. -.RE -.PP -\fBENOCOMPATPROTO\fR -.RS 4 -The requested -\fItransport\fR -protocol is not compatible with the socket type\&. -.RE -.PP -\fBETERM\fR -.RS 4 -The 0MQ -\fIcontext\fR -associated with the specified -\fIsocket\fR -was terminated\&. -.RE -.PP -\fBENOTSOCK\fR -.RS 4 -The provided -\fIsocket\fR -was invalid\&. -.RE -.PP -\fBEMTHREAD\fR -.RS 4 -No I/O thread is available to accomplish the task\&. -.RE -.SH "EXAMPLE" -.PP -\fBConnecting a subscriber socket to an in-process and a TCP transport\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -/* Create a ZMQ_SUB socket */ -void *socket = zmq_socket (context, ZMQ_SUB); -assert (socket); -/* Connect it to an in\-process transport with the address \*(Aqmy_publisher\*(Aq */ -int rc = zmq_connect (socket, "inproc://my_publisher"); -assert (rc == 0); -/* Connect it to the host server001, port 5555 using a TCP transport */ -rc = zmq_connect (socket, "tcp://server001:5555"); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_bind\fR(3) \fBzmq_socket\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_ctx_get.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_ctx_get.3 deleted file mode 100644 index fef5be6649..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_ctx_get.3 +++ /dev/null @@ -1,106 +0,0 @@ -'\" t -.\" Title: zmq_ctx_get -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_CTX_GET" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_ctx_get \- get context options -.SH "SYNOPSIS" -.sp -\fBint zmq_ctx_get (void \fR\fB\fI*context\fR\fR\fB, int \fR\fB\fIoption_name\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_ctx_get()\fR function shall return the option specified by the \fIoption_name\fR argument\&. -.sp -The \fIzmq_ctx_get()\fR function accepts the following option names: -.SS "ZMQ_IO_THREADS: Get number of I/O threads" -.sp -The \fIZMQ_IO_THREADS\fR argument returns the size of the 0MQ thread pool for this context\&. -.SS "ZMQ_MAX_SOCKETS: Get maximum number of sockets" -.sp -The \fIZMQ_MAX_SOCKETS\fR argument returns the maximum number of sockets allowed for this context\&. -.SS "ZMQ_MAX_MSGSZ: Get maximum message size" -.sp -The \fIZMQ_MAX_MSGSZ\fR argument returns the maximum size of a message allowed for this context\&. Default value is INT_MAX\&. -.SS "ZMQ_SOCKET_LIMIT: Get largest configurable number of sockets" -.sp -The \fIZMQ_SOCKET_LIMIT\fR argument returns the largest number of sockets that \fBzmq_ctx_set\fR(3) will accept\&. -.SS "ZMQ_IPV6: Set IPv6 option" -.sp -The \fIZMQ_IPV6\fR argument returns the IPv6 option for the context\&. -.SS "ZMQ_BLOCKY: Get blocky setting" -.sp -The \fIZMQ_BLOCKY\fR argument returns 1 if the context will block on terminate, zero if the "block forever on context termination" gambit was disabled by setting ZMQ_BLOCKY to false on all new contexts\&. -.SS "ZMQ_MSG_T_SIZE: Get the zmq_msg_t size at runtime" -.sp -The \fIZMQ_MSG_T_SIZE\fR argument returns the size of the zmq_msg_t structure at runtime, as defined in the include/zmq\&.h public header\&. This is useful for example for FFI bindings that can\(cqt simply do a sizeof()\&. NOTE: in DRAFT state, not yet available in stable releases\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_ctx_get()\fR function returns a value of 0 or greater if successful\&. Otherwise it returns \-1 and sets \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEINVAL\fR -.RS 4 -The requested option -\fIoption_name\fR -is unknown\&. -.RE -.SH "EXAMPLE" -.PP -\fBSetting a limit on the number of sockets\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -void *context = zmq_ctx_new (); -zmq_ctx_set (context, ZMQ_MAX_SOCKETS, 256); -int max_sockets = zmq_ctx_get (context, ZMQ_MAX_SOCKETS); -assert (max_sockets == 256); -.fi -.if n \{\ -.RE -.\} -.PP -\fBSwitching off the context deadlock gambit\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -zmq_ctx_set (ctx, ZMQ_BLOCKY, false); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_ctx_set\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_ctx_new.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_ctx_new.3 deleted file mode 100644 index 23d1af87f7..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_ctx_new.3 +++ /dev/null @@ -1,55 +0,0 @@ -'\" t -.\" Title: zmq_ctx_new -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_CTX_NEW" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_ctx_new \- create new 0MQ context -.SH "SYNOPSIS" -.sp -\fBvoid *zmq_ctx_new ();\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_ctx_new()\fR function creates a new 0MQ \fIcontext\fR\&. -.sp -This function replaces the deprecated function \fBzmq_init\fR(3)\&. -.PP -\fBThread safety\fR. A 0MQ -\fIcontext\fR -is thread safe and may be shared among as many application threads as necessary, without any additional locking required on the part of the caller\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_ctx_new()\fR function shall return an opaque handle to the newly created \fIcontext\fR if successful\&. Otherwise it shall return NULL and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.sp -No error values are defined for this function\&. -.SH "SEE ALSO" -.sp -\fBzmq\fR(7) \fBzmq_ctx_set\fR(3) \fBzmq_ctx_get\fR(3) \fBzmq_ctx_term\fR(3) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_ctx_set.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_ctx_set.3 deleted file mode 100644 index b7d3e39cbc..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_ctx_set.3 +++ /dev/null @@ -1,186 +0,0 @@ -'\" t -.\" Title: zmq_ctx_set -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_CTX_SET" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_ctx_set \- set context options -.SH "SYNOPSIS" -.sp -\fBint zmq_ctx_set (void \fR\fB\fI*context\fR\fR\fB, int \fR\fB\fIoption_name\fR\fR\fB, int \fR\fB\fIoption_value\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_ctx_set()\fR function shall set the option specified by the \fIoption_name\fR argument to the value of the \fIoption_value\fR argument\&. -.sp -The \fIzmq_ctx_set()\fR function accepts the following options: -.SS "ZMQ_BLOCKY: Fix blocky behavior" -.sp -By default the context will block, forever, on a zmq_ctx_term call\&. The assumption behind this behavior is that abrupt termination will cause message loss\&. Most real applications use some form of handshaking to ensure applications receive termination messages, and then terminate the context with \fIZMQ_LINGER\fR set to zero on all sockets\&. This setting is an easier way to get the same result\&. When \fIZMQ_BLOCKY\fR is set to false, all new sockets are given a linger timeout of zero\&. You must still close all sockets before calling zmq_ctx_term\&. -.TS -tab(:); -lt lt. -T{ -.sp -Default value -T}:T{ -.sp -true (old behavior) -T} -.TE -.sp 1 -.SS "ZMQ_IO_THREADS: Set number of I/O threads" -.sp -The \fIZMQ_IO_THREADS\fR argument specifies the size of the 0MQ thread pool to handle I/O operations\&. If your application is using only the \fIinproc\fR transport for messaging you may set this to zero, otherwise set it to at least one\&. This option only applies before creating any sockets on the context\&. -.TS -tab(:); -lt lt. -T{ -.sp -Default value -T}:T{ -.sp -1 -T} -.TE -.sp 1 -.SS "ZMQ_THREAD_SCHED_POLICY: Set scheduling policy for I/O threads" -.sp -The \fIZMQ_THREAD_SCHED_POLICY\fR argument sets the scheduling policy for internal context\(cqs thread pool\&. This option is not available on windows\&. Supported values for this option can be found in sched\&.h file, or at \m[blue]\fBhttp://man7\&.org/linux/man\-pages/man2/sched_setscheduler\&.2\&.html\fR\m[]\&. This option only applies before creating any sockets on the context\&. -.TS -tab(:); -lt lt. -T{ -.sp -Default value -T}:T{ -.sp -\-1 -T} -.TE -.sp 1 -.SS "ZMQ_THREAD_PRIORITY: Set scheduling priority for I/O threads" -.sp -The \fIZMQ_THREAD_PRIORITY\fR argument sets scheduling priority for internal context\(cqs thread pool\&. This option is not available on windows\&. Supported values for this option depend on chosen scheduling policy\&. Details can be found in sched\&.h file, or at \m[blue]\fBhttp://man7\&.org/linux/man\-pages/man2/sched_setscheduler\&.2\&.html\fR\m[]\&. This option only applies before creating any sockets on the context\&. -.TS -tab(:); -lt lt. -T{ -.sp -Default value -T}:T{ -.sp -\-1 -T} -.TE -.sp 1 -.SS "ZMQ_MAX_MSGSZ: Set maximum message size" -.sp -The \fIZMQ_MAX_MSGSZ\fR argument sets the maximum allowed size of a message sent in the context\&. You can query the maximal allowed value with \fBzmq_ctx_get\fR(3) using the \fIZMQ_MAX_MSGSZ\fR option\&. -.TS -tab(:); -lt lt -lt lt. -T{ -.sp -Default value -T}:T{ -.sp -INT_MAX -T} -T{ -.sp -Maximum value -T}:T{ -.sp -INT_MAX -T} -.TE -.sp 1 -.SS "ZMQ_MAX_SOCKETS: Set maximum number of sockets" -.sp -The \fIZMQ_MAX_SOCKETS\fR argument sets the maximum number of sockets allowed on the context\&. You can query the maximal allowed value with \fBzmq_ctx_get\fR(3) using the \fIZMQ_SOCKET_LIMIT\fR option\&. -.TS -tab(:); -lt lt. -T{ -.sp -Default value -T}:T{ -.sp -1024 -T} -.TE -.sp 1 -.SS "ZMQ_IPV6: Set IPv6 option" -.sp -The \fIZMQ_IPV6\fR argument sets the IPv6 value for all sockets created in the context from this point onwards\&. A value of 1 means IPv6 is enabled, while 0 means the socket will use only IPv4\&. When IPv6 is enabled, a socket will connect to, or accept connections from, both IPv4 and IPv6 hosts\&. -.TS -tab(:); -lt lt. -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -.TE -.sp 1 -.SH "RETURN VALUE" -.sp -The \fIzmq_ctx_set()\fR function returns zero if successful\&. Otherwise it returns \-1 and sets \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEINVAL\fR -.RS 4 -The requested option -\fIoption_name\fR -is unknown\&. -.RE -.SH "EXAMPLE" -.PP -\fBSetting a limit on the number of sockets\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -void *context = zmq_ctx_new (); -zmq_ctx_set (context, ZMQ_MAX_SOCKETS, 256); -int max_sockets = zmq_ctx_get (context, ZMQ_MAX_SOCKETS); -assert (max_sockets == 256); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_ctx_get\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_ctx_shutdown.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_ctx_shutdown.3 deleted file mode 100644 index 1e1d21dea3..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_ctx_shutdown.3 +++ /dev/null @@ -1,58 +0,0 @@ -'\" t -.\" Title: zmq_ctx_shutdown -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_CTX_SHUTDOWN" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_ctx_shutdown \- shutdown a 0MQ context -.SH "SYNOPSIS" -.sp -\fBint zmq_ctx_shutdown (void \fR\fB\fI*context\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_ctx_shutdown()\fR function shall shutdown the 0MQ context \fIcontext\fR\&. -.sp -Context shutdown will cause any blocking operations currently in progress on sockets open within \fIcontext\fR to return immediately with an error code of ETERM\&. With the exception of \fIzmq_close()\fR, any further operations on sockets open within \fIcontext\fR shall fail with an error code of ETERM\&. -.sp -This function is optional, client code is still required to call the \fBzmq_ctx_term\fR(3) function to free all resources allocated by zeromq\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_ctx_shutdown()\fR function shall return zero if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEFAULT\fR -.RS 4 -The provided -\fIcontext\fR -was invalid\&. -.RE -.SH "SEE ALSO" -.sp -\fBzmq\fR(7) \fBzmq_init\fR(3) \fBzmq_ctx_term\fR(3) \fBzmq_close\fR(3) \fBzmq_setsockopt\fR(3) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_ctx_term.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_ctx_term.3 deleted file mode 100644 index c7a5700f4e..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_ctx_term.3 +++ /dev/null @@ -1,126 +0,0 @@ -'\" t -.\" Title: zmq_ctx_term -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_CTX_TERM" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_ctx_term \- terminate a 0MQ context -.SH "SYNOPSIS" -.sp -\fBint zmq_ctx_term (void \fR\fB\fI*context\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_ctx_term()\fR function shall destroy the 0MQ context \fIcontext\fR\&. -.sp -Context termination is performed in the following steps: -.sp -.RS 4 -.ie n \{\ -\h'-04' 1.\h'+01'\c -.\} -.el \{\ -.sp -1 -.IP " 1." 4.2 -.\} -Any blocking operations currently in progress on sockets open within -\fIcontext\fR -shall return immediately with an error code of ETERM\&. With the exception of -\fIzmq_close()\fR, any further operations on sockets open within -\fIcontext\fR -shall fail with an error code of ETERM\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04' 2.\h'+01'\c -.\} -.el \{\ -.sp -1 -.IP " 2." 4.2 -.\} -After interrupting all blocking calls, -\fIzmq_ctx_term()\fR -shall -\fIblock\fR -until the following conditions are satisfied: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -All sockets open within -\fIcontext\fR -have been closed with -\fIzmq_close()\fR\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -For each socket within -\fIcontext\fR, all messages sent by the application with -\fIzmq_send()\fR -have either been physically transferred to a network peer, or the socket\(cqs linger period set with the -\fIZMQ_LINGER\fR -socket option has expired\&. -.RE -.RE -.sp -For further details regarding socket linger behaviour refer to the \fIZMQ_LINGER\fR option in \fBzmq_setsockopt\fR(3)\&. -.sp -This function replaces the deprecated functions \fBzmq_term\fR(3) and \fBzmq_ctx_destroy\fR(3)\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_ctx_term()\fR function shall return zero if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEFAULT\fR -.RS 4 -The provided -\fIcontext\fR -was invalid\&. -.RE -.PP -\fBEINTR\fR -.RS 4 -Termination was interrupted by a signal\&. It can be restarted if needed\&. -.RE -.SH "SEE ALSO" -.sp -\fBzmq\fR(7) \fBzmq_init\fR(3) \fBzmq_close\fR(3) \fBzmq_setsockopt\fR(3) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_curve_keypair.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_curve_keypair.3 deleted file mode 100644 index 5a58963cff..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_curve_keypair.3 +++ /dev/null @@ -1,69 +0,0 @@ -'\" t -.\" Title: zmq_curve_keypair -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_CURVE_KEYPAIR" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_curve_keypair \- generate a new CURVE keypair -.SH "SYNOPSIS" -.sp -\fBint zmq_curve_keypair (char *z85_public_key, char *z85_secret_key);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_curve_keypair()\fR function shall return a newly generated random keypair consisting of a public key and a secret key\&. The caller provides two buffers, each at least 41 octets large, in which this method will store the keys\&. The keys are encoded using \fBzmq_z85_encode\fR(3)\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_curve_keypair()\fR function shall return 0 if successful, else it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBENOTSUP\fR -.RS 4 -The libzmq library was not built with cryptographic support (libsodium)\&. -.RE -.SH "EXAMPLE" -.PP -\fBGenerating a new CURVE keypair\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -char public_key [41]; -char secret_key [41]; -int rc = zmq_curve_keypair (public_key, secret_key); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_z85_decode\fR(3) \fBzmq_z85_encode\fR(3) \fBzmq_curve\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_curve_public.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_curve_public.3 deleted file mode 100644 index f7dceeb5d9..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_curve_public.3 +++ /dev/null @@ -1,73 +0,0 @@ -'\" t -.\" Title: zmq_curve_public -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_CURVE_PUBLIC" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_curve_public \- derive the public key from a private key -.SH "SYNOPSIS" -.sp -\fBint zmq_curve_public (char *z85_public_key, char *z85_secret_key);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_curve_public()\fR function shall derive the public key from a private key\&. The caller provides two buffers, each at least 41 octets large\&. In z85_secret_key the caller shall provide the private key, and the function will store the public key in z85_public_key\&. The keys are encoded using \fBzmq_z85_encode\fR(3)\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_curve_public()\fR function shall return 0 if successful, else it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBENOTSUP\fR -.RS 4 -The libzmq library was not built with cryptographic support (libsodium)\&. -.RE -.SH "EXAMPLE" -.PP -\fBDeriving the public key from a CURVE private key\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -char public_key [41]; -char secret_key [41]; -int rc = zmq_curve_keypair (public_key, secret_key); -assert (rc == 0); -char derived_public[41]; -rc = zmq_curve_public (derived_public, secret_key); -assert (rc == 0); -assert (!strcmp (derived_public, public_key)); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_z85_decode\fR(3) \fBzmq_z85_encode\fR(3) \fBzmq_curve_keypair\fR(3) \fBzmq_curve\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_disconnect.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_disconnect.3 deleted file mode 100644 index ff5075fd31..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_disconnect.3 +++ /dev/null @@ -1,113 +0,0 @@ -'\" t -.\" Title: zmq_disconnect -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_DISCONNECT" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_disconnect \- Disconnect a socket -.SH "SYNOPSIS" -.sp -\fBint zmq_disconnect (void \fR\fB\fI*socket\fR\fR\fB, const char \fR\fB\fI*endpoint\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_disconnect()\fR function shall disconnect a socket specified by the \fIsocket\fR argument from the endpoint specified by the \fIendpoint\fR argument\&. Any outstanding messages physically received from the network but not yet received by the application with \fIzmq_recv()\fR shall be discarded\&. The behaviour for discarding messages sent by the application with \fIzmq_send()\fR but not yet physically transferred to the network depends on the value of the \fIZMQ_LINGER\fR socket option for the specified \fIsocket\fR\&. -.sp -The \fIendpoint\fR argument is as described in \fBzmq_connect\fR(3) -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -The default setting of \fIZMQ_LINGER\fR does not discard unsent messages; this behaviour may cause the application to block when calling \fIzmq_ctx_term()\fR\&. For details refer to \fBzmq_setsockopt\fR(3) and \fBzmq_ctx_term\fR(3)\&. -.sp .5v -.RE -.SH "RETURN VALUE" -.sp -The \fIzmq_disconnect()\fR function shall return zero if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEINVAL\fR -.RS 4 -The endpoint supplied is invalid\&. -.RE -.PP -\fBETERM\fR -.RS 4 -The 0MQ -\fIcontext\fR -associated with the specified -\fIsocket\fR -was terminated\&. -.RE -.PP -\fBENOTSOCK\fR -.RS 4 -The provided -\fIsocket\fR -was invalid\&. -.RE -.PP -\fBENOENT\fR -.RS 4 -The provided endpoint is not connected\&. -.RE -.SH "EXAMPLE" -.PP -\fBConnecting a subscriber socket to an in-process and a TCP transport\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -/* Create a ZMQ_SUB socket */ -void *socket = zmq_socket (context, ZMQ_SUB); -assert (socket); -/* Connect it to the host server001, port 5555 using a TCP transport */ -rc = zmq_connect (socket, "tcp://server001:5555"); -assert (rc == 0); -/* Disconnect from the previously connected endpoint */ -rc = zmq_disconnect (socket, "tcp://server001:5555"); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_connect\fR(3) \fBzmq_socket\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_errno.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_errno.3 deleted file mode 100644 index b7cb977fd1..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_errno.3 +++ /dev/null @@ -1,67 +0,0 @@ -'\" t -.\" Title: zmq_errno -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_ERRNO" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_errno \- retrieve value of errno for the calling thread -.SH "SYNOPSIS" -.sp -\fBint zmq_errno (void);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_errno()\fR function shall retrieve the value of the \fIerrno\fR variable for the calling thread\&. -.sp -The \fIzmq_errno()\fR function is provided to assist users on non\-POSIX systems who are experiencing issues with retrieving the correct value of \fIerrno\fR directly\&. Specifically, users on Win32 systems whose application is using a different C run\-time library from the C run\-time library in use by 0MQ will need to use \fIzmq_errno()\fR for correct operation\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBImportant\fR -.ps -1 -.br -.sp -Users not experiencing issues with retrieving the correct value of \fIerrno\fR should not use this function and should instead access the \fIerrno\fR variable directly\&. -.sp .5v -.RE -.SH "RETURN VALUE" -.sp -The \fIzmq_errno()\fR function shall return the value of the \fIerrno\fR variable for the calling thread\&. -.SH "ERRORS" -.sp -No errors are defined\&. -.SH "SEE ALSO" -.sp -\fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_getsockopt.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_getsockopt.3 deleted file mode 100644 index 7a51c1e678..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_getsockopt.3 +++ /dev/null @@ -1,2298 +0,0 @@ -'\" t -.\" Title: zmq_getsockopt -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_GETSOCKOPT" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_getsockopt \- get 0MQ socket options -.SH "SYNOPSIS" -.sp -\fBint zmq_getsockopt (void \fR\fB\fI*socket\fR\fR\fB, int \fR\fB\fIoption_name\fR\fR\fB, void \fR\fB\fI*option_value\fR\fR\fB, size_t \fR\fB\fI*option_len\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_getsockopt()\fR function shall retrieve the value for the option specified by the \fIoption_name\fR argument for the 0MQ socket pointed to by the \fIsocket\fR argument, and store it in the buffer pointed to by the \fIoption_value\fR argument\&. The \fIoption_len\fR argument is the size in bytes of the buffer pointed to by \fIoption_value\fR; upon successful completion \fIzmq_getsockopt()\fR shall modify the \fIoption_len\fR argument to indicate the actual size of the option value stored in the buffer\&. -.sp -The following options can be retrieved with the \fIzmq_getsockopt()\fR function: -.SS "ZMQ_AFFINITY: Retrieve I/O thread affinity" -.sp -The \fIZMQ_AFFINITY\fR option shall retrieve the I/O thread affinity for newly created connections on the specified \fIsocket\fR\&. -.sp -Affinity determines which threads from the 0MQ I/O thread pool associated with the socket\(cqs \fIcontext\fR shall handle newly created connections\&. A value of zero specifies no affinity, meaning that work shall be distributed fairly among all 0MQ I/O threads in the thread pool\&. For non\-zero values, the lowest bit corresponds to thread 1, second lowest bit to thread 2 and so on\&. For example, a value of 3 specifies that subsequent connections on \fIsocket\fR shall be handled exclusively by I/O threads 1 and 2\&. -.sp -See also \fBzmq_init\fR(3) for details on allocating the number of I/O threads for a specific \fIcontext\fR\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -uint64_t -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A (bitmap) -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -N/A -T} -.TE -.sp 1 -.SS "ZMQ_BACKLOG: Retrieve maximum length of the queue of outstanding connections" -.sp -The \fIZMQ_BACKLOG\fR option shall retrieve the maximum length of the queue of outstanding peer connections for the specified \fIsocket\fR; this only applies to connection\-oriented transports\&. For details refer to your operating system documentation for the \fIlisten\fR function\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -connections -T} -T{ -.sp -Default value -T}:T{ -.sp -100 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, only for connection\-oriented transports -T} -.TE -.sp 1 -.SS "ZMQ_CONNECT_TIMEOUT: Retrieve connect() timeout" -.sp -Retrieves how long to wait before timing\-out a connect() system call\&. The connect() system call normally takes a long time before it returns a time out error\&. Setting this option allows the library to time out the call at an earlier interval\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -0 (disabled) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_CURVE_PUBLICKEY: Retrieve current CURVE public key" -.sp -Retrieves the current long term public key for the socket\&. You can provide either a 32 byte buffer, to retrieve the binary key value, or a 41 byte buffer, to retrieve the key in a printable Z85 format\&. NOTE: to fetch a printable key, the buffer must be 41 bytes large to hold the 40\-char key value and one null byte\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -binary data or Z85 text string -T} -T{ -.sp -Option value size -T}:T{ -.sp -32 or 41 -T} -T{ -.sp -Default value -T}:T{ -.sp -null -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transport -T} -.TE -.sp 1 -.SS "ZMQ_CURVE_SECRETKEY: Retrieve current CURVE secret key" -.sp -Retrieves the current long term secret key for the socket\&. You can provide either a 32 byte buffer, to retrieve the binary key value, or a 41 byte buffer, to retrieve the key in a printable Z85 format\&. NOTE: to fetch a printable key, the buffer must be 41 bytes large to hold the 40\-char key value and one null byte\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -binary data or Z85 text string -T} -T{ -.sp -Option value size -T}:T{ -.sp -32 or 41 -T} -T{ -.sp -Default value -T}:T{ -.sp -null -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transport -T} -.TE -.sp 1 -.SS "ZMQ_CURVE_SERVERKEY: Retrieve current CURVE server key" -.sp -Retrieves the current server key for the client socket\&. You can provide either a 32 byte buffer, to retrieve the binary key value, or a 41\-byte buffer, to retrieve the key in a printable Z85 format\&. NOTE: to fetch a printable key, the buffer must be 41 bytes large to hold the 40\-char key value and one null byte\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -binary data or Z85 text string -T} -T{ -.sp -Option value size -T}:T{ -.sp -32 or 41 -T} -T{ -.sp -Default value -T}:T{ -.sp -null -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transport -T} -.TE -.sp 1 -.SS "ZMQ_EVENTS: Retrieve socket event state" -.sp -The \fIZMQ_EVENTS\fR option shall retrieve the event state for the specified \fIsocket\fR\&. The returned value is a bit mask constructed by OR\(cqing a combination of the following event flags: -.PP -\fBZMQ_POLLIN\fR -.RS 4 -Indicates that at least one message may be received from the specified socket without blocking\&. -.RE -.PP -\fBZMQ_POLLOUT\fR -.RS 4 -Indicates that at least one message may be sent to the specified socket without blocking\&. -.RE -.sp -The combination of a file descriptor returned by the \fIZMQ_FD\fR option being ready for reading but no actual events returned by a subsequent retrieval of the \fIZMQ_EVENTS\fR option is valid; applications should simply ignore this case and restart their polling operation/event loop\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A (flags) -T} -T{ -.sp -Default value -T}:T{ -.sp -N/A -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all -T} -.TE -.sp 1 -.SS "ZMQ_FD: Retrieve file descriptor associated with the socket" -.sp -The \fIZMQ_FD\fR option shall retrieve the file descriptor associated with the specified \fIsocket\fR\&. The returned file descriptor can be used to integrate the socket into an existing event loop; the 0MQ library shall signal any pending events on the socket in an \fIedge\-triggered\fR fashion by making the file descriptor become ready for reading\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -The ability to read from the returned file descriptor does not necessarily indicate that messages are available to be read from, or can be written to, the underlying socket; applications must retrieve the actual event state with a subsequent retrieval of the \fIZMQ_EVENTS\fR option\&. -.sp .5v -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -The returned file descriptor is also used internally by the \fIzmq_send\fR and \fIzmq_recv\fR functions\&. As the descriptor is edge triggered, applications must update the state of \fIZMQ_EVENTS\fR after each invocation of \fIzmq_send\fR or \fIzmq_recv\fR\&.To be more explicit: after calling \fIzmq_send\fR the socket may become readable (and vice versa) without triggering a read event on the file descriptor\&. -.sp .5v -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBCaution\fR -.ps -1 -.br -.sp -The returned file descriptor is intended for use with a \fIpoll\fR or similar system call only\&. Applications must never attempt to read or write data to it directly, neither should they try to close it\&. -.sp .5v -.RE -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int on POSIX systems, SOCKET on Windows -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -N/A -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all -T} -.TE -.sp 1 -.SS "ZMQ_GSSAPI_PLAINTEXT: Retrieve GSSAPI plaintext or encrypted status" -.sp -Returns the \fIZMQ_GSSAPI_PLAINTEXT\fR option, if any, previously set on the socket\&. A value of \fI1\fR means that communications will be plaintext\&. A value of \fI0\fR means communications will be encrypted\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0, 1 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 (false) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP or IPC transports -T} -.TE -.sp 1 -.SS "ZMQ_GSSAPI_PRINCIPAL: Retrieve the name of the GSSAPI principal" -.sp -The \fIZMQ_GSSAPI_PRINCIPAL\fR option shall retrieve the principal name set for the GSSAPI security mechanism\&. The returned value shall be a NULL\-terminated string and MAY be empty\&. The returned size SHALL include the terminating null byte\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -NULL\-terminated character string -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -null string -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP or IPC transports -T} -.TE -.sp 1 -.SS "ZMQ_GSSAPI_SERVER: Retrieve current GSSAPI server role" -.sp -Returns the \fIZMQ_GSSAPI_SERVER\fR option, if any, previously set on the socket\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0, 1 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 (false) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP or IPC transports -T} -.TE -.sp 1 -.SS "ZMQ_GSSAPI_SERVICE_PRINCIPAL: Retrieve the name of the GSSAPI service principal" -.sp -The \fIZMQ_GSSAPI_SERVICE_PRINCIPAL\fR option shall retrieve the principal name of the GSSAPI server to which a GSSAPI client socket intends to connect\&. The returned value shall be a NULL\-terminated string and MAY be empty\&. The returned size SHALL include the terminating null byte\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -NULL\-terminated character string -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -null string -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP or IPC transports -T} -.TE -.sp 1 -.SS "ZMQ_HANDSHAKE_IVL: Retrieve maximum handshake interval" -.sp -The \fIZMQ_HANDSHAKE_IVL\fR option shall retrieve the maximum handshake interval for the specified \fIsocket\fR\&. Handshaking is the exchange of socket configuration information (socket type, identity, security) that occurs when a connection is first opened, only for connection\-oriented transports\&. If handshaking does not complete within the configured time, the connection shall be closed\&. The value 0 means no handshake time limit\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -30000 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all but ZMQ_STREAM, only for connection\-oriented transports -T} -.TE -.sp 1 -.SS "ZMQ_IDENTITY: Retrieve socket identity" -.sp -The \fIZMQ_IDENTITY\fR option shall retrieve the identity of the specified \fIsocket\fR\&. Socket identity is used only by request/reply pattern\&. Namely, it can be used in tandem with ROUTER socket to route messages to the peer with specific identity\&. -.sp -Identity should be at least one byte and at most 255 bytes long\&. Identities starting with binary zero are reserved for use by 0MQ infrastructure\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -binary data -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -NULL -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_REP, ZMQ_REQ, ZMQ_ROUTER, ZMQ_DEALER\&. -T} -.TE -.sp 1 -.SS "ZMQ_IMMEDIATE: Retrieve attach\-on\-connect value" -.sp -Retrieve the state of the attach on connect value\&. If set to 1, will delay the attachment of a pipe on connect until the underlying connection has completed\&. This will cause the socket to block if there are no other connections, but will prevent queues from filling on pipes awaiting connection\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -boolean -T} -T{ -.sp -Default value -T}:T{ -.sp -0 (false) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, primarily when using TCP/IPC transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_INVERT_MATCHING: Retrieve inverted filtering status" -.sp -Returns the value of the \fIZMQ_INVERT_MATCHING\fR option\&. A value of 1 means the socket uses inverted prefix matching\&. -.sp -On \fIPUB\fR and \fIXPUB\fR sockets, this causes messages to be sent to all connected sockets \fIexcept\fR those subscribed to a prefix that matches the message\&. On \fISUB\fR sockets, this causes only incoming messages that do \fInot\fR match any of the socket\(cqs subscriptions to be received by the user\&. -.sp -Whenever \fIZMQ_INVERT_MATCHING\fR is set to 1 on a \fIPUB\fR socket, all \fISUB\fR sockets connecting to it must also have the option set to 1\&. Failure to do so will have the \fISUB\fR sockets reject everything the \fIPUB\fR socket sends them\&. \fIXSUB\fR sockets do not need to do this because they do not filter incoming messages\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0,1 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_PUB, ZMQ_XPUB, ZMQ_SUB -T} -.TE -.sp 1 -.SS "ZMQ_IPV4ONLY: Retrieve IPv4\-only socket override status" -.sp -Retrieve the IPv4\-only option for the socket\&. This option is deprecated\&. Please use the ZMQ_IPV6 option\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -boolean -T} -T{ -.sp -Default value -T}:T{ -.sp -1 (true) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_IPV6: Retrieve IPv6 socket status" -.sp -Retrieve the IPv6 option for the socket\&. A value of 1 means IPv6 is enabled on the socket, while 0 means the socket will use only IPv4\&. When IPv6 is enabled the socket will connect to, or accept connections from, both IPv4 and IPv6 hosts\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -boolean -T} -T{ -.sp -Default value -T}:T{ -.sp -0 (false) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_LAST_ENDPOINT: Retrieve the last endpoint set" -.sp -The \fIZMQ_LAST_ENDPOINT\fR option shall retrieve the last endpoint bound for TCP and IPC transports\&. The returned value will be a string in the form of a ZMQ DSN\&. Note that if the TCP host is INADDR_ANY, indicated by a *, then the returned address will be 0\&.0\&.0\&.0 (for IPv4)\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -NULL\-terminated character string -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -NULL -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when binding TCP or IPC transports -T} -.TE -.sp 1 -.SS "ZMQ_LINGER: Retrieve linger period for socket shutdown" -.sp -The \fIZMQ_LINGER\fR option shall retrieve the linger period for the specified \fIsocket\fR\&. The linger period determines how long pending messages which have yet to be sent to a peer shall linger in memory after a socket is closed with \fBzmq_close\fR(3), and further affects the termination of the socket\(cqs context with \fBzmq_ctx_term\fR(3)\&. The following outlines the different behaviours: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -The default value of -\fI\-1\fR -specifies an infinite linger period\&. Pending messages shall not be discarded after a call to -\fIzmq_close()\fR; attempting to terminate the socket\(cqs context with -\fIzmq_ctx_term()\fR -shall block until all pending messages have been sent to a peer\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -The value of -\fI0\fR -specifies no linger period\&. Pending messages shall be discarded immediately when the socket is closed with -\fIzmq_close()\fR\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Positive values specify an upper bound for the linger period in milliseconds\&. Pending messages shall not be discarded after a call to -\fIzmq_close()\fR; attempting to terminate the socket\(cqs context with -\fIzmq_ctx_term()\fR -shall block until either all pending messages have been sent to a peer, or the linger period expires, after which any pending messages shall be discarded\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -Option value type -T}:T{ -int -T} -T{ -Option value unit -T}:T{ -milliseconds -T} -T{ -Default value -T}:T{ -\-1 (infinite) -T} -T{ -Applicable socket types -T}:T{ -all -T} -.TE -.sp 1 -.RE -.SS "ZMQ_MAXMSGSIZE: Maximum acceptable inbound message size" -.sp -The option shall retrieve limit for the inbound messages\&. If a peer sends a message larger than ZMQ_MAXMSGSIZE it is disconnected\&. Value of \-1 means \fIno limit\fR\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int64_t -T} -T{ -.sp -Option value unit -T}:T{ -.sp -bytes -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all -T} -.TE -.sp 1 -.SS "ZMQ_MECHANISM: Retrieve current security mechanism" -.sp -The \fIZMQ_MECHANISM\fR option shall retrieve the current security mechanism for the socket\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -ZMQ_NULL, ZMQ_PLAIN, ZMQ_CURVE, or ZMQ_GSSAPI -T} -T{ -.sp -Default value -T}:T{ -.sp -ZMQ_NULL -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP or IPC transports -T} -.TE -.sp 1 -.SS "ZMQ_MULTICAST_HOPS: Maximum network hops for multicast packets" -.sp -The option shall retrieve time\-to\-live used for outbound multicast packets\&. The default of 1 means that the multicast packets don\(cqt leave the local network\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -network hops -T} -T{ -.sp -Default value -T}:T{ -.sp -1 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using multicast transports -T} -.TE -.sp 1 -.SS "ZMQ_MULTICAST_MAXTPDU: Maximum transport data unit size for multicast packets" -.sp -The \fIZMQ_MULTICAST_MAXTPDU\fR option shall retrieve the maximum transport data unit size used for outbound multicast packets\&. -.sp -This must be set at or below the minimum Maximum Transmission Unit (MTU) for all network paths over which multicast reception is required\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -bytes -T} -T{ -.sp -Default value -T}:T{ -.sp -1500 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using multicast transports -T} -.TE -.sp 1 -.SS "ZMQ_PLAIN_PASSWORD: Retrieve current password" -.sp -The \fIZMQ_PLAIN_PASSWORD\fR option shall retrieve the last password set for the PLAIN security mechanism\&. The returned value shall be a NULL\-terminated string and MAY be empty\&. The returned size SHALL include the terminating null byte\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -NULL\-terminated character string -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -null string -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP or IPC transports -T} -.TE -.sp 1 -.SS "ZMQ_PLAIN_SERVER: Retrieve current PLAIN server role" -.sp -Returns the \fIZMQ_PLAIN_SERVER\fR option, if any, previously set on the socket\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0, 1 -T} -T{ -.sp -Default value -T}:T{ -.sp -int -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP or IPC transports -T} -.TE -.sp 1 -.SS "ZMQ_PLAIN_USERNAME: Retrieve current PLAIN username" -.sp -The \fIZMQ_PLAIN_USERNAME\fR option shall retrieve the last username set for the PLAIN security mechanism\&. The returned value shall be a NULL\-terminated string and MAY be empty\&. The returned size SHALL include the terminating null byte\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -NULL\-terminated character string -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -null string -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP or IPC transports -T} -.TE -.sp 1 -.SS "ZMQ_USE_FD: Retrieve the pre\-allocated socket file descriptor" -.sp -The \fIZMQ_USE_FD\fR option shall retrieve the pre\-allocated file descriptor that has been assigned to a ZMQ socket, if any\&. \-1 shall be returned if a pre\-allocated file descriptor was not set for the socket\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -file descriptor -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all bound sockets, when using IPC or TCP transport -T} -.TE -.sp 1 -.SS "ZMQ_RATE: Retrieve multicast data rate" -.sp -The \fIZMQ_RATE\fR option shall retrieve the maximum send or receive data rate for multicast transports using the specified \fIsocket\fR\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -kilobits per second -T} -T{ -.sp -Default value -T}:T{ -.sp -100 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using multicast transports -T} -.TE -.sp 1 -.SS "ZMQ_RCVBUF: Retrieve kernel receive buffer size" -.sp -The \fIZMQ_RCVBUF\fR option shall retrieve the underlying kernel receive buffer size for the specified \fIsocket\fR\&. For details refer to your operating system documentation for the \fISO_RCVBUF\fR socket option\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -bytes -T} -T{ -.sp -Default value -T}:T{ -.sp -8192 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all -T} -.TE -.sp 1 -.SS "ZMQ_RCVHWM: Retrieve high water mark for inbound messages" -.sp -The \fIZMQ_RCVHWM\fR option shall return the high water mark for inbound messages on the specified \fIsocket\fR\&. The high water mark is a hard limit on the maximum number of outstanding messages 0MQ shall queue in memory for any single peer that the specified \fIsocket\fR is communicating with\&. A value of zero means no limit\&. -.sp -If this limit has been reached the socket shall enter an exceptional state and depending on the socket type, 0MQ shall take appropriate action such as blocking or dropping sent messages\&. Refer to the individual socket descriptions in \fBzmq_socket\fR(3) for details on the exact action taken for each socket type\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -messages -T} -T{ -.sp -Default value -T}:T{ -.sp -1000 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all -T} -.TE -.sp 1 -.SS "ZMQ_RCVMORE: More message data parts to follow" -.sp -The \fIZMQ_RCVMORE\fR option shall return True (1) if the message part last received from the \fIsocket\fR was a data part with more parts to follow\&. If there are no data parts to follow, this option shall return False (0)\&. -.sp -Refer to \fBzmq_send\fR(3) and \fBzmq_recv\fR(3) for a detailed description of multi\-part messages\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -boolean -T} -T{ -.sp -Default value -T}:T{ -.sp -N/A -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all -T} -.TE -.sp 1 -.SS "ZMQ_RCVTIMEO: Maximum time before a socket operation returns with EAGAIN" -.sp -Retrieve the timeout for recv operation on the socket\&. If the value is 0, \fIzmq_recv(3)\fR will return immediately, with a EAGAIN error if there is no message to receive\&. If the value is \-1, it will block until a message is available\&. For all other values, it will wait for a message for that amount of time before returning with an EAGAIN error\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 (infinite) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all -T} -.TE -.sp 1 -.SS "ZMQ_RECONNECT_IVL: Retrieve reconnection interval" -.sp -The \fIZMQ_RECONNECT_IVL\fR option shall retrieve the initial reconnection interval for the specified \fIsocket\fR\&. The reconnection interval is the period 0MQ shall wait between attempts to reconnect disconnected peers when using connection\-oriented transports\&. The value \-1 means no reconnection\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -The reconnection interval may be randomized by 0MQ to prevent reconnection storms in topologies with a large number of peers per socket\&. -.sp .5v -.RE -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -100 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, only for connection\-oriented transports -T} -.TE -.sp 1 -.SS "ZMQ_RECONNECT_IVL_MAX: Retrieve maximum reconnection interval" -.sp -The \fIZMQ_RECONNECT_IVL_MAX\fR option shall retrieve the maximum reconnection interval for the specified \fIsocket\fR\&. This is the maximum period 0MQ shall wait between attempts to reconnect\&. On each reconnect attempt, the previous interval shall be doubled untill ZMQ_RECONNECT_IVL_MAX is reached\&. This allows for exponential backoff strategy\&. Default value means no exponential backoff is performed and reconnect interval calculations are only based on ZMQ_RECONNECT_IVL\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -Values less than ZMQ_RECONNECT_IVL will be ignored\&. -.sp .5v -.RE -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -0 (only use ZMQ_RECONNECT_IVL) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, only for connection\-oriented transport -T} -.TE -.sp 1 -.SS "ZMQ_RECOVERY_IVL: Get multicast recovery interval" -.sp -The \fIZMQ_RECOVERY_IVL\fR option shall retrieve the recovery interval for multicast transports using the specified \fIsocket\fR\&. The recovery interval determines the maximum time in milliseconds that a receiver can be absent from a multicast group before unrecoverable data loss will occur\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -10000 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using multicast transports -T} -.TE -.sp 1 -.SS "ZMQ_SNDBUF: Retrieve kernel transmit buffer size" -.sp -The \fIZMQ_SNDBUF\fR option shall retrieve the underlying kernel transmit buffer size for the specified \fIsocket\fR\&. For details refer to your operating system documentation for the \fISO_SNDBUF\fR socket option\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -bytes -T} -T{ -.sp -Default value -T}:T{ -.sp -8192 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all -T} -.TE -.sp 1 -.SS "ZMQ_SNDHWM: Retrieves high water mark for outbound messages" -.sp -The \fIZMQ_SNDHWM\fR option shall return the high water mark for outbound messages on the specified \fIsocket\fR\&. The high water mark is a hard limit on the maximum number of outstanding messages 0MQ shall queue in memory for any single peer that the specified \fIsocket\fR is communicating with\&. A value of zero means no limit\&. -.sp -If this limit has been reached the socket shall enter an exceptional state and depending on the socket type, 0MQ shall take appropriate action such as blocking or dropping sent messages\&. Refer to the individual socket descriptions in \fBzmq_socket\fR(3) for details on the exact action taken for each socket type\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -messages -T} -T{ -.sp -Default value -T}:T{ -.sp -1000 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all -T} -.TE -.sp 1 -.SS "ZMQ_SNDTIMEO: Maximum time before a socket operation returns with EAGAIN" -.sp -Retrieve the timeout for send operation on the socket\&. If the value is 0, \fIzmq_send(3)\fR will return immediately, with a EAGAIN error if the message cannot be sent\&. If the value is \-1, it will block until the message is sent\&. For all other values, it will try to send the message for that amount of time before returning with an EAGAIN error\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 (infinite) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all -T} -.TE -.sp 1 -.SS "ZMQ_SOCKS_PROXY: Retrieve SOCKS5 proxy address" -.sp -The \fIZMQ_SOCKS_PROXY\fR option shall retrieve the SOCKS5 proxy address in string format\&. The returned value shall be a NULL\-terminated string and MAY be empty\&. The returned size SHALL include the terminating null byte\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -NULL\-terminated character string -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -null string -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transports -T} -.TE -.sp 1 -.SS "ZMQ_TCP_KEEPALIVE: Override SO_KEEPALIVE socket option" -.sp -Override \fISO_KEEPALIVE\fR socket option(where supported by OS)\&. The default value of \-1 means to skip any overrides and leave it to OS default\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -\-1,0,1 -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 (leave to OS default) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_TCP_KEEPALIVE_CNT: Override TCP_KEEPCNT socket option" -.sp -Override \fITCP_KEEPCNT\fR socket option(where supported by OS)\&. The default value of \-1 means to skip any overrides and leave it to OS default\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -\-1,>0 -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 (leave to OS default) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_TCP_KEEPALIVE_IDLE: Override TCP_KEEPIDLE (or TCP_KEEPALIVE on some OS)" -.sp -Override \fITCP_KEEPIDLE\fR(or \fITCP_KEEPALIVE\fR on some OS) socket option (where supported by OS)\&. The default value of \-1 means to skip any overrides and leave it to OS default\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -\-1,>0 -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 (leave to OS default) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_TCP_KEEPALIVE_INTVL: Override TCP_KEEPINTVL socket option" -.sp -Override \fITCP_KEEPINTVL\fR socket option(where supported by OS)\&. The default value of \-1 means to skip any overrides and leave it to OS default\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -\-1,>0 -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 (leave to OS default) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_TCP_MAXRT: Retrieve Max TCP Retransmit Timeout" -.sp -On OSes where it is supported, retrieves how long before an unacknowledged TCP retransmit times out\&. The system normally attempts many TCP retransmits following an exponential backoff strategy\&. This means that after a network outage, it may take a long time before the session can be re\-established\&. Setting this option allows the timeout to happen at a shorter interval\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -0 (leave to OS default) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_THREAD_SAFE: Retrieve socket thread safety" -.sp -The \fIZMQ_THREAD_SAFE\fR option shall retrieve a boolean value indicating whether or not the socket is threadsafe\&. Currently \fIZMQ_CLIENT\fR and \fIZMQ_SERVER\fR sockets are threadsafe\&. -.TS -tab(:); -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -boolean -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all -T} -.TE -.sp 1 -.SS "ZMQ_TOS: Retrieve the Type\-of\-Service socket override status" -.sp -Retrieve the IP_TOS option for the socket\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp ->0 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, only for connection\-oriented transports -T} -.TE -.sp 1 -.SS "ZMQ_TYPE: Retrieve socket type" -.sp -The \fIZMQ_TYPE\fR option shall retrieve the socket type for the specified \fIsocket\fR\&. The socket type is specified at socket creation time and cannot be modified afterwards\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -N/A -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all -T} -.TE -.sp 1 -.SS "ZMQ_ZAP_DOMAIN: Retrieve RFC 27 authentication domain" -.sp -The \fIZMQ_ZAP_DOMAIN\fR option shall retrieve the last ZAP domain set for the socket\&. The returned value shall be a NULL\-terminated string and MAY be empty\&. The returned size SHALL include the terminating null byte\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -character string -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -not set -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transport -T} -.TE -.sp 1 -.SS "ZMQ_VMCI_BUFFER_SIZE: Retrieve buffer size of the VMCI socket" -.sp -The ZMQ_VMCI_BUFFER_SIZE option shall retrieve the size of the underlying buffer for the socket\&. Used during negotiation before the connection is established\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -uint64_t -T} -T{ -.sp -Option value unit -T}:T{ -.sp -bytes -T} -T{ -.sp -Default value -T}:T{ -.sp -65546 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using VMCI transport -T} -.TE -.sp 1 -.SS "ZMQ_VMCI_BUFFER_MIN_SIZE: Retrieve min buffer size of the VMCI socket" -.sp -The ZMQ_VMCI_BUFFER_MIN_SIZE option shall retrieve the min size of the underlying buffer for the socket\&. Used during negotiation before the connection is established\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -uint64_t -T} -T{ -.sp -Option value unit -T}:T{ -.sp -bytes -T} -T{ -.sp -Default value -T}:T{ -.sp -128 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using VMCI transport -T} -.TE -.sp 1 -.SS "ZMQ_VMCI_BUFFER_MAX_SIZE: Retrieve max buffer size of the VMCI socket" -.sp -The ZMQ_VMCI_BUFFER_MAX_SIZE option shall retrieve the max size of the underlying buffer for the socket\&. Used during negotiation before the connection is established\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -uint64_t -T} -T{ -.sp -Option value unit -T}:T{ -.sp -bytes -T} -T{ -.sp -Default value -T}:T{ -.sp -262144 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using VMCI transport -T} -.TE -.sp 1 -.SS "ZMQ_VMCI_CONNECT_TIMEOUT: Retrieve connection timeout of the VMCI socket" -.sp -The ZMQ_VMCI_CONNECT_TIMEOUT option shall retrieve connection timeout for the socket\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using VMCI transport -T} -.TE -.sp 1 -.SH "RETURN VALUE" -.sp -The \fIzmq_getsockopt()\fR function shall return zero if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEINVAL\fR -.RS 4 -The requested option -\fIoption_name\fR -is unknown, or the requested -\fIoption_len\fR -or -\fIoption_value\fR -is invalid, or the size of the buffer pointed to by -\fIoption_value\fR, as specified by -\fIoption_len\fR, is insufficient for storing the option value\&. -.RE -.PP -\fBETERM\fR -.RS 4 -The 0MQ -\fIcontext\fR -associated with the specified -\fIsocket\fR -was terminated\&. -.RE -.PP -\fBENOTSOCK\fR -.RS 4 -The provided -\fIsocket\fR -was invalid\&. -.RE -.PP -\fBEINTR\fR -.RS 4 -The operation was interrupted by delivery of a signal\&. -.RE -.SH "EXAMPLE" -.PP -\fBRetrieving the high water mark for outgoing messages\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -/* Retrieve high water mark into sndhwm */ -int sndhwm; -size_t sndhwm_size = sizeof (sndhwm); -rc = zmq_getsockopt (socket, ZMQ_SNDHWM, &sndhwm, &sndhwm_size); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_setsockopt\fR(3) \fBzmq_socket\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_has.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_has.3 deleted file mode 100644 index 37a0100105..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_has.3 +++ /dev/null @@ -1,124 +0,0 @@ -'\" t -.\" Title: zmq_has -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_HAS" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_has \- check a ZMQ capability -.SH "SYNOPSIS" -.sp -\fBint zmq_has (const char *capability);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_has()\fR function shall report whether a specified capability is available in the library\&. This allows bindings and applications to probe a library directly, for transport and security options\&. -.sp -Capabilities shall be lowercase strings\&. The following capabilities are defined: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -ipc \- the library supports the ipc:// protocol -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -pgm \- the library supports the pgm:// protocol -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -tipc \- the library supports the tipc:// protocol -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -norm \- the library supports the norm:// protocol -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -curve \- the library supports the CURVE security mechanism -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -gssapi \- the library supports the GSSAPI security mechanism -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -draft \- the library is built with the draft api -.RE -.sp -When this method is provided, the zmq\&.h header file will define ZMQ_HAS_CAPABILITIES\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_has()\fR function shall return 1 if the specified capability is provided\&. Otherwise it shall return 0\&. -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_close.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_close.3 deleted file mode 100644 index 098a5a8b3c..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_close.3 +++ /dev/null @@ -1,70 +0,0 @@ -'\" t -.\" Title: zmq_msg_close -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_MSG_CLOSE" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_msg_close \- release 0MQ message -.SH "SYNOPSIS" -.sp -\fBint zmq_msg_close (zmq_msg_t \fR\fB\fI*msg\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_msg_close()\fR function shall inform the 0MQ infrastructure that any resources associated with the message object referenced by \fImsg\fR are no longer required and may be released\&. Actual release of resources associated with the message object shall be postponed by 0MQ until all users of the message or underlying data buffer have indicated it is no longer required\&. -.sp -Applications should ensure that \fIzmq_msg_close()\fR is called once a message is no longer required, otherwise memory leaks may occur\&. Note that this is NOT necessary after a successful \fIzmq_msg_send()\fR\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBCaution\fR -.ps -1 -.br -.sp -Never access \fIzmq_msg_t\fR members directly, instead always use the \fIzmq_msg\fR family of functions\&. -.sp .5v -.RE -.SH "RETURN VALUE" -.sp -The \fIzmq_msg_close()\fR function shall return zero if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEFAULT\fR -.RS 4 -Invalid message\&. -.RE -.SH "SEE ALSO" -.sp -\fBzmq_msg_init\fR(3) \fBzmq_msg_init_size\fR(3) \fBzmq_msg_init_data\fR(3) \fBzmq_msg_data\fR(3) \fBzmq_msg_size\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_copy.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_copy.3 deleted file mode 100644 index d8136ef9aa..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_copy.3 +++ /dev/null @@ -1,106 +0,0 @@ -'\" t -.\" Title: zmq_msg_copy -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_MSG_COPY" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_msg_copy \- copy content of a message to another message -.SH "SYNOPSIS" -.sp -\fBint zmq_msg_copy (zmq_msg_t \fR\fB\fI*dest\fR\fR\fB, zmq_msg_t \fR\fB\fI*src\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_msg_copy()\fR function shall copy the message object referenced by \fIsrc\fR to the message object referenced by \fIdest\fR\&. The original content of \fIdest\fR, if any, shall be released\&. You must initialise \fIdest\fR before copying to it\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBCaution\fR -.ps -1 -.br -.sp -The implementation may choose not to physically copy the message content, rather to share the underlying buffer between \fIsrc\fR and \fIdest\fR\&. Avoid modifying message content after a message has been copied with \fIzmq_msg_copy()\fR, doing so can result in undefined behaviour\&. If what you need is an actual hard copy, allocate a new message using \fIzmq_msg_init_size()\fR and copy the message content using \fImemcpy()\fR\&. -.sp .5v -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBCaution\fR -.ps -1 -.br -.sp -Never access \fIzmq_msg_t\fR members directly, instead always use the \fIzmq_msg\fR family of functions\&. -.sp .5v -.RE -.SH "RETURN VALUE" -.sp -The \fIzmq_msg_copy()\fR function shall return zero if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEFAULT\fR -.RS 4 -Invalid message\&. -.RE -.SH "EXAMPLE" -.PP -\fBCopying a message\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -zmq_msg_t msg; -zmq_msg_init_size (&msg, 255); -memcpy (zmq_msg_data (&msg, "Hello, World", 12); -zmq_msg_t copy; -zmq_msg_init (©); -zmq_msg_copy (©, &msg); -\&.\&.\&. -zmq_msg_close (©); -zmq_msg_close (&msg); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_msg_move\fR(3) \fBzmq_msg_init\fR(3) \fBzmq_msg_init_size\fR(3) \fBzmq_msg_init_data\fR(3) \fBzmq_msg_close\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_data.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_data.3 deleted file mode 100644 index 7525f5cce8..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_data.3 +++ /dev/null @@ -1,65 +0,0 @@ -'\" t -.\" Title: zmq_msg_data -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_MSG_DATA" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_msg_data \- retrieve pointer to message content -.SH "SYNOPSIS" -.sp -\fBvoid *zmq_msg_data (zmq_msg_t \fR\fB\fI*msg\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_msg_data()\fR function shall return a pointer to the message content of the message object referenced by \fImsg\fR\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBCaution\fR -.ps -1 -.br -.sp -Never access \fIzmq_msg_t\fR members directly, instead always use the \fIzmq_msg\fR family of functions\&. -.sp .5v -.RE -.SH "RETURN VALUE" -.sp -Upon successful completion, \fIzmq_msg_data()\fR shall return a pointer to the message content\&. -.SH "ERRORS" -.sp -No errors are defined\&. -.SH "SEE ALSO" -.sp -\fBzmq_msg_size\fR(3) \fBzmq_msg_init\fR(3) \fBzmq_msg_init_size\fR(3) \fBzmq_msg_init_data\fR(3) \fBzmq_msg_close\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_get.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_get.3 deleted file mode 100644 index ec1764be38..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_get.3 +++ /dev/null @@ -1,104 +0,0 @@ -'\" t -.\" Title: zmq_msg_get -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_MSG_GET" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_msg_get \- get message property -.SH "SYNOPSIS" -.sp -\fBint zmq_msg_get (zmq_msg_t \fR\fB\fI*message\fR\fR\fB, int \fR\fB\fIproperty\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_msg_get()\fR function shall return the value for the property specified by the \fIproperty\fR argument for the message pointed to by the \fImessage\fR argument\&. -.sp -The following properties can be retrieved with the \fIzmq_msg_get()\fR function: -.PP -\fBZMQ_MORE\fR -.RS 4 -Indicates that there are more message frames to follow after the -\fImessage\fR\&. -.RE -.PP -\fBZMQ_SRCFD\fR -.RS 4 -Returns the file descriptor of the socket the -\fImessage\fR -was read from\&. This allows application to retrieve the remote endpoint via -\fIgetpeername(2)\fR\&. Be aware that the respective socket might be closed already, reused even\&. Currently only implemented for TCP sockets\&. -.RE -.PP -\fBZMQ_SHARED\fR -.RS 4 -Indicates that a message MAY share underlying storage with another copy of this message\&. -.RE -.SH "RETURN VALUE" -.sp -The \fIzmq_msg_get()\fR function shall return the value for the property if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEINVAL\fR -.RS 4 -The requested -\fIproperty\fR -is unknown\&. -.RE -.SH "EXAMPLE" -.PP -\fBReceiving a multi-frame message\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -zmq_msg_t frame; -while (true) { - // Create an empty 0MQ message to hold the message frame - int rc = zmq_msg_init (&frame); - assert (rc == 0); - // Block until a message is available to be received from socket - rc = zmq_msg_recv (socket, &frame, 0); - assert (rc != \-1); - if (zmq_msg_get (&frame, ZMQ_MORE)) - fprintf (stderr, "more\en"); - else { - fprintf (stderr, "end\en"); - break; - } - zmq_msg_close (&frame); -} -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_msg_set\fR(3) \fBzmq_msg_init\fR(3) \fBzmq_msg_close\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_gets.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_gets.3 deleted file mode 100644 index 2624896f60..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_gets.3 +++ /dev/null @@ -1,93 +0,0 @@ -'\" t -.\" Title: zmq_msg_gets -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_MSG_GETS" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_msg_gets \- get message metadata property -.SH "SYNOPSIS" -.sp -\fBconst char *zmq_msg_gets (zmq_msg_t \fR\fB\fI*message\fR\fR\fB, const char *\fR\fB\fIproperty\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_msg_gets()\fR function shall return the string value for the metadata property specified by the \fIproperty\fR argument for the message pointed to by the \fImessage\fR argument\&. Both the \fIproperty\fR argument and the \fIvalue\fR shall be NULL\-terminated UTF8\-encoded strings\&. -.sp -Metadata is defined on a per\-connection basis during the ZeroMQ connection handshake as specified in \&. -.sp -The following ZMTP properties can be retrieved with the \fIzmq_msg_gets()\fR function: -.sp -.if n \{\ -.RS 4 -.\} -.nf -Socket\-Type -Identity -Resource -.fi -.if n \{\ -.RE -.\} -.sp -Additionally, when available for the underlying transport, the \fBPeer\-Address\fR property will return the IP address of the remote endpoint as returned by getnameinfo(2)\&. -.sp -Other properties may be defined based on the underlying security mechanism, see ZAP authenticated connection sample below\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_msg_gets()\fR function shall return the string value for the property if successful\&. Otherwise it shall return NULL and set \fIerrno\fR to one of the values defined below\&. The caller shall not modify or free the returned value, which shall be owned by the message\&. The encoding of the property and value shall be UTF8\&. -.SH "ERRORS" -.PP -\fBEINVAL\fR -.RS 4 -The requested -\fIproperty\fR -is unknown\&. -.RE -.SH "EXAMPLE" -.PP -\fBGetting the ZAP authenticated user id for a message:\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -zmq_msg_t msg; -zmq_msg_init (&msg); -rc = zmq_msg_recv (&msg, dealer, 0); -assert (rc != \-1); -const char *user_id = zmq_msg_gets (&msg, "User\-Id"); -zmq_msg_close (&msg); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_init.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_init.3 deleted file mode 100644 index baf280b251..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_init.3 +++ /dev/null @@ -1,99 +0,0 @@ -'\" t -.\" Title: zmq_msg_init -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_MSG_INIT" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_msg_init \- initialise empty 0MQ message -.SH "SYNOPSIS" -.sp -\fBint zmq_msg_init (zmq_msg_t \fR\fB\fI*msg\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_msg_init()\fR function shall initialise the message object referenced by \fImsg\fR to represent an empty message\&. This function is most useful when called before receiving a message with \fIzmq_recv()\fR\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBCaution\fR -.ps -1 -.br -.sp -Never access \fIzmq_msg_t\fR members directly, instead always use the \fIzmq_msg\fR family of functions\&. -.sp .5v -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBCaution\fR -.ps -1 -.br -.sp -The functions \fIzmq_msg_init()\fR, \fIzmq_msg_init_data()\fR and \fIzmq_msg_init_size()\fR are mutually exclusive\&. Never initialise the same \fIzmq_msg_t\fR twice\&. -.sp .5v -.RE -.SH "RETURN VALUE" -.sp -The \fIzmq_msg_init()\fR function always returns zero\&. -.SH "ERRORS" -.sp -No errors are defined\&. -.SH "EXAMPLE" -.PP -\fBReceiving a message from a socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -zmq_msg_t msg; -rc = zmq_msg_init (&msg); -assert (rc == 0); -int nbytes = zmq_recv (socket, &msg, 0); -assert (nbytes != \-1); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_msg_init_size\fR(3) \fBzmq_msg_init_data\fR(3) \fBzmq_msg_close\fR(3) \fBzmq_msg_data\fR(3) \fBzmq_msg_size\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_init_data.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_init_data.3 deleted file mode 100644 index 1130b76c72..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_init_data.3 +++ /dev/null @@ -1,146 +0,0 @@ -'\" t -.\" Title: zmq_msg_init_data -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_MSG_INIT_DATA" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_msg_init_data \- initialise 0MQ message from a supplied buffer -.SH "SYNOPSIS" -.sp -\fBtypedef void (zmq_free_fn) (void \fR\fB\fI*data\fR\fR\fB, void \fR\fB\fI*hint\fR\fR\fB);\fR -.sp -\fBint zmq_msg_init_data (zmq_msg_t \fR\fB\fI*msg\fR\fR\fB, void \fR\fB\fI*data\fR\fR\fB, size_t \fR\fB\fIsize\fR\fR\fB, zmq_free_fn \fR\fB\fI*ffn\fR\fR\fB, void \fR\fB\fI*hint\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_msg_init_data()\fR function shall initialise the message object referenced by \fImsg\fR to represent the content referenced by the buffer located at address \fIdata\fR, \fIsize\fR bytes long\&. No copy of \fIdata\fR shall be performed and 0MQ shall take ownership of the supplied buffer\&. -.sp -If provided, the deallocation function \fIffn\fR shall be called once the data buffer is no longer required by 0MQ, with the \fIdata\fR and \fIhint\fR arguments supplied to \fIzmq_msg_init_data()\fR\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBCaution\fR -.ps -1 -.br -.sp -Never access \fIzmq_msg_t\fR members directly, instead always use the \fIzmq_msg\fR family of functions\&. -.sp .5v -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBCaution\fR -.ps -1 -.br -.sp -The deallocation function \fIffn\fR needs to be thread\-safe, since it will be called from an arbitrary thread\&. -.sp .5v -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBCaution\fR -.ps -1 -.br -.sp -If the deallocation function is not provided, the allocated memory will not be freed, and this may cause a memory leak\&. -.sp .5v -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBCaution\fR -.ps -1 -.br -.sp -The functions \fIzmq_msg_init()\fR, \fIzmq_msg_init_data()\fR and \fIzmq_msg_init_size()\fR are mutually exclusive\&. Never initialise the same \fIzmq_msg_t\fR twice\&. -.sp .5v -.RE -.SH "RETURN VALUE" -.sp -The \fIzmq_msg_init_data()\fR function shall return zero if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBENOMEM\fR -.RS 4 -Insufficient storage space is available\&. -.RE -.SH "EXAMPLE" -.PP -\fBInitialising a message from a supplied buffer\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -void my_free (void *data, void *hint) -{ - free (data); -} - - /* \&.\&.\&. */ - -void *data = malloc (6); -assert (data); -memcpy (data, "ABCDEF", 6); -zmq_msg_t msg; -rc = zmq_msg_init_data (&msg, data, 6, my_free, NULL); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_msg_init_size\fR(3) \fBzmq_msg_init\fR(3) \fBzmq_msg_close\fR(3) \fBzmq_msg_data\fR(3) \fBzmq_msg_size\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_init_size.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_init_size.3 deleted file mode 100644 index f0f4eb51ed..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_init_size.3 +++ /dev/null @@ -1,86 +0,0 @@ -'\" t -.\" Title: zmq_msg_init_size -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_MSG_INIT_SIZE" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_msg_init_size \- initialise 0MQ message of a specified size -.SH "SYNOPSIS" -.sp -\fBint zmq_msg_init_size (zmq_msg_t \fR\fB\fI*msg\fR\fR\fB, size_t \fR\fB\fIsize\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_msg_init_size()\fR function shall allocate any resources required to store a message \fIsize\fR bytes long and initialise the message object referenced by \fImsg\fR to represent the newly allocated message\&. -.sp -The implementation shall choose whether to store message content on the stack (small messages) or on the heap (large messages)\&. For performance reasons \fIzmq_msg_init_size()\fR shall not clear the message data\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBCaution\fR -.ps -1 -.br -.sp -Never access \fIzmq_msg_t\fR members directly, instead always use the \fIzmq_msg\fR family of functions\&. -.sp .5v -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBCaution\fR -.ps -1 -.br -.sp -The functions \fIzmq_msg_init()\fR, \fIzmq_msg_init_data()\fR and \fIzmq_msg_init_size()\fR are mutually exclusive\&. Never initialise the same \fIzmq_msg_t\fR twice\&. -.sp .5v -.RE -.SH "RETURN VALUE" -.sp -The \fIzmq_msg_init_size()\fR function shall return zero if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBENOMEM\fR -.RS 4 -Insufficient storage space is available\&. -.RE -.SH "SEE ALSO" -.sp -\fBzmq_msg_init_data\fR(3) \fBzmq_msg_init\fR(3) \fBzmq_msg_close\fR(3) \fBzmq_msg_data\fR(3) \fBzmq_msg_size\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_more.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_more.3 deleted file mode 100644 index d10ff83f89..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_more.3 +++ /dev/null @@ -1,75 +0,0 @@ -'\" t -.\" Title: zmq_msg_more -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_MSG_MORE" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_msg_more \- indicate if there are more message parts to receive -.SH "SYNOPSIS" -.sp -\fBint zmq_msg_more (zmq_msg_t \fR\fB\fI*message\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_msg_more()\fR function indicates whether this is part of a multi\-part message, and there are further parts to receive\&. This method can safely be called after \fIzmq_msg_close()\fR\&. This method is identical to \fIzmq_msg_get()\fR with an argument of ZMQ_MORE\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_msg_more()\fR function shall return zero if this is the final part of a multi\-part message, or the only part of a single\-part message\&. It shall return 1 if there are further parts to receive\&. -.SH "EXAMPLE" -.PP -\fBReceiving a multi-part message\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -zmq_msg_t part; -while (true) { - // Create an empty 0MQ message to hold the message part - int rc = zmq_msg_init (&part); - assert (rc == 0); - // Block until a message is available to be received from socket - rc = zmq_msg_recv (socket, &part, 0); - assert (rc != \-1); - if (zmq_msg_more (&part)) - fprintf (stderr, "more\en"); - else { - fprintf (stderr, "end\en"); - break; - } - zmq_msg_close (&part); -} -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_msg_get\fR(3) \fBzmq_msg_set\fR(3) \fBzmq_msg_init\fR(3) \fBzmq_msg_close\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_move.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_move.3 deleted file mode 100644 index 7328f99464..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_move.3 +++ /dev/null @@ -1,68 +0,0 @@ -'\" t -.\" Title: zmq_msg_move -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_MSG_MOVE" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_msg_move \- move content of a message to another message -.SH "SYNOPSIS" -.sp -\fBint zmq_msg_move (zmq_msg_t \fR\fB\fI*dest\fR\fR\fB, zmq_msg_t \fR\fB\fI*src\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_msg_move()\fR function shall move the content of the message object referenced by \fIsrc\fR to the message object referenced by \fIdest\fR\&. No actual copying of message content is performed, \fIdest\fR is simply updated to reference the new content\&. \fIsrc\fR becomes an empty message after calling \fIzmq_msg_move()\fR\&. The original content of \fIdest\fR, if any, shall be released\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBCaution\fR -.ps -1 -.br -.sp -Never access \fIzmq_msg_t\fR members directly, instead always use the \fIzmq_msg\fR family of functions\&. -.sp .5v -.RE -.SH "RETURN VALUE" -.sp -The \fIzmq_msg_move()\fR function shall return zero if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEFAULT\fR -.RS 4 -Invalid message\&. -.RE -.SH "SEE ALSO" -.sp -\fBzmq_msg_copy\fR(3) \fBzmq_msg_init\fR(3) \fBzmq_msg_init_size\fR(3) \fBzmq_msg_init_data\fR(3) \fBzmq_msg_close\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_recv.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_recv.3 deleted file mode 100644 index 3f8b8a3e7b..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_recv.3 +++ /dev/null @@ -1,161 +0,0 @@ -'\" t -.\" Title: zmq_msg_recv -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_MSG_RECV" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_msg_recv \- receive a message part from a socket -.SH "SYNOPSIS" -.sp -\fBint zmq_msg_recv (zmq_msg_t \fR\fB\fI*msg\fR\fR\fB, void \fR\fB\fI*socket\fR\fR\fB, int \fR\fB\fIflags\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_msg_recv()\fR function is identical to \fBzmq_recvmsg\fR(3), which shall be deprecated in future versions\&. \fIzmq_msg_recv()\fR is more consistent with other message manipulation functions\&. -.sp -The \fIzmq_msg_recv()\fR function shall receive a message part from the socket referenced by the \fIsocket\fR argument and store it in the message referenced by the \fImsg\fR argument\&. Any content previously stored in \fImsg\fR shall be properly deallocated\&. If there are no message parts available on the specified \fIsocket\fR the \fIzmq_msg_recv()\fR function shall block until the request can be satisfied\&. The \fIflags\fR argument is a combination of the flags defined below: -.PP -\fBZMQ_DONTWAIT\fR -.RS 4 -Specifies that the operation should be performed in non\-blocking mode\&. If there are no messages available on the specified -\fIsocket\fR, the -\fIzmq_msg_recv()\fR -function shall fail with -\fIerrno\fR -set to EAGAIN\&. -.RE -.SS "Multi\-part messages" -.sp -A 0MQ message is composed of 1 or more message parts\&. Each message part is an independent \fIzmq_msg_t\fR in its own right\&. 0MQ ensures atomic delivery of messages: peers shall receive either all \fImessage parts\fR of a message or none at all\&. The total number of message parts is unlimited except by available memory\&. -.sp -An application that processes multi\-part messages must use the \fIZMQ_RCVMORE\fR \fBzmq_getsockopt\fR(3) option after calling \fIzmq_msg_recv()\fR to determine if there are further parts to receive\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_msg_recv()\fR function shall return number of bytes in the message if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEAGAIN\fR -.RS 4 -Non\-blocking mode was requested and no messages are available at the moment\&. -.RE -.PP -\fBENOTSUP\fR -.RS 4 -The -\fIzmq_msg_recv()\fR -operation is not supported by this socket type\&. -.RE -.PP -\fBEFSM\fR -.RS 4 -The -\fIzmq_msg_recv()\fR -operation cannot be performed on this socket at the moment due to the socket not being in the appropriate state\&. This error may occur with socket types that switch between several states, such as ZMQ_REP\&. See the -\fImessaging patterns\fR -section of -\fBzmq_socket\fR(3) -for more information\&. -.RE -.PP -\fBETERM\fR -.RS 4 -The 0MQ -\fIcontext\fR -associated with the specified -\fIsocket\fR -was terminated\&. -.RE -.PP -\fBENOTSOCK\fR -.RS 4 -The provided -\fIsocket\fR -was invalid\&. -.RE -.PP -\fBEINTR\fR -.RS 4 -The operation was interrupted by delivery of a signal before a message was available\&. -.RE -.PP -\fBEFAULT\fR -.RS 4 -The message passed to the function was invalid\&. -.RE -.SH "EXAMPLE" -.PP -\fBReceiving a message from a socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -/* Create an empty 0MQ message */ -zmq_msg_t msg; -int rc = zmq_msg_init (&msg); -assert (rc == 0); -/* Block until a message is available to be received from socket */ -rc = zmq_msg_recv (&msg, socket, 0); -assert (rc != \-1); -/* Release message */ -zmq_msg_close (&msg); -.fi -.if n \{\ -.RE -.\} -.PP -\fBReceiving a multi-part message\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -int more; -size_t more_size = sizeof (more); -do { - /* Create an empty 0MQ message to hold the message part */ - zmq_msg_t part; - int rc = zmq_msg_init (&part); - assert (rc == 0); - /* Block until a message is available to be received from socket */ - rc = zmq_msg_recv (&part, socket, 0); - assert (rc != \-1); - /* Determine if more message parts are to follow */ - rc = zmq_getsockopt (socket, ZMQ_RCVMORE, &more, &more_size); - assert (rc == 0); - zmq_msg_close (&part); -} while (more); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_recv\fR(3) \fBzmq_send\fR(3) \fBzmq_msg_send\fR(3) \fBzmq_getsockopt\fR(3) \fBzmq_socket\fR(7) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_routing_id.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_routing_id.3 deleted file mode 100644 index 94a832143b..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_routing_id.3 +++ /dev/null @@ -1,76 +0,0 @@ -'\" t -.\" Title: zmq_msg_routing_id -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_MSG_ROUTING_ID" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_msg_routing_id \- return routing ID for message, if any -.SH "SYNOPSIS" -.sp -\fBuint32_t zmq_msg_routing_id (zmq_msg_t \fR\fB\fI*message\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_msg_routing_id()\fR function returns the routing ID for the message, if any\&. The routing ID is set on all messages received from a \fIZMQ_SERVER\fR socket\&. To send a message to a \fIZMQ_SERVER\fR socket you must set the routing ID of a connected \fIZMQ_CLIENT\fR peer\&. Routing IDs are transient\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_msg_routing_id()\fR function shall return zero if there is no routing ID, otherwise it shall return an unsigned 32\-bit integer greater than zero\&. -.SH "EXAMPLE" -.PP -\fBReceiving a client message and routing ID\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -void *ctx = zmq_ctx_new (); -assert (ctx); - -void *server = zmq_socket (ctx, ZMQ_SERVER); -assert (server); -int rc = zmq_bind (server, "tcp://127\&.0\&.0\&.1:8080"); -assert (rc == 0); - -zmq_msg_t message; -rc = zmq_msg_init (&message); -assert (rc == 0); - -// Receive a message from socket -rc = zmq_msg_recv (server, &message, 0); -assert (rc != \-1); -uint32_t routing_id = zmq_msg_routing_id (&message); -assert (routing_id); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_msg_set_routing_id\fR(3) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_send.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_send.3 deleted file mode 100644 index a6070a8672..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_send.3 +++ /dev/null @@ -1,184 +0,0 @@ -'\" t -.\" Title: zmq_msg_send -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_MSG_SEND" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_msg_send \- send a message part on a socket -.SH "SYNOPSIS" -.sp -\fBint zmq_msg_send (zmq_msg_t \fR\fB\fI*msg\fR\fR\fB, void \fR\fB\fI*socket\fR\fR\fB, int \fR\fB\fIflags\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_msg_send()\fR function is identical to \fBzmq_sendmsg\fR(3), which shall be deprecated in future versions\&. \fIzmq_msg_send()\fR is more consistent with other message manipulation functions\&. -.sp -The \fIzmq_msg_send()\fR function shall queue the message referenced by the \fImsg\fR argument to be sent to the socket referenced by the \fIsocket\fR argument\&. The \fIflags\fR argument is a combination of the flags defined below: -.PP -\fBZMQ_DONTWAIT\fR -.RS 4 -For socket types (DEALER, PUSH) that block when there are no available peers (or all peers have full high\-water mark), specifies that the operation should be performed in non\-blocking mode\&. If the message cannot be queued on the -\fIsocket\fR, the -\fIzmq_msg_send()\fR -function shall fail with -\fIerrno\fR -set to EAGAIN\&. -.RE -.PP -\fBZMQ_SNDMORE\fR -.RS 4 -Specifies that the message being sent is a multi\-part message, and that further message parts are to follow\&. Refer to the section regarding multi\-part messages below for a detailed description\&. -.RE -.sp -The \fIzmq_msg_t\fR structure passed to \fIzmq_msg_send()\fR is nullified during the call\&. If you want to send the same message to multiple sockets you have to copy it (e\&.g\&. using \fIzmq_msg_copy()\fR)\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -A successful invocation of \fIzmq_msg_send()\fR does not indicate that the message has been transmitted to the network, only that it has been queued on the \fIsocket\fR and 0MQ has assumed responsibility for the message\&. You do not need to call \fIzmq_msg_close()\fR after a successful \fIzmq_msg_send()\fR\&. -.sp .5v -.RE -.SS "Multi\-part messages" -.sp -A 0MQ message is composed of 1 or more message parts\&. Each message part is an independent \fIzmq_msg_t\fR in its own right\&. 0MQ ensures atomic delivery of messages: peers shall receive either all \fImessage parts\fR of a message or none at all\&. The total number of message parts is unlimited except by available memory\&. -.sp -An application that sends multi\-part messages must use the \fIZMQ_SNDMORE\fR flag when sending each message part except the final one\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_msg_send()\fR function shall return number of bytes in the message if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEAGAIN\fR -.RS 4 -Non\-blocking mode was requested and the message cannot be sent at the moment\&. -.RE -.PP -\fBENOTSUP\fR -.RS 4 -The -\fIzmq_msg_send()\fR -operation is not supported by this socket type\&. -.RE -.PP -\fBEINVAL\fR -.RS 4 -The sender tried to send multipart data, which the socket type does not allow\&. -.RE -.PP -\fBEFSM\fR -.RS 4 -The -\fIzmq_msg_send()\fR -operation cannot be performed on this socket at the moment due to the socket not being in the appropriate state\&. This error may occur with socket types that switch between several states, such as ZMQ_REP\&. See the -\fImessaging patterns\fR -section of -\fBzmq_socket\fR(3) -for more information\&. -.RE -.PP -\fBETERM\fR -.RS 4 -The 0MQ -\fIcontext\fR -associated with the specified -\fIsocket\fR -was terminated\&. -.RE -.PP -\fBENOTSOCK\fR -.RS 4 -The provided -\fIsocket\fR -was invalid\&. -.RE -.PP -\fBEINTR\fR -.RS 4 -The operation was interrupted by delivery of a signal before the message was sent\&. -.RE -.PP -\fBEFAULT\fR -.RS 4 -Invalid message\&. -.RE -.PP -\fBEHOSTUNREACH\fR -.RS 4 -The message cannot be routed\&. -.RE -.SH "EXAMPLE" -.PP -\fBFilling in a message and sending it to a socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -/* Create a new message, allocating 6 bytes for message content */ -zmq_msg_t msg; -int rc = zmq_msg_init_size (&msg, 6); -assert (rc == 0); -/* Fill in message content with \*(AqAAAAAA\*(Aq */ -memset (zmq_msg_data (&msg), \*(AqA\*(Aq, 6); -/* Send the message to the socket */ -rc = zmq_msg_send (&msg, socket, 0); -assert (rc == 6); -.fi -.if n \{\ -.RE -.\} -.PP -\fBSending a multi-part message\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -/* Send a multi\-part message consisting of three parts to socket */ -rc = zmq_msg_send (&part1, socket, ZMQ_SNDMORE); -rc = zmq_msg_send (&part2, socket, ZMQ_SNDMORE); -/* Final part; no more parts to follow */ -rc = zmq_msg_send (&part3, socket, 0); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_recv\fR(3) \fBzmq_send\fR(3) \fBzmq_msg_recv\fR(3) \fBzmq_socket\fR(7) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_set.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_set.3 deleted file mode 100644 index a2c5da543b..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_set.3 +++ /dev/null @@ -1,56 +0,0 @@ -'\" t -.\" Title: zmq_msg_set -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_MSG_SET" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_msg_set \- set message property -.SH "SYNOPSIS" -.sp -\fBint zmq_msg_set (zmq_msg_t \fR\fB\fI*message\fR\fR\fB, int \fR\fB\fIproperty\fR\fR\fB, int \fR\fB\fIvalue\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_msg_set()\fR function shall set the property specified by the \fIproperty\fR argument to the value of the \fIvalue\fR argument for the 0MQ message fragment pointed to by the \fImessage\fR argument\&. -.sp -Currently the \fIzmq_msg_set()\fR function does not support any property names\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_msg_set()\fR function shall return zero if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEINVAL\fR -.RS 4 -The requested property -\fIproperty\fR -is unknown\&. -.RE -.SH "SEE ALSO" -.sp -\fBzmq_msg_get\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_set_routing_id.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_set_routing_id.3 deleted file mode 100644 index c11c84cd67..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_set_routing_id.3 +++ /dev/null @@ -1,54 +0,0 @@ -'\" t -.\" Title: zmq_msg_set_routing_id -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_MSG_SET_ROUTING_" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_msg_set_routing_id \- set routing ID property on message -.SH "SYNOPSIS" -.sp -\fBint zmq_msg_set_routing_id (zmq_msg_t \fR\fB\fI*message\fR\fR\fB, uint32_t \fR\fB\fIrouting_id\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_msg_set_routing_id()\fR function sets the \fIrouting_id\fR specified, on the the message pointed to by the \fImessage\fR argument\&. The \fIrouting_id\fR must be greater than zero\&. To get a valid routing ID, you must receive a message from a \fIZMQ_SERVER\fR socket, and use the libzmq:zmq_msg_routing_id method\&. Routing IDs are transient\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_msg_set_routing_id()\fR function shall return zero if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEINVAL\fR -.RS 4 -The provided -\fIrouting_id\fR -is zero\&. -.RE -.SH "SEE ALSO" -.sp -\fBzmq_msg_routing_id\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_size.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_size.3 deleted file mode 100644 index 7e808b7223..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_msg_size.3 +++ /dev/null @@ -1,65 +0,0 @@ -'\" t -.\" Title: zmq_msg_size -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_MSG_SIZE" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_msg_size \- retrieve message content size in bytes -.SH "SYNOPSIS" -.sp -\fBsize_t zmq_msg_size (zmq_msg_t \fR\fB\fI*msg\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_msg_size()\fR function shall return the size in bytes of the content of the message object referenced by \fImsg\fR\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBCaution\fR -.ps -1 -.br -.sp -Never access \fIzmq_msg_t\fR members directly, instead always use the \fIzmq_msg\fR family of functions\&. -.sp .5v -.RE -.SH "RETURN VALUE" -.sp -Upon successful completion, \fIzmq_msg_size()\fR shall return the size of the message content in bytes\&. -.SH "ERRORS" -.sp -No errors are defined\&. -.SH "SEE ALSO" -.sp -\fBzmq_msg_data\fR(3) \fBzmq_msg_init\fR(3) \fBzmq_msg_init_size\fR(3) \fBzmq_msg_init_data\fR(3) \fBzmq_msg_close\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_poll.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_poll.3 deleted file mode 100644 index 928bde440e..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_poll.3 +++ /dev/null @@ -1,182 +0,0 @@ -'\" t -.\" Title: zmq_poll -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_POLL" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_poll \- input/output multiplexing -.SH "SYNOPSIS" -.sp -\fBint zmq_poll (zmq_pollitem_t \fR\fB\fI*items\fR\fR\fB, int \fR\fB\fInitems\fR\fR\fB, long \fR\fB\fItimeout\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_poll()\fR function provides a mechanism for applications to multiplex input/output events in a level\-triggered fashion over a set of sockets\&. Each member of the array pointed to by the \fIitems\fR argument is a \fBzmq_pollitem_t\fR structure\&. The \fInitems\fR argument specifies the number of items in the \fIitems\fR array\&. The \fBzmq_pollitem_t\fR structure is defined as follows: -.sp -.if n \{\ -.RS 4 -.\} -.nf -typedef struct -{ - void \fI*socket\fR; - int \fIfd\fR; - short \fIevents\fR; - short \fIrevents\fR; -} zmq_pollitem_t; -.fi -.if n \{\ -.RE -.\} -.sp -For each \fBzmq_pollitem_t\fR item, \fIzmq_poll()\fR shall examine either the 0MQ socket referenced by \fIsocket\fR \fBor\fR the standard socket specified by the file descriptor \fIfd\fR, for the event(s) specified in \fIevents\fR\&. If both \fIsocket\fR and \fIfd\fR are set in a single \fBzmq_pollitem_t\fR, the 0MQ socket referenced by \fIsocket\fR shall take precedence and the value of \fIfd\fR shall be ignored\&. -.sp -For each \fBzmq_pollitem_t\fR item, \fIzmq_poll()\fR shall first clear the \fIrevents\fR member, and then indicate any requested events that have occurred by setting the bit corresponding to the event condition in the \fIrevents\fR member\&. -.sp -If none of the requested events have occurred on any \fBzmq_pollitem_t\fR item, \fIzmq_poll()\fR shall wait \fItimeout\fR milliseconds for an event to occur on any of the requested items\&. If the value of \fItimeout\fR is 0, \fIzmq_poll()\fR shall return immediately\&. If the value of \fItimeout\fR is \-1, \fIzmq_poll()\fR shall block indefinitely until a requested event has occurred on at least one \fBzmq_pollitem_t\fR\&. -.sp -The \fIevents\fR and \fIrevents\fR members of \fBzmq_pollitem_t\fR are bit masks constructed by OR\(cqing a combination of the following event flags: -.PP -\fBZMQ_POLLIN\fR -.RS 4 -For 0MQ sockets, at least one message may be received from the -\fIsocket\fR -without blocking\&. For standard sockets this is equivalent to the -\fIPOLLIN\fR -flag of the -\fIpoll()\fR -system call and generally means that at least one byte of data may be read from -\fIfd\fR -without blocking\&. -.RE -.PP -\fBZMQ_POLLOUT\fR -.RS 4 -For 0MQ sockets, at least one message may be sent to the -\fIsocket\fR -without blocking\&. For standard sockets this is equivalent to the -\fIPOLLOUT\fR -flag of the -\fIpoll()\fR -system call and generally means that at least one byte of data may be written to -\fIfd\fR -without blocking\&. -.RE -.PP -\fBZMQ_POLLERR\fR -.RS 4 -For standard sockets, this flag is passed through -\fIzmq_poll()\fR -to the underlying -\fIpoll()\fR -system call and generally means that some sort of error condition is present on the socket specified by -\fIfd\fR\&. For 0MQ sockets this flag has no effect if set in -\fIevents\fR, and shall never be returned in -\fIrevents\fR -by -\fIzmq_poll()\fR\&. -.RE -.PP -\fBZMQ_POLLPRI\fR -.RS 4 -For 0MQ sockets this flags is of no use\&. For standard sockets this means there is urgent data to read\&. Refer to the POLLPRI flag for more informations\&. For file descriptor, refer to your use case: as an example, GPIO interrupts are signaled through a POLLPRI event\&. This flag has no effect on Windows\&. -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -The \fIzmq_poll()\fR function may be implemented or emulated using operating system interfaces other than \fIpoll()\fR, and as such may be subject to the limits of those interfaces in ways not defined in this documentation\&. -.sp .5v -.RE -.SH "RETURN VALUE" -.sp -Upon successful completion, the \fIzmq_poll()\fR function shall return the number of \fBzmq_pollitem_t\fR structures with events signaled in \fIrevents\fR or 0 if no events have been signaled\&. Upon failure, \fIzmq_poll()\fR shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBETERM\fR -.RS 4 -At least one of the members of the -\fIitems\fR -array refers to a -\fIsocket\fR -whose associated 0MQ -\fIcontext\fR -was terminated\&. -.RE -.PP -\fBEFAULT\fR -.RS 4 -The provided -\fIitems\fR -was not valid (NULL)\&. -.RE -.PP -\fBEINTR\fR -.RS 4 -The operation was interrupted by delivery of a signal before any events were available\&. -.RE -.SH "EXAMPLE" -.PP -\fBPolling indefinitely for input events on both a 0MQ socket and a standard socket.\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -zmq_pollitem_t items [2]; -/* First item refers to 0MQ socket \*(Aqsocket\*(Aq */ -items[0]\&.socket = socket; -items[0]\&.events = ZMQ_POLLIN; -/* Second item refers to standard socket \*(Aqfd\*(Aq */ -items[1]\&.socket = NULL; -items[1]\&.fd = fd; -items[1]\&.events = ZMQ_POLLIN; -/* Poll for events indefinitely */ -int rc = zmq_poll (items, 2, \-1); -assert (rc >= 0); -/* Returned events will be stored in items[]\&.revents */ -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_socket\fR(3) \fBzmq_send\fR(3) \fBzmq_recv\fR(3) \fBzmq\fR(7) -.sp -Your operating system documentation for the \fIpoll()\fR system call\&. -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_proxy.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_proxy.3 deleted file mode 100644 index 73b244b7f3..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_proxy.3 +++ /dev/null @@ -1,89 +0,0 @@ -'\" t -.\" Title: zmq_proxy -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_PROXY" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_proxy \- start built\-in 0MQ proxy -.SH "SYNOPSIS" -.sp -\fBint zmq_proxy (const void \fR\fB\fI*frontend\fR\fR\fB, const void \fR\fB\fI*backend\fR\fR\fB, const void \fR\fB\fI*capture\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_proxy()\fR function starts the built\-in 0MQ proxy in the current application thread\&. -.sp -The proxy connects a frontend socket to a backend socket\&. Conceptually, data flows from frontend to backend\&. Depending on the socket types, replies may flow in the opposite direction\&. The direction is conceptual only; the proxy is fully symmetric and there is no technical difference between frontend and backend\&. -.sp -Before calling \fIzmq_proxy()\fR you must set any socket options, and connect or bind both frontend and backend sockets\&. The two conventional proxy models are: -.sp -\fIzmq_proxy()\fR runs in the current thread and returns only if/when the current context is closed\&. -.sp -If the capture socket is not NULL, the proxy shall send all messages, received on both frontend and backend, to the capture socket\&. The capture socket should be a \fIZMQ_PUB\fR, \fIZMQ_DEALER\fR, \fIZMQ_PUSH\fR, or \fIZMQ_PAIR\fR socket\&. -.sp -Refer to \fBzmq_socket\fR(3) for a description of the available socket types\&. -.SH "EXAMPLE USAGE" -.SS "Shared Queue" -.sp -When the frontend is a ZMQ_ROUTER socket, and the backend is a ZMQ_DEALER socket, the proxy shall act as a shared queue that collects requests from a set of clients, and distributes these fairly among a set of services\&. Requests shall be fair\-queued from frontend connections and distributed evenly across backend connections\&. Replies shall automatically return to the client that made the original request\&. -.SS "Forwarder" -.sp -When the frontend is a ZMQ_XSUB socket, and the backend is a ZMQ_XPUB socket, the proxy shall act as a message forwarder that collects messages from a set of publishers and forwards these to a set of subscribers\&. This may be used to bridge networks transports, e\&.g\&. read on tcp:// and forward on pgm://\&. -.SS "Streamer" -.sp -When the frontend is a ZMQ_PULL socket, and the backend is a ZMQ_PUSH socket, the proxy shall collect tasks from a set of clients and forwards these to a set of workers using the pipeline pattern\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_proxy()\fR function always returns \-1 and \fIerrno\fR set to \fBETERM\fR or \fBEINTR\fR (the 0MQ \fIcontext\fR associated with either of the specified sockets was terminated)\&. -.SH "EXAMPLE" -.PP -\fBCreating a shared queue proxy\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Create frontend and backend sockets -void *frontend = zmq_socket (context, ZMQ_ROUTER); -assert (backend); -void *backend = zmq_socket (context, ZMQ_DEALER); -assert (frontend); -// Bind both sockets to TCP ports -assert (zmq_bind (frontend, "tcp://*:5555") == 0); -assert (zmq_bind (backend, "tcp://*:5556") == 0); -// Start the queue proxy, which runs until ETERM -zmq_proxy (frontend, backend, NULL); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_bind\fR(3) \fBzmq_connect\fR(3) \fBzmq_socket\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_proxy_steerable.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_proxy_steerable.3 deleted file mode 100644 index 2cf1209e9c..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_proxy_steerable.3 +++ /dev/null @@ -1,112 +0,0 @@ -'\" t -.\" Title: zmq_proxy_steerable -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_PROXY_STEERABLE" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_proxy_steerable \- built\-in 0MQ proxy with control flow -.SH "SYNOPSIS" -.sp -\fBint zmq_proxy_steerable (const void \fR\fB\fI*frontend\fR\fR\fB, const void \fR\fB\fI*backend\fR\fR\fB, const void \fR\fB\fI*capture\fR\fR\fB, const void \fR\fB\fI*control\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_proxy_steerable()\fR function starts the built\-in 0MQ proxy in the current application thread, as \fIzmq_proxy()\fR do\&. Please, refer to this function for the general description and usage\&. We describe here only the additional control flow provided by the socket passed as the fourth argument "control"\&. -.sp -If the control socket is not NULL, the proxy supports control flow\&. If \fIPAUSE\fR is received on this socket, the proxy suspends its activities\&. If \fIRESUME\fR is received, it goes on\&. If \fITERMINATE\fR is received, it terminates smoothly\&. At start, the proxy runs normally as if zmq_proxy was used\&. -.sp -If the control socket is NULL, the function behave exactly as if zmq_proxy had been called\&. -.sp -Refer to \fBzmq_socket\fR(3) for a description of the available socket types\&. Refer to \fBzmq_proxy\fR(3) for a description of the zmq_proxy\&. -.SH "EXAMPLE USAGE" -.sp -cf zmq_proxy -.SH "RETURN VALUE" -.sp -The \fIzmq_proxy_steerable()\fR function returns 0 if TERMINATE is sent to its control socket\&. Otherwise, it returns \-1 and \fIerrno\fR set to \fBETERM\fR or \fBEINTR\fR (the 0MQ \fIcontext\fR associated with either of the specified sockets was terminated)\&. -.SH "EXAMPLE" -.PP -\fBCreating a shared queue proxy\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Create frontend, backend and control sockets -void *frontend = zmq_socket (context, ZMQ_ROUTER); -assert (backend); -void *backend = zmq_socket (context, ZMQ_DEALER); -assert (frontend); -void *control = zmq_socket (context, ZMQ_SUB); -assert (control); - -// Bind sockets to TCP ports -assert (zmq_bind (frontend, "tcp://*:5555") == 0); -assert (zmq_bind (backend, "tcp://*:5556") == 0); -assert (zmq_connect (control, "tcp://*:5557") == 0); - -// Subscribe to the control socket since we have chosen SUB here -assert (zmq_setsockopt (control, ZMQ_SUBSCRIBE, "", 0)); - -// Start the queue proxy, which runs until ETERM or "TERMINATE" -// received on the control socket -zmq_proxy_steerable (frontend, backend, NULL, control); -.fi -.if n \{\ -.RE -.\} -.PP -\fBSet up a controller in another node, process or whatever\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -void *control = zmq_socket (context, ZMQ_PUB); -assert (control); -assert (zmq_bind (control, "tcp://*:5557") == 0); - -// pause the proxy -assert (zmq_send (control, "PAUSE", 5, 0) == 0); - -// resume the proxy -assert (zmq_send (control, "RESUME", 6, 0) == 0); - -// terminate the proxy -assert (zmq_send (control, "TERMINATE", 9, 0) == 0); -\-\-\- - - -SEE ALSO -.fi -.if n \{\ -.RE -.\} -.sp -\fBzmq_proxy\fR(3) \fBzmq_bind\fR(3) \fBzmq_connect\fR(3) \fBzmq_socket\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_recv.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_recv.3 deleted file mode 100644 index f90366ae30..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_recv.3 +++ /dev/null @@ -1,122 +0,0 @@ -'\" t -.\" Title: zmq_recv -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_RECV" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_recv \- receive a message part from a socket -.SH "SYNOPSIS" -.sp -\fBint zmq_recv (void \fR\fB\fI*socket\fR\fR\fB, void \fR\fB\fI*buf\fR\fR\fB, size_t \fR\fB\fIlen\fR\fR\fB, int \fR\fB\fIflags\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_recv()\fR function shall receive a message from the socket referenced by the \fIsocket\fR argument and store it in the buffer referenced by the \fIbuf\fR argument\&. Any bytes exceeding the length specified by the \fIlen\fR argument shall be truncated\&. If there are no messages available on the specified \fIsocket\fR the \fIzmq_recv()\fR function shall block until the request can be satisfied\&. The \fIflags\fR argument is a combination of the flags defined below: The \fIbuf\fR argument may be null if len is zero\&. -.PP -\fBZMQ_DONTWAIT\fR -.RS 4 -Specifies that the operation should be performed in non\-blocking mode\&. If there are no messages available on the specified -\fIsocket\fR, the -\fIzmq_recv()\fR -function shall fail with -\fIerrno\fR -set to EAGAIN\&. -.RE -.SS "Multi\-part messages" -.sp -A 0MQ message is composed of 1 or more message parts\&. 0MQ ensures atomic delivery of messages: peers shall receive either all \fImessage parts\fR of a message or none at all\&. The total number of message parts is unlimited except by available memory\&. -.sp -An application that processes multi\-part messages must use the \fIZMQ_RCVMORE\fR \fBzmq_getsockopt\fR(3) option after calling \fIzmq_recv()\fR to determine if there are further parts to receive\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_recv()\fR function shall return number of bytes in the message if successful\&. Note that the value can exceed the value of the \fIlen\fR parameter in case the message was truncated\&. If not successful the function shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEAGAIN\fR -.RS 4 -Non\-blocking mode was requested and no messages are available at the moment\&. -.RE -.PP -\fBENOTSUP\fR -.RS 4 -The -\fIzmq_recv()\fR -operation is not supported by this socket type\&. -.RE -.PP -\fBEFSM\fR -.RS 4 -The -\fIzmq_recv()\fR -operation cannot be performed on this socket at the moment due to the socket not being in the appropriate state\&. This error may occur with socket types that switch between several states, such as ZMQ_REP\&. See the -\fImessaging patterns\fR -section of -\fBzmq_socket\fR(3) -for more information\&. -.RE -.PP -\fBETERM\fR -.RS 4 -The 0MQ -\fIcontext\fR -associated with the specified -\fIsocket\fR -was terminated\&. -.RE -.PP -\fBENOTSOCK\fR -.RS 4 -The provided -\fIsocket\fR -was invalid\&. -.RE -.PP -\fBEINTR\fR -.RS 4 -The operation was interrupted by delivery of a signal before a message was available\&. -.RE -.SH "EXAMPLE" -.PP -\fBReceiving a message from a socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -char buf [256]; -nbytes = zmq_recv (socket, buf, 256, 0); -assert (nbytes != \-1); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_send\fR(3) \fBzmq_getsockopt\fR(3) \fBzmq_socket\fR(7) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_recvmsg.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_recvmsg.3 deleted file mode 100644 index c3b0b44bb1..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_recvmsg.3 +++ /dev/null @@ -1,175 +0,0 @@ -'\" t -.\" Title: zmq_recvmsg -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_RECVMSG" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_recvmsg \- receive a message part from a socket -.SH "SYNOPSIS" -.sp -\fBint zmq_recvmsg (void \fR\fB\fI*socket\fR\fR\fB, zmq_msg_t \fR\fB\fI*msg\fR\fR\fB, int \fR\fB\fIflags\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_recvmsg()\fR function shall receive a message part from the socket referenced by the \fIsocket\fR argument and store it in the message referenced by the \fImsg\fR argument\&. Any content previously stored in \fImsg\fR shall be properly deallocated\&. If there are no message parts available on the specified \fIsocket\fR the \fIzmq_recvmsg()\fR function shall block until the request can be satisfied\&. The \fIflags\fR argument is a combination of the flags defined below: -.PP -\fBZMQ_DONTWAIT\fR -.RS 4 -Specifies that the operation should be performed in non\-blocking mode\&. If there are no messages available on the specified -\fIsocket\fR, the -\fIzmq_recvmsg()\fR -function shall fail with -\fIerrno\fR -set to EAGAIN\&. -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -this API method is deprecated in favor of zmq_msg_recv(3)\&. -.sp .5v -.RE -.SS "Multi\-part messages" -.sp -A 0MQ message is composed of 1 or more message parts\&. Each message part is an independent \fIzmq_msg_t\fR in its own right\&. 0MQ ensures atomic delivery of messages: peers shall receive either all \fImessage parts\fR of a message or none at all\&. The total number of message parts is unlimited except by available memory\&. -.sp -An application that processes multi\-part messages must use the \fIZMQ_RCVMORE\fR \fBzmq_getsockopt\fR(3) option after calling \fIzmq_recvmsg()\fR to determine if there are further parts to receive\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_recvmsg()\fR function shall return number of bytes in the message if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEAGAIN\fR -.RS 4 -Non\-blocking mode was requested and no messages are available at the moment\&. -.RE -.PP -\fBENOTSUP\fR -.RS 4 -The -\fIzmq_recvmsg()\fR -operation is not supported by this socket type\&. -.RE -.PP -\fBEFSM\fR -.RS 4 -The -\fIzmq_recvmsg()\fR -operation cannot be performed on this socket at the moment due to the socket not being in the appropriate state\&. This error may occur with socket types that switch between several states, such as ZMQ_REP\&. See the -\fImessaging patterns\fR -section of -\fBzmq_socket\fR(3) -for more information\&. -.RE -.PP -\fBETERM\fR -.RS 4 -The 0MQ -\fIcontext\fR -associated with the specified -\fIsocket\fR -was terminated\&. -.RE -.PP -\fBENOTSOCK\fR -.RS 4 -The provided -\fIsocket\fR -was invalid\&. -.RE -.PP -\fBEINTR\fR -.RS 4 -The operation was interrupted by delivery of a signal before a message was available\&. -.RE -.PP -\fBEFAULT\fR -.RS 4 -The message passed to the function was invalid\&. -.RE -.SH "EXAMPLE" -.PP -\fBReceiving a message from a socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -/* Create an empty 0MQ message */ -zmq_msg_t msg; -int rc = zmq_msg_init (&msg); -assert (rc == 0); -/* Block until a message is available to be received from socket */ -rc = zmq_recvmsg (socket, &msg, 0); -assert (rc != \-1); -/* Release message */ -zmq_msg_close (&msg); -.fi -.if n \{\ -.RE -.\} -.PP -\fBReceiving a multi-part message\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -int more; -size_t more_size = sizeof (more); -do { - /* Create an empty 0MQ message to hold the message part */ - zmq_msg_t part; - int rc = zmq_msg_init (&part); - assert (rc == 0); - /* Block until a message is available to be received from socket */ - rc = zmq_recvmsg (socket, &part, 0); - assert (rc != \-1); - /* Determine if more message parts are to follow */ - rc = zmq_getsockopt (socket, ZMQ_RCVMORE, &more, &more_size); - assert (rc == 0); - zmq_msg_close (&part); -} while (more); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_recv\fR(3) \fBzmq_send\fR(3) \fBzmq_getsockopt\fR(3) \fBzmq_socket\fR(7) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_send.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_send.3 deleted file mode 100644 index f0bb2adadb..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_send.3 +++ /dev/null @@ -1,158 +0,0 @@ -'\" t -.\" Title: zmq_send -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_SEND" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_send \- send a message part on a socket -.SH "SYNOPSIS" -.sp -\fBint zmq_send (void \fR\fB\fI*socket\fR\fR\fB, void \fR\fB\fI*buf\fR\fR\fB, size_t \fR\fB\fIlen\fR\fR\fB, int \fR\fB\fIflags\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_send()\fR function shall queue a message created from the buffer referenced by the \fIbuf\fR and \fIlen\fR arguments\&. The \fIflags\fR argument is a combination of the flags defined below: -.PP -\fBZMQ_DONTWAIT\fR -.RS 4 -For socket types (DEALER, PUSH) that block when there are no available peers (or all peers have full high\-water mark), specifies that the operation should be performed in non\-blocking mode\&. If the message cannot be queued on the -\fIsocket\fR, the -\fIzmq_send()\fR -function shall fail with -\fIerrno\fR -set to EAGAIN\&. -.RE -.PP -\fBZMQ_SNDMORE\fR -.RS 4 -Specifies that the message being sent is a multi\-part message, and that further message parts are to follow\&. Refer to the section regarding multi\-part messages below for a detailed description\&. -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -A successful invocation of \fIzmq_send()\fR does not indicate that the message has been transmitted to the network, only that it has been queued on the \fIsocket\fR and 0MQ has assumed responsibility for the message\&. -.sp .5v -.RE -.SS "Multi\-part messages" -.sp -A 0MQ message is composed of 1 or more message parts\&. 0MQ ensures atomic delivery of messages: peers shall receive either all \fImessage parts\fR of a message or none at all\&. The total number of message parts is unlimited except by available memory\&. -.sp -An application that sends multi\-part messages must use the \fIZMQ_SNDMORE\fR flag when sending each message part except the final one\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_send()\fR function shall return number of bytes in the message if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEAGAIN\fR -.RS 4 -Non\-blocking mode was requested and the message cannot be sent at the moment\&. -.RE -.PP -\fBENOTSUP\fR -.RS 4 -The -\fIzmq_send()\fR -operation is not supported by this socket type\&. -.RE -.PP -\fBEINVAL\fR -.RS 4 -The sender tried to send multipart data, which the socket type does not allow\&. -.RE -.PP -\fBEFSM\fR -.RS 4 -The -\fIzmq_send()\fR -operation cannot be performed on this socket at the moment due to the socket not being in the appropriate state\&. This error may occur with socket types that switch between several states, such as ZMQ_REP\&. See the -\fImessaging patterns\fR -section of -\fBzmq_socket\fR(3) -for more information\&. -.RE -.PP -\fBETERM\fR -.RS 4 -The 0MQ -\fIcontext\fR -associated with the specified -\fIsocket\fR -was terminated\&. -.RE -.PP -\fBENOTSOCK\fR -.RS 4 -The provided -\fIsocket\fR -was invalid\&. -.RE -.PP -\fBEINTR\fR -.RS 4 -The operation was interrupted by delivery of a signal before the message was sent\&. -.RE -.PP -\fBEHOSTUNREACH\fR -.RS 4 -The message cannot be routed\&. -.RE -.SH "EXAMPLE" -.PP -\fBSending a multi-part message\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -/* Send a multi\-part message consisting of three parts to socket */ -rc = zmq_send (socket, "ABC", 3, ZMQ_SNDMORE); -assert (rc == 3); -rc = zmq_send (socket, "DEFGH", 5, ZMQ_SNDMORE); -assert (rc == 5); -/* Final part; no more parts to follow */ -rc = zmq_send (socket, "JK", 2, 0); -assert (rc == 2); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_send_const\fR(3) \fBzmq_recv\fR(3) \fBzmq_socket\fR(7) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_send_const.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_send_const.3 deleted file mode 100644 index 11175ff326..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_send_const.3 +++ /dev/null @@ -1,153 +0,0 @@ -'\" t -.\" Title: zmq_send_const -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_SEND_CONST" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_send_const \- send a constant\-memory message part on a socket -.SH "SYNOPSIS" -.sp -\fBint zmq_send_const (void \fR\fB\fI*socket\fR\fR\fB, void \fR\fB\fI*buf\fR\fR\fB, size_t \fR\fB\fIlen\fR\fR\fB, int \fR\fB\fIflags\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_send_const()\fR function shall queue a message created from the buffer referenced by the \fIbuf\fR and \fIlen\fR arguments\&. The message buffer is assumed to be constant\-memory and will therefore not be copied or deallocated in any way\&. The \fIflags\fR argument is a combination of the flags defined below: -.PP -\fBZMQ_DONTWAIT\fR -.RS 4 -For socket types (DEALER, PUSH) that block when there are no available peers (or all peers have full high\-water mark), specifies that the operation should be performed in non\-blocking mode\&. If the message cannot be queued on the -\fIsocket\fR, the -\fIzmq_send_const()\fR -function shall fail with -\fIerrno\fR -set to EAGAIN\&. -.RE -.PP -\fBZMQ_SNDMORE\fR -.RS 4 -Specifies that the message being sent is a multi\-part message, and that further message parts are to follow\&. Refer to the section regarding multi\-part messages below for a detailed description\&. -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -A successful invocation of \fIzmq_send_const()\fR does not indicate that the message has been transmitted to the network, only that it has been queued on the \fIsocket\fR and 0MQ has assumed responsibility for the message\&. -.sp .5v -.RE -.SS "Multi\-part messages" -.sp -A 0MQ message is composed of 1 or more message parts\&. 0MQ ensures atomic delivery of messages: peers shall receive either all \fImessage parts\fR of a message or none at all\&. The total number of message parts is unlimited except by available memory\&. -.sp -An application that sends multi\-part messages must use the \fIZMQ_SNDMORE\fR flag when sending each message part except the final one\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_send_const()\fR function shall return number of bytes in the message if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEAGAIN\fR -.RS 4 -Non\-blocking mode was requested and the message cannot be sent at the moment\&. -.RE -.PP -\fBENOTSUP\fR -.RS 4 -The -\fIzmq_send_const()\fR -operation is not supported by this socket type\&. -.RE -.PP -\fBEFSM\fR -.RS 4 -The -\fIzmq_send_const()\fR -operation cannot be performed on this socket at the moment due to the socket not being in the appropriate state\&. This error may occur with socket types that switch between several states, such as ZMQ_REP\&. See the -\fImessaging patterns\fR -section of -\fBzmq_socket\fR(3) -for more information\&. -.RE -.PP -\fBETERM\fR -.RS 4 -The 0MQ -\fIcontext\fR -associated with the specified -\fIsocket\fR -was terminated\&. -.RE -.PP -\fBENOTSOCK\fR -.RS 4 -The provided -\fIsocket\fR -was invalid\&. -.RE -.PP -\fBEINTR\fR -.RS 4 -The operation was interrupted by delivery of a signal before the message was sent\&. -.RE -.PP -\fBEHOSTUNREACH\fR -.RS 4 -The message cannot be routed\&. -.RE -.SH "EXAMPLE" -.PP -\fBSending a multi-part message\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -/* Send a multi\-part message consisting of three parts to socket */ -rc = zmq_send_const (socket, "ABC", 3, ZMQ_SNDMORE); -assert (rc == 3); -rc = zmq_send_const (socket, "DEFGH", 5, ZMQ_SNDMORE); -assert (rc == 5); -/* Final part; no more parts to follow */ -rc = zmq_send_const (socket, "JK", 2, 0); -assert (rc == 2); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_send\fR(3) \fBzmq_recv\fR(3) \fBzmq_socket\fR(7) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_sendmsg.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_sendmsg.3 deleted file mode 100644 index 4074be3a45..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_sendmsg.3 +++ /dev/null @@ -1,198 +0,0 @@ -'\" t -.\" Title: zmq_sendmsg -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_SENDMSG" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_sendmsg \- send a message part on a socket -.SH "SYNOPSIS" -.sp -\fBint zmq_sendmsg (void \fR\fB\fI*socket\fR\fR\fB, zmq_msg_t \fR\fB\fI*msg\fR\fR\fB, int \fR\fB\fIflags\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_sendmsg()\fR function shall queue the message referenced by the \fImsg\fR argument to be sent to the socket referenced by the \fIsocket\fR argument\&. The \fIflags\fR argument is a combination of the flags defined below: -.PP -\fBZMQ_DONTWAIT\fR -.RS 4 -For socket types (DEALER, PUSH) that block when there are no available peers (or all peers have full high\-water mark), specifies that the operation should be performed in non\-blocking mode\&. If the message cannot be queued on the -\fIsocket\fR, the -\fIzmq_sendmsg()\fR -function shall fail with -\fIerrno\fR -set to EAGAIN\&. -.RE -.PP -\fBZMQ_SNDMORE\fR -.RS 4 -Specifies that the message being sent is a multi\-part message, and that further message parts are to follow\&. Refer to the section regarding multi\-part messages below for a detailed description\&. -.RE -.sp -The \fIzmq_msg_t\fR structure passed to \fIzmq_sendmsg()\fR is nullified during the call\&. If you want to send the same message to multiple sockets you have to copy it (e\&.g\&. using \fIzmq_msg_copy()\fR)\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -A successful invocation of \fIzmq_sendmsg()\fR does not indicate that the message has been transmitted to the network, only that it has been queued on the \fIsocket\fR and 0MQ has assumed responsibility for the message\&. -.sp .5v -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -this API method is deprecated in favor of zmq_msg_send(3)\&. -.sp .5v -.RE -.SS "Multi\-part messages" -.sp -A 0MQ message is composed of 1 or more message parts\&. Each message part is an independent \fIzmq_msg_t\fR in its own right\&. 0MQ ensures atomic delivery of messages: peers shall receive either all \fImessage parts\fR of a message or none at all\&. The total number of message parts is unlimited except by available memory\&. -.sp -An application that sends multi\-part messages must use the \fIZMQ_SNDMORE\fR flag when sending each message part except the final one\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_sendmsg()\fR function shall return number of bytes in the message if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEAGAIN\fR -.RS 4 -Non\-blocking mode was requested and the message cannot be sent at the moment\&. -.RE -.PP -\fBENOTSUP\fR -.RS 4 -The -\fIzmq_sendmsg()\fR -operation is not supported by this socket type\&. -.RE -.PP -\fBEINVAL\fR -.RS 4 -The sender tried to send multipart data, which the socket type does not allow\&. -.RE -.PP -\fBEFSM\fR -.RS 4 -The -\fIzmq_sendmsg()\fR -operation cannot be performed on this socket at the moment due to the socket not being in the appropriate state\&. This error may occur with socket types that switch between several states, such as ZMQ_REP\&. See the -\fImessaging patterns\fR -section of -\fBzmq_socket\fR(3) -for more information\&. -.RE -.PP -\fBETERM\fR -.RS 4 -The 0MQ -\fIcontext\fR -associated with the specified -\fIsocket\fR -was terminated\&. -.RE -.PP -\fBENOTSOCK\fR -.RS 4 -The provided -\fIsocket\fR -was invalid\&. -.RE -.PP -\fBEINTR\fR -.RS 4 -The operation was interrupted by delivery of a signal before the message was sent\&. -.RE -.PP -\fBEFAULT\fR -.RS 4 -Invalid message\&. -.RE -.PP -\fBEHOSTUNREACH\fR -.RS 4 -The message cannot be routed\&. -.RE -.SH "EXAMPLE" -.PP -\fBFilling in a message and sending it to a socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -/* Create a new message, allocating 6 bytes for message content */ -zmq_msg_t msg; -int rc = zmq_msg_init_size (&msg, 6); -assert (rc == 0); -/* Fill in message content with \*(AqAAAAAA\*(Aq */ -memset (zmq_msg_data (&msg), \*(AqA\*(Aq, 6); -/* Send the message to the socket */ -rc = zmq_sendmsg (socket, &msg, 0); -assert (rc == 6); -.fi -.if n \{\ -.RE -.\} -.PP -\fBSending a multi-part message\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -/* Send a multi\-part message consisting of three parts to socket */ -rc = zmq_sendmsg (socket, &part1, ZMQ_SNDMORE); -rc = zmq_sendmsg (socket, &part2, ZMQ_SNDMORE); -/* Final part; no more parts to follow */ -rc = zmq_sendmsg (socket, &part3, 0); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_recv\fR(3) \fBzmq_socket\fR(7) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_setsockopt.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_setsockopt.3 deleted file mode 100644 index af381286e8..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_setsockopt.3 +++ /dev/null @@ -1,3201 +0,0 @@ -'\" t -.\" Title: zmq_setsockopt -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_SETSOCKOPT" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_setsockopt \- set 0MQ socket options -.SH "SYNOPSIS" -.sp -\fBint zmq_setsockopt (void \fR\fB\fI*socket\fR\fR\fB, int \fR\fB\fIoption_name\fR\fR\fB, const void \fR\fB\fI*option_value\fR\fR\fB, size_t \fR\fB\fIoption_len\fR\fR\fB);\fR -.sp -Caution: All options, with the exception of ZMQ_SUBSCRIBE, ZMQ_UNSUBSCRIBE, ZMQ_LINGER, ZMQ_ROUTER_HANDOVER, ZMQ_ROUTER_MANDATORY, ZMQ_PROBE_ROUTER, ZMQ_XPUB_VERBOSE, ZMQ_XPUB_VERBOSER, ZMQ_REQ_CORRELATE, ZMQ_REQ_RELAXED, ZMQ_SNDHWM and ZMQ_RCVHWM, only take effect for subsequent socket bind/connects\&. -.sp -Specifically, security options take effect for subsequent bind/connect calls, and can be changed at any time to affect subsequent binds and/or connects\&. -.SH "DESCRIPTION" -.sp -The \fIzmq_setsockopt()\fR function shall set the option specified by the \fIoption_name\fR argument to the value pointed to by the \fIoption_value\fR argument for the 0MQ socket pointed to by the \fIsocket\fR argument\&. The \fIoption_len\fR argument is the size of the option value in bytes\&. For options taking a value of type "character string", the provided byte data should either contain no zero bytes, or end in a single zero byte (terminating ASCII NUL character)\&. -.sp -The following socket options can be set with the \fIzmq_setsockopt()\fR function: -.SS "ZMQ_AFFINITY: Set I/O thread affinity" -.sp -The \fIZMQ_AFFINITY\fR option shall set the I/O thread affinity for newly created connections on the specified \fIsocket\fR\&. -.sp -Affinity determines which threads from the 0MQ I/O thread pool associated with the socket\(cqs \fIcontext\fR shall handle newly created connections\&. A value of zero specifies no affinity, meaning that work shall be distributed fairly among all 0MQ I/O threads in the thread pool\&. For non\-zero values, the lowest bit corresponds to thread 1, second lowest bit to thread 2 and so on\&. For example, a value of 3 specifies that subsequent connections on \fIsocket\fR shall be handled exclusively by I/O threads 1 and 2\&. -.sp -See also \fBzmq_init\fR(3) for details on allocating the number of I/O threads for a specific \fIcontext\fR\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -uint64_t -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A (bitmap) -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -N/A -T} -.TE -.sp 1 -.SS "ZMQ_BACKLOG: Set maximum length of the queue of outstanding connections" -.sp -The \fIZMQ_BACKLOG\fR option shall set the maximum length of the queue of outstanding peer connections for the specified \fIsocket\fR; this only applies to connection\-oriented transports\&. For details refer to your operating system documentation for the \fIlisten\fR function\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -connections -T} -T{ -.sp -Default value -T}:T{ -.sp -100 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, only for connection\-oriented transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_CONNECT_RID: Assign the next outbound connection id" -.sp -The \fIZMQ_CONNECT_RID\fR option sets the peer id of the next host connected via the zmq_connect() call, and immediately readies that connection for data transfer with the named id\&. This option applies only to the first subsequent call to zmq_connect(), calls thereafter use default connection behaviour\&. -.sp -Typical use is to set this socket option ahead of each zmq_connect() attempt to a new host\&. Each connection MUST be assigned a unique name\&. Assigning a name that is already in use is not allowed\&. -.sp -Useful when connecting ROUTER to ROUTER, or STREAM to STREAM, as it allows for immediate sending to peers\&. Outbound id framing requirements for ROUTER and STREAM sockets apply\&. -.sp -The peer id should be from 1 to 255 bytes long and MAY NOT start with binary zero\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -binary data -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -NULL -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_ROUTER, ZMQ_STREAM -T} -.TE -.sp 1 -.SS "ZMQ_CONFLATE: Keep only last message" -.sp -If set, a socket shall keep only one message in its inbound/outbound queue, this message being the last message received/the last message to be sent\&. Ignores \fIZMQ_RCVHWM\fR and \fIZMQ_SNDHWM\fR options\&. Does not support multi\-part messages, in particular, only one part of it is kept in the socket internal queue\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -boolean -T} -T{ -.sp -Default value -T}:T{ -.sp -0 (false) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_PULL, ZMQ_PUSH, ZMQ_SUB, ZMQ_PUB, ZMQ_DEALER -T} -.TE -.sp 1 -.SS "ZMQ_CONNECT_TIMEOUT: Set connect() timeout" -.sp -Sets how long to wait before timing\-out a connect() system call\&. The connect() system call normally takes a long time before it returns a time out error\&. Setting this option allows the library to time out the call at an earlier interval\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -0 (disabled) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_CURVE_PUBLICKEY: Set CURVE public key" -.sp -Sets the socket\(cqs long term public key\&. You must set this on CURVE client sockets, see \fBzmq_curve\fR(7)\&. You can provide the key as 32 binary bytes, or as a 40\-character string encoded in the Z85 encoding format and terminated in a null byte\&. The public key must always be used with the matching secret key\&. To generate a public/secret key pair, use \fBzmq_curve_keypair\fR(3)\&. To derive the public key from a secret key, use \fBzmq_curve_public\fR(3)\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -an option value size of 40 is supported for backwards compatibility, though is deprecated\&. -.sp .5v -.RE -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -binary data or Z85 text string -T} -T{ -.sp -Option value size -T}:T{ -.sp -32 or 41 -T} -T{ -.sp -Default value -T}:T{ -.sp -NULL -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transport -T} -.TE -.sp 1 -.SS "ZMQ_CURVE_SECRETKEY: Set CURVE secret key" -.sp -Sets the socket\(cqs long term secret key\&. You must set this on both CURVE client and server sockets, see \fBzmq_curve\fR(7)\&. You can provide the key as 32 binary bytes, or as a 40\-character string encoded in the Z85 encoding format and terminated in a null byte\&. To generate a public/secret key pair, use \fBzmq_curve_keypair\fR(3)\&. To derive the public key from a secret key, use \fBzmq_curve_public\fR(3)\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -an option value size of 40 is supported for backwards compatibility, though is deprecated\&. -.sp .5v -.RE -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -binary data or Z85 text string -T} -T{ -.sp -Option value size -T}:T{ -.sp -32 or 41 -T} -T{ -.sp -Default value -T}:T{ -.sp -NULL -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transport -T} -.TE -.sp 1 -.SS "ZMQ_CURVE_SERVER: Set CURVE server role" -.sp -Defines whether the socket will act as server for CURVE security, see \fBzmq_curve\fR(7)\&. A value of \fI1\fR means the socket will act as CURVE server\&. A value of \fI0\fR means the socket will not act as CURVE server, and its security role then depends on other option settings\&. Setting this to \fI0\fR shall reset the socket security to NULL\&. When you set this you must also set the server\(cqs secret key using the ZMQ_CURVE_SECRETKEY option\&. A server socket does not need to know its own public key\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0, 1 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transport -T} -.TE -.sp 1 -.SS "ZMQ_CURVE_SERVERKEY: Set CURVE server key" -.sp -Sets the socket\(cqs long term server key\&. You must set this on CURVE client sockets, see \fBzmq_curve\fR(7)\&. You can provide the key as 32 binary bytes, or as a 40\-character string encoded in the Z85 encoding format and terminated in a null byte\&. This key must have been generated together with the server\(cqs secret key\&. To generate a public/secret key pair, use \fBzmq_curve_keypair\fR(3)\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -an option value size of 40 is supported for backwards compatibility, though is deprecated\&. -.sp .5v -.RE -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -binary data or Z85 text string -T} -T{ -.sp -Option value size -T}:T{ -.sp -32 or 41 -T} -T{ -.sp -Default value -T}:T{ -.sp -NULL -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transport -T} -.TE -.sp 1 -.SS "ZMQ_GSSAPI_PLAINTEXT: Disable GSSAPI encryption" -.sp -Defines whether communications on the socket will be encrypted, see \fBzmq_gssapi\fR(7)\&. A value of \fI1\fR means that communications will be plaintext\&. A value of \fI0\fR means communications will be encrypted\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0, 1 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 (false) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transport -T} -.TE -.sp 1 -.SS "ZMQ_GSSAPI_PRINCIPAL: Set name of GSSAPI principal" -.sp -Sets the name of the principal for whom GSSAPI credentials should be acquired\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -character string -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -not set -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transport -T} -.TE -.sp 1 -.SS "ZMQ_GSSAPI_SERVER: Set GSSAPI server role" -.sp -Defines whether the socket will act as server for GSSAPI security, see \fBzmq_gssapi\fR(7)\&. A value of \fI1\fR means the socket will act as GSSAPI server\&. A value of \fI0\fR means the socket will act as GSSAPI client\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0, 1 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 (false) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transport -T} -.TE -.sp 1 -.SS "ZMQ_GSSAPI_SERVICE_PRINCIPAL: Set name of GSSAPI service principal" -.sp -Sets the name of the principal of the GSSAPI server to which a GSSAPI client intends to connect\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -character string -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -not set -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transport -T} -.TE -.sp 1 -.SS "ZMQ_HANDSHAKE_IVL: Set maximum handshake interval" -.sp -The \fIZMQ_HANDSHAKE_IVL\fR option shall set the maximum handshake interval for the specified \fIsocket\fR\&. Handshaking is the exchange of socket configuration information (socket type, identity, security) that occurs when a connection is first opened, only for connection\-oriented transports\&. If handshaking does not complete within the configured time, the connection shall be closed\&. The value 0 means no handshake time limit\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -30000 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all but ZMQ_STREAM, only for connection\-oriented transports -T} -.TE -.sp 1 -.SS "ZMQ_HEARTBEAT_IVL: Set interval between sending ZMTP heartbeats" -.sp -The \fIZMQ_HEARTBEAT_IVL\fR option shall set the interval between sending ZMTP heartbeats for the specified \fIsocket\fR\&. If this option is set and is greater than 0, then a \fIPING\fR ZMTP command will be sent every \fIZMQ_HEARTBEAT_IVL\fR milliseconds\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using connection\-oriented transports -T} -.TE -.sp 1 -.SS "ZMQ_HEARTBEAT_TIMEOUT: Set timeout for ZMTP heartbeats" -.sp -The \fIZMQ_HEARTBEAT_TIMEOUT\fR option shall set how long to wait before timing\-out a connection after sending a \fIPING\fR ZMTP command and not receiving any traffic\&. This option is only valid if \fIZMQ_HEARTBEAT_IVL\fR is also set, and is greater than 0\&. The connection will time out if there is no traffic received after sending the \fIPING\fR command, but the received traffic does not have to be a \fIPONG\fR command \- any received traffic will cancel the timeout\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using connection\-oriented transports -T} -.TE -.sp 1 -.SS "ZMQ_HEARTBEAT_TTL: Set the TTL value for ZMTP heartbeats" -.sp -The \fIZMQ_HEARTBEAT_TTL\fR option shall set the timeout on the remote peer for ZMTP heartbeats\&. If this option is greater than 0, the remote side shall time out the connection if it does not receive any more traffic within the TTL period\&. This option does not have any effect if \fIZMQ_HEARTBEAT_IVL\fR is not set or is 0\&. Internally, this value is rounded down to the nearest decisecond, any value less than 100 will have no effect\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using connection\-oriented transports -T} -.TE -.sp 1 -.SS "ZMQ_IDENTITY: Set socket identity" -.sp -The \fIZMQ_IDENTITY\fR option shall set the identity of the specified \fIsocket\fR when connecting to a ROUTER socket\&. The identity should be from 1 to 255 bytes long and may contain any values\&. -.sp -If two clients use the same identity when connecting to a ROUTER, the results shall depend on the ZMQ_ROUTER_HANDOVER option setting\&. If that is not set (or set to the default of zero), the ROUTER socket shall reject clients trying to connect with an already\-used identity\&. If that option is set to 1, the ROUTER socket shall hand\-over the connection to the new client and disconnect the existing one\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -binary data -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -NULL -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_REQ, ZMQ_REP, ZMQ_ROUTER, ZMQ_DEALER\&. -T} -.TE -.sp 1 -.SS "ZMQ_IMMEDIATE: Queue messages only to completed connections" -.sp -By default queues will fill on outgoing connections even if the connection has not completed\&. This can lead to "lost" messages on sockets with round\-robin routing (REQ, PUSH, DEALER)\&. If this option is set to 1, messages shall be queued only to completed connections\&. This will cause the socket to block if there are no other connections, but will prevent queues from filling on pipes awaiting connection\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -boolean -T} -T{ -.sp -Default value -T}:T{ -.sp -0 (false) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, only for connection\-oriented transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_INVERT_MATCHING: Invert message filtering" -.sp -Reverses the filtering behavior of PUB\-SUB sockets, when set to 1\&. -.sp -On \fIPUB\fR and \fIXPUB\fR sockets, this causes messages to be sent to all connected sockets \fIexcept\fR those subscribed to a prefix that matches the message\&. On \fISUB\fR sockets, this causes only incoming messages that do \fInot\fR match any of the socket\(cqs subscriptions to be received by the user\&. -.sp -Whenever \fIZMQ_INVERT_MATCHING\fR is set to 1 on a \fIPUB\fR socket, all \fISUB\fR sockets connecting to it must also have the option set to 1\&. Failure to do so will have the \fISUB\fR sockets reject everything the \fIPUB\fR socket sends them\&. \fIXSUB\fR sockets do not need to do this because they do not filter incoming messages\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0,1 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_PUB, ZMQ_XPUB, ZMQ_SUB -T} -.TE -.sp 1 -.SS "ZMQ_IPV6: Enable IPv6 on socket" -.sp -Set the IPv6 option for the socket\&. A value of 1 means IPv6 is enabled on the socket, while 0 means the socket will use only IPv4\&. When IPv6 is enabled the socket will connect to, or accept connections from, both IPv4 and IPv6 hosts\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -boolean -T} -T{ -.sp -Default value -T}:T{ -.sp -0 (false) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_LINGER: Set linger period for socket shutdown" -.sp -The \fIZMQ_LINGER\fR option shall set the linger period for the specified \fIsocket\fR\&. The linger period determines how long pending messages which have yet to be sent to a peer shall linger in memory after a socket is disconnected with \fBzmq_disconnect\fR(3) or closed with \fBzmq_close\fR(3), and further affects the termination of the socket\(cqs context with \fBzmq_ctx_term\fR(3)\&. The following outlines the different behaviours: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -A value of -\fI\-1\fR -specifies an infinite linger period\&. Pending messages shall not be discarded after a call to -\fIzmq_disconnect()\fR -or -\fIzmq_close()\fR; attempting to terminate the socket\(cqs context with -\fIzmq_ctx_term()\fR -shall block until all pending messages have been sent to a peer\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -The value of -\fI0\fR -specifies no linger period\&. Pending messages shall be discarded immediately after a call to -\fIzmq_disconnect()\fR -or -\fIzmq_close()\fR\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Positive values specify an upper bound for the linger period in milliseconds\&. Pending messages shall not be discarded after a call to -\fIzmq_disconnect()\fR -or -\fIzmq_close()\fR; attempting to terminate the socket\(cqs context with -\fIzmq_ctx_term()\fR -shall block until either all pending messages have been sent to a peer, or the linger period expires, after which any pending messages shall be discarded\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -Option value type -T}:T{ -int -T} -T{ -Option value unit -T}:T{ -milliseconds -T} -T{ -Default value -T}:T{ -30000 (thirty seconds) -T} -T{ -Applicable socket types -T}:T{ -all -T} -.TE -.sp 1 -.RE -.SS "ZMQ_MAXMSGSIZE: Maximum acceptable inbound message size" -.sp -Limits the size of the inbound message\&. If a peer sends a message larger than ZMQ_MAXMSGSIZE it is disconnected\&. Value of \-1 means \fIno limit\fR\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int64_t -T} -T{ -.sp -Option value unit -T}:T{ -.sp -bytes -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all -T} -.TE -.sp 1 -.SS "ZMQ_MULTICAST_HOPS: Maximum network hops for multicast packets" -.sp -Sets the time\-to\-live field in every multicast packet sent from this socket\&. The default is 1 which means that the multicast packets don\(cqt leave the local network\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -network hops -T} -T{ -.sp -Default value -T}:T{ -.sp -1 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using multicast transports -T} -.TE -.sp 1 -.SS "ZMQ_MULTICAST_MAXTPDU: Maximum transport data unit size for multicast packets" -.sp -Sets the maximum transport data unit size used for outbound multicast packets\&. -.sp -This must be set at or below the minimum Maximum Transmission Unit (MTU) for all network paths over which multicast reception is required\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -bytes -T} -T{ -.sp -Default value -T}:T{ -.sp -1500 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using multicast transports -T} -.TE -.sp 1 -.SS "ZMQ_PLAIN_PASSWORD: Set PLAIN security password" -.sp -Sets the password for outgoing connections over TCP or IPC\&. If you set this to a non\-null value, the security mechanism used for connections shall be PLAIN, see \fBzmq_plain\fR(7)\&. If you set this to a null value, the security mechanism used for connections shall be NULL, see \fBzmq_null\fR(3)\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -character string -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -not set -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transport -T} -.TE -.sp 1 -.SS "ZMQ_PLAIN_SERVER: Set PLAIN server role" -.sp -Defines whether the socket will act as server for PLAIN security, see \fBzmq_plain\fR(7)\&. A value of \fI1\fR means the socket will act as PLAIN server\&. A value of \fI0\fR means the socket will not act as PLAIN server, and its security role then depends on other option settings\&. Setting this to \fI0\fR shall reset the socket security to NULL\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0, 1 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transport -T} -.TE -.sp 1 -.SS "ZMQ_PLAIN_USERNAME: Set PLAIN security username" -.sp -Sets the username for outgoing connections over TCP or IPC\&. If you set this to a non\-null value, the security mechanism used for connections shall be PLAIN, see \fBzmq_plain\fR(7)\&. If you set this to a null value, the security mechanism used for connections shall be NULL, see \fBzmq_null\fR(3)\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -character string -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -not set -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transport -T} -.TE -.sp 1 -.SS "ZMQ_USE_FD: Set the pre\-allocated socket file descriptor" -.sp -When set to a positive integer value before zmq_bind is called on the socket, the socket shall use the corresponding file descriptor for connections over TCP or IPC instead of allocating a new file descriptor\&. Useful for writing systemd socket activated services\&. If set to \-1 (default), a new file descriptor will be allocated instead (default behaviour)\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -if set after calling zmq_bind, this option shall have no effect\&. NOTE: the file descriptor passed through MUST have been ran through the "bind" and "listen" system calls beforehand\&. Also, socket option that would normally be passed through zmq_setsockopt like TCP buffers length, IP_TOS or SO_REUSEADDR MUST be set beforehand by the caller, as they must be set before the socket is bound\&. -.sp .5v -.RE -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -file descriptor -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all bound sockets, when using IPC or TCP transport -T} -.TE -.sp 1 -.SS "ZMQ_PROBE_ROUTER: bootstrap connections to ROUTER sockets" -.sp -When set to 1, the socket will automatically send an empty message when a new connection is made or accepted\&. You may set this on REQ, DEALER, or ROUTER sockets connected to a ROUTER socket\&. The application must filter such empty messages\&. The ZMQ_PROBE_ROUTER option in effect provides the ROUTER application with an event signaling the arrival of a new peer\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -do not set this option on a socket that talks to any other socket types: the results are undefined\&. -.sp .5v -.RE -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0, 1 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_ROUTER, ZMQ_DEALER, ZMQ_REQ -T} -.TE -.sp 1 -.SS "ZMQ_RATE: Set multicast data rate" -.sp -The \fIZMQ_RATE\fR option shall set the maximum send or receive data rate for multicast transports such as \fBzmq_pgm\fR(7) using the specified \fIsocket\fR\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -kilobits per second -T} -T{ -.sp -Default value -T}:T{ -.sp -100 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using multicast transports -T} -.TE -.sp 1 -.SS "ZMQ_RCVBUF: Set kernel receive buffer size" -.sp -The \fIZMQ_RCVBUF\fR option shall set the underlying kernel receive buffer size for the \fIsocket\fR to the specified size in bytes\&. A value of \-1 means leave the OS default unchanged\&. For details refer to your operating system documentation for the \fISO_RCVBUF\fR socket option\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -bytes -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all -T} -.TE -.sp 1 -.SS "ZMQ_RCVHWM: Set high water mark for inbound messages" -.sp -The \fIZMQ_RCVHWM\fR option shall set the high water mark for inbound messages on the specified \fIsocket\fR\&. The high water mark is a hard limit on the maximum number of outstanding messages 0MQ shall queue in memory for any single peer that the specified \fIsocket\fR is communicating with\&. A value of zero means no limit\&. -.sp -If this limit has been reached the socket shall enter an exceptional state and depending on the socket type, 0MQ shall take appropriate action such as blocking or dropping sent messages\&. Refer to the individual socket descriptions in \fBzmq_socket\fR(3) for details on the exact action taken for each socket type\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -messages -T} -T{ -.sp -Default value -T}:T{ -.sp -1000 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all -T} -.TE -.sp 1 -.SS "ZMQ_RCVTIMEO: Maximum time before a recv operation returns with EAGAIN" -.sp -Sets the timeout for receive operation on the socket\&. If the value is 0, \fIzmq_recv(3)\fR will return immediately, with a EAGAIN error if there is no message to receive\&. If the value is \-1, it will block until a message is available\&. For all other values, it will wait for a message for that amount of time before returning with an EAGAIN error\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 (infinite) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all -T} -.TE -.sp 1 -.SS "ZMQ_RECONNECT_IVL: Set reconnection interval" -.sp -The \fIZMQ_RECONNECT_IVL\fR option shall set the initial reconnection interval for the specified \fIsocket\fR\&. The reconnection interval is the period 0MQ shall wait between attempts to reconnect disconnected peers when using connection\-oriented transports\&. The value \-1 means no reconnection\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -The reconnection interval may be randomized by 0MQ to prevent reconnection storms in topologies with a large number of peers per socket\&. -.sp .5v -.RE -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -100 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, only for connection\-oriented transports -T} -.TE -.sp 1 -.SS "ZMQ_RECONNECT_IVL_MAX: Set maximum reconnection interval" -.sp -The \fIZMQ_RECONNECT_IVL_MAX\fR option shall set the maximum reconnection interval for the specified \fIsocket\fR\&. This is the maximum period 0MQ shall wait between attempts to reconnect\&. On each reconnect attempt, the previous interval shall be doubled untill ZMQ_RECONNECT_IVL_MAX is reached\&. This allows for exponential backoff strategy\&. Default value means no exponential backoff is performed and reconnect interval calculations are only based on ZMQ_RECONNECT_IVL\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -Values less than ZMQ_RECONNECT_IVL will be ignored\&. -.sp .5v -.RE -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -0 (only use ZMQ_RECONNECT_IVL) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, only for connection\-oriented transports -T} -.TE -.sp 1 -.SS "ZMQ_RECOVERY_IVL: Set multicast recovery interval" -.sp -The \fIZMQ_RECOVERY_IVL\fR option shall set the recovery interval for multicast transports using the specified \fIsocket\fR\&. The recovery interval determines the maximum time in milliseconds that a receiver can be absent from a multicast group before unrecoverable data loss will occur\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBCaution\fR -.ps -1 -.br -.sp -Exercise care when setting large recovery intervals as the data needed for recovery will be held in memory\&. For example, a 1 minute recovery interval at a data rate of 1Gbps requires a 7GB in\-memory buffer\&. -.sp .5v -.RE -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -10000 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using multicast transports -T} -.TE -.sp 1 -.SS "ZMQ_REQ_CORRELATE: match replies with requests" -.sp -The default behaviour of REQ sockets is to rely on the ordering of messages to match requests and responses and that is usually sufficient\&. When this option is set to 1, the REQ socket will prefix outgoing messages with an extra frame containing a request id\&. That means the full message is (request id, 0, user frames\&...)\&. The REQ socket will discard all incoming messages that don\(cqt begin with these two frames\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0, 1 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_REQ -T} -.TE -.sp 1 -.SS "ZMQ_REQ_RELAXED: relax strict alternation between request and reply" -.sp -By default, a REQ socket does not allow initiating a new request with \fIzmq_send(3)\fR until the reply to the previous one has been received\&. When set to 1, sending another message is allowed and previous replies will be discarded if any\&. The request\-reply state machine is reset and a new request is sent to the next available peer\&. -.sp -If set to 1, also enable ZMQ_REQ_CORRELATE to ensure correct matching of requests and replies\&. Otherwise a late reply to an aborted request can be reported as the reply to the superseding request\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0, 1 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_REQ -T} -.TE -.sp 1 -.SS "ZMQ_ROUTER_HANDOVER: handle duplicate client identities on ROUTER sockets" -.sp -If two clients use the same identity when connecting to a ROUTER, the results shall depend on the ZMQ_ROUTER_HANDOVER option setting\&. If that is not set (or set to the default of zero), the ROUTER socket shall reject clients trying to connect with an already\-used identity\&. If that option is set to 1, the ROUTER socket shall hand\-over the connection to the new client and disconnect the existing one\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0, 1 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_ROUTER -T} -.TE -.sp 1 -.SS "ZMQ_ROUTER_MANDATORY: accept only routable messages on ROUTER sockets" -.sp -Sets the ROUTER socket behaviour when an unroutable message is encountered\&. A value of 0 is the default and discards the message silently when it cannot be routed or the peers SNDHWM is reached\&. A value of 1 returns an \fIEHOSTUNREACH\fR error code if the message cannot be routed or \fIEAGAIN\fR error code if the SNDHWM is reached and ZMQ_DONTWAIT was used\&. Without ZMQ_DONTWAIT it will block until the SNDTIMEO is reached or a spot in the send queue opens up\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0, 1 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_ROUTER -T} -.TE -.sp 1 -.SS "ZMQ_ROUTER_RAW: switch ROUTER socket to raw mode" -.sp -Sets the raw mode on the ROUTER, when set to 1\&. When the ROUTER socket is in raw mode, and when using the tcp:// transport, it will read and write TCP data without 0MQ framing\&. This lets 0MQ applications talk to non\-0MQ applications\&. When using raw mode, you cannot set explicit identities, and the ZMQ_SNDMORE flag is ignored when sending data messages\&. In raw mode you can close a specific connection by sending it a zero\-length message (following the identity frame)\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -This option is deprecated, please use ZMQ_STREAM sockets instead\&. -.sp .5v -.RE -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0, 1 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_ROUTER -T} -.TE -.sp 1 -.SS "ZMQ_SNDBUF: Set kernel transmit buffer size" -.sp -The \fIZMQ_SNDBUF\fR option shall set the underlying kernel transmit buffer size for the \fIsocket\fR to the specified size in bytes\&. A value of \-1 means leave the OS default unchanged\&. For details please refer to your operating system documentation for the \fISO_SNDBUF\fR socket option\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -bytes -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all -T} -.TE -.sp 1 -.SS "ZMQ_SNDHWM: Set high water mark for outbound messages" -.sp -The \fIZMQ_SNDHWM\fR option shall set the high water mark for outbound messages on the specified \fIsocket\fR\&. The high water mark is a hard limit on the maximum number of outstanding messages 0MQ shall queue in memory for any single peer that the specified \fIsocket\fR is communicating with\&. A value of zero means no limit\&. -.sp -If this limit has been reached the socket shall enter an exceptional state and depending on the socket type, 0MQ shall take appropriate action such as blocking or dropping sent messages\&. Refer to the individual socket descriptions in \fBzmq_socket\fR(3) for details on the exact action taken for each socket type\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -0MQ does not guarantee that the socket will accept as many as ZMQ_SNDHWM messages, and the actual limit may be as much as 60\-70% lower depending on the flow of messages on the socket\&. -.sp .5v -.RE -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -messages -T} -T{ -.sp -Default value -T}:T{ -.sp -1000 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all -T} -.TE -.sp 1 -.SS "ZMQ_SNDTIMEO: Maximum time before a send operation returns with EAGAIN" -.sp -Sets the timeout for send operation on the socket\&. If the value is 0, \fIzmq_send(3)\fR will return immediately, with a EAGAIN error if the message cannot be sent\&. If the value is \-1, it will block until the message is sent\&. For all other values, it will try to send the message for that amount of time before returning with an EAGAIN error\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 (infinite) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all -T} -.TE -.sp 1 -.SS "ZMQ_SOCKS_PROXY: Set SOCKS5 proxy address" -.sp -Sets the SOCKS5 proxy address that shall be used by the socket for the TCP connection(s)\&. Does not support SOCKS5 authentication\&. If the endpoints are domain names instead of addresses they shall not be resolved and they shall be forwarded unchanged to the SOCKS proxy service in the client connection request message (address type 0x03 domain name)\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -character string -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -not set -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transport -T} -.TE -.sp 1 -.SS "ZMQ_STREAM_NOTIFY: send connect and disconnect notifications" -.sp -Enables connect and disconnect notifications on a STREAM socket, when set to 1\&. When notifications are enabled, the socket delivers a zero\-length message when a peer connects or disconnects\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0, 1 -T} -T{ -.sp -Default value -T}:T{ -.sp -1 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_STREAM -T} -.TE -.sp 1 -.SS "ZMQ_SUBSCRIBE: Establish message filter" -.sp -The \fIZMQ_SUBSCRIBE\fR option shall establish a new message filter on a \fIZMQ_SUB\fR socket\&. Newly created \fIZMQ_SUB\fR sockets shall filter out all incoming messages, therefore you should call this option to establish an initial message filter\&. -.sp -An empty \fIoption_value\fR of length zero shall subscribe to all incoming messages\&. A non\-empty \fIoption_value\fR shall subscribe to all messages beginning with the specified prefix\&. Multiple filters may be attached to a single \fIZMQ_SUB\fR socket, in which case a message shall be accepted if it matches at least one filter\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -binary data -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -N/A -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_SUB -T} -.TE -.sp 1 -.SS "ZMQ_TCP_KEEPALIVE: Override SO_KEEPALIVE socket option" -.sp -Override \fISO_KEEPALIVE\fR socket option (where supported by OS)\&. The default value of \-1 means to skip any overrides and leave it to OS default\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -\-1,0,1 -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 (leave to OS default) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_TCP_KEEPALIVE_CNT: Override TCP_KEEPCNT socket option" -.sp -Override \fITCP_KEEPCNT\fR socket option (where supported by OS)\&. The default value of \-1 means to skip any overrides and leave it to OS default\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -\-1,>0 -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 (leave to OS default) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_TCP_KEEPALIVE_IDLE: Override TCP_KEEPIDLE (or TCP_KEEPALIVE on some OS)" -.sp -Override \fITCP_KEEPIDLE\fR (or \fITCP_KEEPALIVE\fR on some OS) socket option (where supported by OS)\&. The default value of \-1 means to skip any overrides and leave it to OS default\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -\-1,>0 -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 (leave to OS default) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_TCP_KEEPALIVE_INTVL: Override TCP_KEEPINTVL socket option" -.sp -Override \fITCP_KEEPINTVL\fR socket option(where supported by OS)\&. The default value of \-1 means to skip any overrides and leave it to OS default\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -\-1,>0 -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 (leave to OS default) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_TCP_MAXRT: Set TCP Maximum Retransmit Timeout" -.sp -On OSes where it is supported, sets how long before an unacknowledged TCP retransmit times out\&. The system normally attempts many TCP retransmits following an exponential backoff strategy\&. This means that after a network outage, it may take a long time before the session can be re\-established\&. Setting this option allows the timeout to happen at a shorter interval\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -0 (leave to OS default) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_TOS: Set the Type\-of\-Service on socket" -.sp -Sets the ToS fields (Differentiated services (DS) and Explicit Congestion Notification (ECN) field of the IP header\&. The ToS field is typically used to specify a packets priority\&. The availability of this option is dependent on intermediate network equipment that inspect the ToS field and provide a path for low\-delay, high\-throughput, highly\-reliable service, etc\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp ->0 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, only for connection\-oriented transports -T} -.TE -.sp 1 -.SS "ZMQ_UNSUBSCRIBE: Remove message filter" -.sp -The \fIZMQ_UNSUBSCRIBE\fR option shall remove an existing message filter on a \fIZMQ_SUB\fR socket\&. The filter specified must match an existing filter previously established with the \fIZMQ_SUBSCRIBE\fR option\&. If the socket has several instances of the same filter attached the \fIZMQ_UNSUBSCRIBE\fR option shall remove only one instance, leaving the rest in place and functional\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -binary data -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -N/A -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_SUB -T} -.TE -.sp 1 -.SS "ZMQ_XPUB_VERBOSE: pass subscribe messages on XPUB socket" -.sp -Sets the \fIXPUB\fR socket behaviour on new subscriptions\&. If enabled, the socket passes all subscribe messages to the caller\&. If disabled, these are not visible to the caller\&. The default is 0 (disabled)\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0, 1 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_XPUB -T} -.TE -.sp 1 -.SS "ZMQ_XPUB_VERBOSER: pass subscribe and unsubscribe messages on XPUB socket" -.sp -Sets the \fIXPUB\fR socket behaviour on new subscriptions and ubsubscriptions\&. If enabled, the socket passes all subscribe and unsubscribe messages to the caller\&. If disabled, these are not visible to the caller\&. The default is 0 (disabled)\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0, 1 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_XPUB -T} -.TE -.sp 1 -.SS "ZMQ_XPUB_MANUAL: change the subscription handling to manual" -.sp -Sets the \fIXPUB\fR socket subscription handling mode manual/automatic\&. A value of \fI0\fR is the default and subscription requests will be handled automatically\&. A value of \fI1\fR will change the subscription requests handling to manual, with manual mode subscription requests are not added to the subscription list\&. To add subscription the user need to call setsockopt with ZMQ_SUBSCRIBE on XPUB socket\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0, 1 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_XPUB -T} -.TE -.sp 1 -.SS "ZMQ_XPUB_NODROP: do not silently drop messages if SENDHWM is reached" -.sp -Sets the \fIXPUB\fR socket behaviour to return error EAGAIN if SENDHWM is reached and the message could not be send\&. -.sp -A value of 0 is the default and drops the message silently when the peers SNDHWM is reached\&. A value of 1 returns an \fIEAGAIN\fR error code if the SNDHWM is reached and ZMQ_DONTWAIT was used\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -0, 1 -T} -T{ -.sp -Default value -T}:T{ -.sp -0 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_XPUB, ZMQ_PUB -T} -.TE -.sp 1 -.SS "ZMQ_XPUB_WELCOME_MSG: set welcome message that will be received by subscriber when connecting" -.sp -Sets a welcome message the will be recieved by subscriber when connecting\&. Subscriber must subscribe to the Welcome message before connecting\&. Welcome message will also be sent on reconnecting\&. For welcome message to work well user must poll on incoming subscription messages on the XPUB socket and handle them\&. -.sp -Use NULL and lenght of zero to disable welcome message\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -binary data -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -NULL -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -ZMQ_XPUB -T} -.TE -.sp 1 -.SS "ZMQ_ZAP_DOMAIN: Set RFC 27 authentication domain" -.sp -Sets the domain for ZAP (ZMQ RFC 27) authentication\&. For NULL security (the default on all tcp:// connections), ZAP authentication only happens if you set a non\-empty domain\&. For PLAIN and CURVE security, ZAP requests are always made, if there is a ZAP handler present\&. See \m[blue]\fBhttp://rfc\&.zeromq\&.org/spec:27\fR\m[] for more details\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -character string -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -not set -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transport -T} -.TE -.sp 1 -.SS "ZMQ_TCP_ACCEPT_FILTER: Assign filters to allow new TCP connections" -.sp -Assign an arbitrary number of filters that will be applied for each new TCP transport connection on a listening socket\&. If no filters are applied, then the TCP transport allows connections from any IP address\&. If at least one filter is applied then new connection source ip should be matched\&. To clear all filters call zmq_setsockopt(socket, ZMQ_TCP_ACCEPT_FILTER, NULL, 0)\&. Filter is a null\-terminated string with ipv6 or ipv4 CIDR\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -This option is deprecated, please use authentication via the ZAP API and IP address whitelisting / blacklisting\&. -.sp .5v -.RE -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -binary data -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -no filters (allow from all) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all listening sockets, when using TCP transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_IPC_FILTER_GID: Assign group ID filters to allow new IPC connections" -.sp -Assign an arbitrary number of filters that will be applied for each new IPC transport connection on a listening socket\&. If no IPC filters are applied, then the IPC transport allows connections from any process\&. If at least one UID, GID, or PID filter is applied then new connection credentials should be matched\&. To clear all GID filters call zmq_setsockopt(socket, ZMQ_IPC_FILTER_GID, NULL, 0)\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -GID filters are only available on platforms supporting SO_PEERCRED or LOCAL_PEERCRED socket options (currently only Linux and later versions of OS X)\&. -.sp .5v -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -This option is deprecated, please use authentication via the ZAP API and IPC whitelisting / blacklisting\&. -.sp .5v -.RE -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -gid_t -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -no filters (allow from all) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all listening sockets, when using IPC transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_IPC_FILTER_PID: Assign process ID filters to allow new IPC connections" -.sp -Assign an arbitrary number of filters that will be applied for each new IPC transport connection on a listening socket\&. If no IPC filters are applied, then the IPC transport allows connections from any process\&. If at least one UID, GID, or PID filter is applied then new connection credentials should be matched\&. To clear all PID filters call zmq_setsockopt(socket, ZMQ_IPC_FILTER_PID, NULL, 0)\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -PID filters are only available on platforms supporting the SO_PEERCRED socket option (currently only Linux)\&. -.sp .5v -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -This option is deprecated, please use authentication via the ZAP API and IPC whitelisting / blacklisting\&. -.sp .5v -.RE -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -pid_t -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -no filters (allow from all) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all listening sockets, when using IPC transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_IPC_FILTER_UID: Assign user ID filters to allow new IPC connections" -.sp -Assign an arbitrary number of filters that will be applied for each new IPC transport connection on a listening socket\&. If no IPC filters are applied, then the IPC transport allows connections from any process\&. If at least one UID, GID, or PID filter is applied then new connection credentials should be matched\&. To clear all UID filters call zmq_setsockopt(socket, ZMQ_IPC_FILTER_UID, NULL, 0)\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -UID filters are only available on platforms supporting SO_PEERCRED or LOCAL_PEERCRED socket options (currently only Linux and later versions of OS X)\&. -.sp .5v -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -This option is deprecated, please use authentication via the ZAP API and IPC whitelisting / blacklisting\&. -.sp .5v -.RE -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -uid_t -T} -T{ -.sp -Option value unit -T}:T{ -.sp -N/A -T} -T{ -.sp -Default value -T}:T{ -.sp -no filters (allow from all) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all listening sockets, when using IPC transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_IPV4ONLY: Use IPv4\-only on socket" -.sp -Set the IPv4\-only option for the socket\&. This option is deprecated\&. Please use the ZMQ_IPV6 option\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -boolean -T} -T{ -.sp -Default value -T}:T{ -.sp -1 (true) -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using TCP transports\&. -T} -.TE -.sp 1 -.SS "ZMQ_VMCI_BUFFER_SIZE: Set buffer size of the VMCI socket" -.sp -The ZMQ_VMCI_BUFFER_SIZE option shall set the size of the underlying buffer for the socket\&. Used during negotiation before the connection is established\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -uint64_t -T} -T{ -.sp -Option value unit -T}:T{ -.sp -bytes -T} -T{ -.sp -Default value -T}:T{ -.sp -65546 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using VMCI transport -T} -.TE -.sp 1 -.SS "ZMQ_VMCI_BUFFER_MIN_SIZE: Set min buffer size of the VMCI socket" -.sp -The ZMQ_VMCI_BUFFER_MIN_SIZE option shall set the min size of the underlying buffer for the socket\&. Used during negotiation before the connection is established\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -uint64_t -T} -T{ -.sp -Option value unit -T}:T{ -.sp -bytes -T} -T{ -.sp -Default value -T}:T{ -.sp -128 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using VMCI transport -T} -.TE -.sp 1 -.SS "ZMQ_VMCI_BUFFER_MAX_SIZE: Set max buffer size of the VMCI socket" -.sp -The ZMQ_VMCI_BUFFER_MAX_SIZE option shall set the max size of the underlying buffer for the socket\&. Used during negotiation before the connection is established\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -uint64_t -T} -T{ -.sp -Option value unit -T}:T{ -.sp -bytes -T} -T{ -.sp -Default value -T}:T{ -.sp -262144 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using VMCI transport -T} -.TE -.sp 1 -.SS "ZMQ_VMCI_CONNECT_TIMEOUT: Set connection timeout of the VMCI socket" -.sp -The ZMQ_VMCI_CONNECT_TIMEOUT option shall set connection timeout for the socket\&. -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Option value type -T}:T{ -.sp -int -T} -T{ -.sp -Option value unit -T}:T{ -.sp -milliseconds -T} -T{ -.sp -Default value -T}:T{ -.sp -\-1 -T} -T{ -.sp -Applicable socket types -T}:T{ -.sp -all, when using VMCI transport -T} -.TE -.sp 1 -.SH "RETURN VALUE" -.sp -The \fIzmq_setsockopt()\fR function shall return zero if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEINVAL\fR -.RS 4 -The requested option -\fIoption_name\fR -is unknown, or the requested -\fIoption_len\fR -or -\fIoption_value\fR -is invalid\&. -.RE -.PP -\fBETERM\fR -.RS 4 -The 0MQ -\fIcontext\fR -associated with the specified -\fIsocket\fR -was terminated\&. -.RE -.PP -\fBENOTSOCK\fR -.RS 4 -The provided -\fIsocket\fR -was invalid\&. -.RE -.PP -\fBEINTR\fR -.RS 4 -The operation was interrupted by delivery of a signal\&. -.RE -.SH "EXAMPLE" -.PP -\fBSubscribing to messages on a ZMQ_SUB socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -/* Subscribe to all messages */ -rc = zmq_setsockopt (socket, ZMQ_SUBSCRIBE, "", 0); -assert (rc == 0); -/* Subscribe to messages prefixed with "ANIMALS\&.CATS" */ -rc = zmq_setsockopt (socket, ZMQ_SUBSCRIBE, "ANIMALS\&.CATS", 12); -.fi -.if n \{\ -.RE -.\} -.PP -\fBSetting I/O thread affinity\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -int64_t affinity; -/* Incoming connections on TCP port 5555 shall be handled by I/O thread 1 */ -affinity = 1; -rc = zmq_setsockopt (socket, ZMQ_AFFINITY, &affinity, sizeof (affinity)); -assert (rc); -rc = zmq_bind (socket, "tcp://lo:5555"); -assert (rc); -/* Incoming connections on TCP port 5556 shall be handled by I/O thread 2 */ -affinity = 2; -rc = zmq_setsockopt (socket, ZMQ_AFFINITY, &affinity, sizeof (affinity)); -assert (rc); -rc = zmq_bind (socket, "tcp://lo:5556"); -assert (rc); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_getsockopt\fR(3) \fBzmq_socket\fR(3) \fBzmq_plain\fR(7) \fBzmq_curve\fR(7) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_socket.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_socket.3 deleted file mode 100644 index eaf039a03f..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_socket.3 +++ /dev/null @@ -1,1403 +0,0 @@ -'\" t -.\" Title: zmq_socket -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_SOCKET" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_socket \- create 0MQ socket -.SH "SYNOPSIS" -.sp -\fBvoid *zmq_socket (void \fR\fB\fI*context\fR\fR\fB, int \fR\fB\fItype\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_socket()\fR function shall create a 0MQ socket within the specified \fIcontext\fR and return an opaque handle to the newly created socket\&. The \fItype\fR argument specifies the socket type, which determines the semantics of communication over the socket\&. -.sp -The newly created socket is initially unbound, and not associated with any endpoints\&. In order to establish a message flow a socket must first be connected to at least one endpoint with \fBzmq_connect\fR(3), or at least one endpoint must be created for accepting incoming connections with \fBzmq_bind\fR(3)\&. -.PP -\fBKey differences to conventional sockets\fR. Generally speaking, conventional sockets present a -\fIsynchronous\fR -interface to either connection\-oriented reliable byte streams (SOCK_STREAM), or connection\-less unreliable datagrams (SOCK_DGRAM)\&. In comparison, 0MQ sockets present an abstraction of an asynchronous -\fImessage queue\fR, with the exact queueing semantics depending on the socket type in use\&. Where conventional sockets transfer streams of bytes or discrete datagrams, 0MQ sockets transfer discrete -\fImessages\fR\&. -.sp -0MQ sockets being \fIasynchronous\fR means that the timings of the physical connection setup and tear down, reconnect and effective delivery are transparent to the user and organized by 0MQ itself\&. Further, messages may be \fIqueued\fR in the event that a peer is unavailable to receive them\&. -.sp -Conventional sockets allow only strict one\-to\-one (two peers), many\-to\-one (many clients, one server), or in some cases one\-to\-many (multicast) relationships\&. With the exception of \fIZMQ_PAIR\fR, 0MQ sockets may be connected \fBto multiple endpoints\fR using \fIzmq_connect()\fR, while simultaneously accepting incoming connections \fBfrom multiple endpoints\fR bound to the socket using \fIzmq_bind()\fR, thus allowing many\-to\-many relationships\&. -.PP -\fBThread safety\fR. 0MQ has both thread safe socket type and -\fInot\fR -thread safe socket types\&. Applications MUST NOT use a -\fInot\fR -thread safe socket from multiple threads except after migrating a socket from one thread to another with a "full fence" memory barrier\&. -.sp -Following are the thread safe sockets: * ZMQ_CLIENT * ZMQ_SERVER * ZMQ_DISH * ZMQ_RADIO * ZMQ_SCATTER * ZMQ_GATHER -.PP -\fBSocket types\fR. The following sections present the socket types defined by 0MQ, grouped by the general -\fImessaging pattern\fR -which is built from related socket types\&. -.SS "Client\-server pattern" -.sp -The client\-server pattern is used to allow a single \fIZMQ_SERVER\fR \fIserver\fR talk to one or more \fIZMQ_CLIENT\fR \fIclients\fR\&. The client always starts the conversation, after which either peer can send messages asynchronously, to the other\&. -.sp -The client\-server pattern is formally defined by \m[blue]\fBhttp://rfc\&.zeromq\&.org/spec:41\fR\m[]\&. -.sp -Note: this pattern is meant to eventually deprecate the use of \fIZMQ_DEALER\fR and \fIZMQ_ROUTER\fR to build client\-server architectures, as well as \fIZMQ_REP\fR and \fIZMQ_REQ\fR for request\-reply\&. -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBZMQ_CLIENT\fR -.RS 4 -.sp -A \fIZMQ_CLIENT\fR socket talks to a \fIZMQ_SERVER\fR socket\&. Either peer can connect, though the usual and recommended model is to bind the \fIZMQ_SERVER\fR and connect the \fIZMQ_CLIENT\fR\&. -.sp -If the \fIZMQ_CLIENT\fR socket has established a connection, \fBzmq_send\fR(3) will accept messages, queue them, and send them as rapidly as the network allows\&. The outgoing buffer limit is defined by the high water mark for the socket\&. If the outgoing buffer is full, or if there is no connected peer, \fBzmq_send\fR(3) will block, by default\&. The \fIZMQ_CLIENT\fR socket will not drop messages\&. -.sp -When a \fIZMQ_CLIENT\fR socket is connected to multiple \fIZMQ_SERVER\fR sockets, outgoing messages are distributed between connected peers on a round\-robin basis\&. Likewise, the \fIZMQ_CLIENT\fR socket receives messages fairly from each connected peer\&. This usage is sensible only for stateless protocols\&. -.sp -\fIZMQ_CLIENT\fR sockets are threadsafe and can be used from multiple threads at the same time\&. Note that replies from a \fIZMQ_SERVER\fR socket will go to the first client thread that calls libzmq:zmq_msg_recv\&. If you need to get replies back to the originating thread, use one \fIZMQ_CLIENT\fR socket per thread\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -\fIZMQ_CLIENT\fR sockets are threadsafe\&. They do not accept the ZMQ_SNDMORE option on sends not ZMQ_RCVMORE on receives\&. This limits them to single part data\&. The intention is to extend the API to allow scatter/gather of multi\-part data\&. -.sp .5v -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.B Table\ \&1.\ \&Summary of ZMQ_CLIENT characteristics -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Compatible peer sockets -T}:T{ -.sp -\fIZMQ_SERVER\fR -T} -T{ -.sp -Direction -T}:T{ -.sp -Bidirectional -T} -T{ -.sp -Send/receive pattern -T}:T{ -.sp -Unrestricted -T} -T{ -.sp -Outgoing routing strategy -T}:T{ -.sp -Round\-robin -T} -T{ -.sp -Incoming routing strategy -T}:T{ -.sp -Fair\-queued -T} -T{ -.sp -Action in mute state -T}:T{ -.sp -Block -T} -.TE -.sp 1 -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBZMQ_SERVER\fR -.RS 4 -.sp -A \fIZMQ_SERVER\fR socket talks to a set of \fIZMQ_CLIENT\fR sockets\&. A \fIZMQ_SERVER\fR socket can only reply to an incoming message: the \fIZMQ_CLIENT\fR peer must always initiate a conversation\&. -.sp -Each received message has a \fIrouting_id\fR that is a 32\-bit unsigned integer\&. The application can fetch this with \fBzmq_msg_routing_id\fR(3)\&. To send a message to a given \fIZMQ_CLIENT\fR peer the application must set the peer\(cqs \fIrouting_id\fR on the message, using \fBzmq_msg_set_routing_id\fR(3)\&. -.sp -If the \fIrouting_id\fR is not specified, or does not refer to a connected client peer, the send call will fail with EHOSTUNREACH\&. If the outgoing buffer for the client peer is full, the send call shall block, unless ZMQ_DONT_WAIT is used in the send, in which case it shall fail with EAGAIN\&. The \fIZMQ_SERVER\fR socket shall not drop messages in any case\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -\fIZMQ_SERVER\fR sockets are threadsafe\&. They do not accept the ZMQ_SNDMORE option on sends not ZMQ_RCVMORE on receives\&. This limits them to single part data\&. The intention is to extend the API to allow scatter/gather of multi\-part data\&. -.sp .5v -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.B Table\ \&2.\ \&Summary of ZMQ_SERVER characteristics -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Compatible peer sockets -T}:T{ -.sp -\fIZMQ_CLIENT\fR -T} -T{ -.sp -Direction -T}:T{ -.sp -Bidirectional -T} -T{ -.sp -Send/receive pattern -T}:T{ -.sp -Unrestricted -T} -T{ -.sp -Outgoing routing strategy -T}:T{ -.sp -See text -T} -T{ -.sp -Incoming routing strategy -T}:T{ -.sp -Fair\-queued -T} -T{ -.sp -Action in mute state -T}:T{ -.sp -Return EAGAIN -T} -.TE -.sp 1 -.RE -.SS "Radio\-dish pattern" -.sp -The radio\-dish pattern is used for one\-to\-many distribution of data from a single \fIpublisher\fR to multiple \fIsubscribers\fR in a fan out fashion\&. -.sp -Radio\-dish is using groups (vs Pub\-sub topics), Dish sockets can join a group and each message sent by Radio sockets belong to a group\&. -.sp -Groups are null terminated strings limited to 16 chars length (including null)\&. The intention is to increase the length to 40 chars (including null)\&. -.sp -Groups are matched using exact matching (vs prefix matching of PubSub)\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -Radio\-dish is still in draft phase\&. -.sp .5v -.RE -.sp -Note: this pattern is meant to eventually deprecate the use of \fIZMQ_PUB\fR and \fIZMQ_SUB\fR to build pub\-sub architectures\&. -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBZMQ_RADIO\fR -.RS 4 -.sp -A socket of type \fIZMQ_RADIO\fR is used by a \fIpublisher\fR to distribute data\&. Each message belong to a group, a group is specified with linkzmq_zmq_msg_set_group[3]\&. Messages are distributed to all members of a group\&. The \fBzmq_recv\fR(3) function is not implemented for this socket type\&. -.sp -When a \fIZMQ_RADIO\fR socket enters the \fImute\fR state due to having reached the high water mark for a \fIsubscriber\fR, then any messages that would be sent to the \fIsubscriber\fR in question shall instead be dropped until the mute state ends\&. The \fIzmq_send()\fR function shall never block for this socket type\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -\fIZMQ_RADIO\fR sockets are threadsafe\&. They do not accept the ZMQ_SNDMORE option on sends\&. This limits them to single part data\&. -.sp .5v -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.B Table\ \&3.\ \&Summary of ZMQ_RADIO characteristics -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Compatible peer sockets -T}:T{ -.sp -\fIZMQ_DISH\fR -T} -T{ -.sp -Direction -T}:T{ -.sp -Unidirectional -T} -T{ -.sp -Send/receive pattern -T}:T{ -.sp -Send only -T} -T{ -.sp -Incoming routing strategy -T}:T{ -.sp -N/A -T} -T{ -.sp -Outgoing routing strategy -T}:T{ -.sp -Fan out -T} -T{ -.sp -Action in mute state -T}:T{ -.sp -Drop -T} -.TE -.sp 1 -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBZMQ_DISH\fR -.RS 4 -.sp -A socket of type \fIZMQ_DISH\fR is used by a \fIsubscriber\fR to subscribe to groups distributed by a \fIradio\fR\&. Initially a \fIZMQ_DISH\fR socket is not subscribed to any groups, use \fBzmq_join\fR(3) to join a group\&. To get the group the message belong to call \fBzmq_msg_group\fR(3)\&. The \fIzmq_send()\fR function is not implemented for this socket type\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -\fIZMQ_DISH\fR sockets are threadsafe\&. They do not accept ZMQ_RCVMORE on receives\&. This limits them to single part data\&. -.sp .5v -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.B Table\ \&4.\ \&Summary of ZMQ_DISH characteristics -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Compatible peer sockets -T}:T{ -.sp -\fIZMQ_RADIO\fR -T} -T{ -.sp -Direction -T}:T{ -.sp -Unidirectional -T} -T{ -.sp -Send/receive pattern -T}:T{ -.sp -Receive only -T} -T{ -.sp -Incoming routing strategy -T}:T{ -.sp -Fair\-queued -T} -T{ -.sp -Outgoing routing strategy -T}:T{ -.sp -N/A -T} -.TE -.sp 1 -.RE -.SS "Publish\-subscribe pattern" -.sp -The publish\-subscribe pattern is used for one\-to\-many distribution of data from a single \fIpublisher\fR to multiple \fIsubscribers\fR in a fan out fashion\&. -.sp -The publish\-subscribe pattern is formally defined by \m[blue]\fBhttp://rfc\&.zeromq\&.org/spec:29\fR\m[]\&. -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBZMQ_PUB\fR -.RS 4 -.sp -A socket of type \fIZMQ_PUB\fR is used by a \fIpublisher\fR to distribute data\&. Messages sent are distributed in a fan out fashion to all connected peers\&. The \fBzmq_recv\fR(3) function is not implemented for this socket type\&. -.sp -When a \fIZMQ_PUB\fR socket enters the \fImute\fR state due to having reached the high water mark for a \fIsubscriber\fR, then any messages that would be sent to the \fIsubscriber\fR in question shall instead be dropped until the mute state ends\&. The \fIzmq_send()\fR function shall never block for this socket type\&. -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.B Table\ \&5.\ \&Summary of ZMQ_PUB characteristics -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Compatible peer sockets -T}:T{ -.sp -\fIZMQ_SUB\fR, \fIZMQ_XSUB\fR -T} -T{ -.sp -Direction -T}:T{ -.sp -Unidirectional -T} -T{ -.sp -Send/receive pattern -T}:T{ -.sp -Send only -T} -T{ -.sp -Incoming routing strategy -T}:T{ -.sp -N/A -T} -T{ -.sp -Outgoing routing strategy -T}:T{ -.sp -Fan out -T} -T{ -.sp -Action in mute state -T}:T{ -.sp -Drop -T} -.TE -.sp 1 -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBZMQ_SUB\fR -.RS 4 -.sp -A socket of type \fIZMQ_SUB\fR is used by a \fIsubscriber\fR to subscribe to data distributed by a \fIpublisher\fR\&. Initially a \fIZMQ_SUB\fR socket is not subscribed to any messages, use the \fIZMQ_SUBSCRIBE\fR option of \fBzmq_setsockopt\fR(3) to specify which messages to subscribe to\&. The \fIzmq_send()\fR function is not implemented for this socket type\&. -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.B Table\ \&6.\ \&Summary of ZMQ_SUB characteristics -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Compatible peer sockets -T}:T{ -.sp -\fIZMQ_PUB\fR, \fIZMQ_XPUB\fR -T} -T{ -.sp -Direction -T}:T{ -.sp -Unidirectional -T} -T{ -.sp -Send/receive pattern -T}:T{ -.sp -Receive only -T} -T{ -.sp -Incoming routing strategy -T}:T{ -.sp -Fair\-queued -T} -T{ -.sp -Outgoing routing strategy -T}:T{ -.sp -N/A -T} -.TE -.sp 1 -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBZMQ_XPUB\fR -.RS 4 -.sp -Same as ZMQ_PUB except that you can receive subscriptions from the peers in form of incoming messages\&. Subscription message is a byte 1 (for subscriptions) or byte 0 (for unsubscriptions) followed by the subscription body\&. Messages without a sub/unsub prefix are also received, but have no effect on subscription status\&. -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.B Table\ \&7.\ \&Summary of ZMQ_XPUB characteristics -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Compatible peer sockets -T}:T{ -.sp -\fIZMQ_SUB\fR, \fIZMQ_XSUB\fR -T} -T{ -.sp -Direction -T}:T{ -.sp -Unidirectional -T} -T{ -.sp -Send/receive pattern -T}:T{ -.sp -Send messages, receive subscriptions -T} -T{ -.sp -Incoming routing strategy -T}:T{ -.sp -N/A -T} -T{ -.sp -Outgoing routing strategy -T}:T{ -.sp -Fan out -T} -T{ -.sp -Action in mute state -T}:T{ -.sp -Drop -T} -.TE -.sp 1 -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBZMQ_XSUB\fR -.RS 4 -.sp -Same as ZMQ_SUB except that you subscribe by sending subscription messages to the socket\&. Subscription message is a byte 1 (for subscriptions) or byte 0 (for unsubscriptions) followed by the subscription body\&. Messages without a sub/unsub prefix may also be sent, but have no effect on subscription status\&. -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.B Table\ \&8.\ \&Summary of ZMQ_XSUB characteristics -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Compatible peer sockets -T}:T{ -.sp -\fIZMQ_PUB\fR, \fIZMQ_XPUB\fR -T} -T{ -.sp -Direction -T}:T{ -.sp -Unidirectional -T} -T{ -.sp -Send/receive pattern -T}:T{ -.sp -Receive messages, send subscriptions -T} -T{ -.sp -Incoming routing strategy -T}:T{ -.sp -Fair\-queued -T} -T{ -.sp -Outgoing routing strategy -T}:T{ -.sp -N/A -T} -T{ -.sp -Action in mute state -T}:T{ -.sp -Drop -T} -.TE -.sp 1 -.RE -.SS "Pipeline pattern" -.sp -The pipeline pattern is used for distributing data to \fInodes\fR arranged in a pipeline\&. Data always flows down the pipeline, and each stage of the pipeline is connected to at least one \fInode\fR\&. When a pipeline stage is connected to multiple \fInodes\fR data is round\-robined among all connected \fInodes\fR\&. -.sp -The pipeline pattern is formally defined by \m[blue]\fBhttp://rfc\&.zeromq\&.org/spec:30\fR\m[]\&. -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBZMQ_PUSH\fR -.RS 4 -.sp -A socket of type \fIZMQ_PUSH\fR is used by a pipeline \fInode\fR to send messages to downstream pipeline \fInodes\fR\&. Messages are round\-robined to all connected downstream \fInodes\fR\&. The \fIzmq_recv()\fR function is not implemented for this socket type\&. -.sp -When a \fIZMQ_PUSH\fR socket enters the \fImute\fR state due to having reached the high water mark for all downstream \fInodes\fR, or if there are no downstream \fInodes\fR at all, then any \fBzmq_send\fR(3) operations on the socket shall block until the mute state ends or at least one downstream \fInode\fR becomes available for sending; messages are not discarded\&. -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.B Table\ \&9.\ \&Summary of ZMQ_PUSH characteristics -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Compatible peer sockets -T}:T{ -.sp -\fIZMQ_PULL\fR -T} -T{ -.sp -Direction -T}:T{ -.sp -Unidirectional -T} -T{ -.sp -Send/receive pattern -T}:T{ -.sp -Send only -T} -T{ -.sp -Incoming routing strategy -T}:T{ -.sp -N/A -T} -T{ -.sp -Outgoing routing strategy -T}:T{ -.sp -Round\-robin -T} -T{ -.sp -Action in mute state -T}:T{ -.sp -Block -T} -.TE -.sp 1 -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBZMQ_PULL\fR -.RS 4 -.sp -A socket of type \fIZMQ_PULL\fR is used by a pipeline \fInode\fR to receive messages from upstream pipeline \fInodes\fR\&. Messages are fair\-queued from among all connected upstream \fInodes\fR\&. The \fIzmq_send()\fR function is not implemented for this socket type\&. -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.B Table\ \&10.\ \&Summary of ZMQ_PULL characteristics -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Compatible peer sockets -T}:T{ -.sp -\fIZMQ_PUSH\fR -T} -T{ -.sp -Direction -T}:T{ -.sp -Unidirectional -T} -T{ -.sp -Send/receive pattern -T}:T{ -.sp -Receive only -T} -T{ -.sp -Incoming routing strategy -T}:T{ -.sp -Fair\-queued -T} -T{ -.sp -Outgoing routing strategy -T}:T{ -.sp -N/A -T} -T{ -.sp -Action in mute state -T}:T{ -.sp -Block -T} -.TE -.sp 1 -.RE -.SS "Exclusive pair pattern" -.sp -The exclusive pair pattern is used to connect a peer to precisely one other peer\&. This pattern is used for inter\-thread communication across the inproc transport\&. -.sp -The exclusive pair pattern is formally defined by \m[blue]\fBhttp://rfc\&.zeromq\&.org/spec:31\fR\m[]\&. -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBZMQ_PAIR\fR -.RS 4 -.sp -A socket of type \fIZMQ_PAIR\fR can only be connected to a single peer at any one time\&. No message routing or filtering is performed on messages sent over a \fIZMQ_PAIR\fR socket\&. -.sp -When a \fIZMQ_PAIR\fR socket enters the \fImute\fR state due to having reached the high water mark for the connected peer, or if no peer is connected, then any \fBzmq_send\fR(3) operations on the socket shall block until the peer becomes available for sending; messages are not discarded\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -\fIZMQ_PAIR\fR sockets are designed for inter\-thread communication across the \fBzmq_inproc\fR(7) transport and do not implement functionality such as auto\-reconnection\&. -.sp .5v -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.B Table\ \&11.\ \&Summary of ZMQ_PAIR characteristics -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Compatible peer sockets -T}:T{ -.sp -\fIZMQ_PAIR\fR -T} -T{ -.sp -Direction -T}:T{ -.sp -Bidirectional -T} -T{ -.sp -Send/receive pattern -T}:T{ -.sp -Unrestricted -T} -T{ -.sp -Incoming routing strategy -T}:T{ -.sp -N/A -T} -T{ -.sp -Outgoing routing strategy -T}:T{ -.sp -N/A -T} -T{ -.sp -Action in mute state -T}:T{ -.sp -Block -T} -.TE -.sp 1 -.RE -.SS "Native Pattern" -.sp -The native pattern is used for communicating with TCP peers and allows asynchronous requests and replies in either direction\&. -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBZMQ_STREAM\fR -.RS 4 -.sp -A socket of type \fIZMQ_STREAM\fR is used to send and receive TCP data from a non\-0MQ peer, when using the tcp:// transport\&. A \fIZMQ_STREAM\fR socket can act as client and/or server, sending and/or receiving TCP data asynchronously\&. -.sp -When receiving TCP data, a \fIZMQ_STREAM\fR socket shall prepend a message part containing the \fIidentity\fR of the originating peer to the message before passing it to the application\&. Messages received are fair\-queued from among all connected peers\&. -.sp -When sending TCP data, a \fIZMQ_STREAM\fR socket shall remove the first part of the message and use it to determine the \fIidentity\fR of the peer the message shall be routed to, and unroutable messages shall cause an EHOSTUNREACH or EAGAIN error\&. -.sp -To open a connection to a server, use the zmq_connect call, and then fetch the socket identity using the ZMQ_IDENTITY zmq_getsockopt call\&. -.sp -To close a specific connection, send the identity frame followed by a zero\-length message (see EXAMPLE section)\&. -.sp -When a connection is made, a zero\-length message will be received by the application\&. Similarly, when the peer disconnects (or the connection is lost), a zero\-length message will be received by the application\&. -.sp -You must send one identity frame followed by one data frame\&. The ZMQ_SNDMORE flag is required for identity frames but is ignored on data frames\&. -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.B Table\ \&12.\ \&Summary of ZMQ_STREAM characteristics -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Compatible peer sockets -T}:T{ -.sp -none\&. -T} -T{ -.sp -Direction -T}:T{ -.sp -Bidirectional -T} -T{ -.sp -Send/receive pattern -T}:T{ -.sp -Unrestricted -T} -T{ -.sp -Outgoing routing strategy -T}:T{ -.sp -See text -T} -T{ -.sp -Incoming routing strategy -T}:T{ -.sp -Fair\-queued -T} -T{ -.sp -Action in mute state -T}:T{ -.sp -EAGAIN -T} -.TE -.sp 1 -.RE -.SS "Request\-reply pattern" -.sp -The request\-reply pattern is used for sending requests from a ZMQ_REQ \fIclient\fR to one or more ZMQ_REP \fIservices\fR, and receiving subsequent replies to each request sent\&. -.sp -The request\-reply pattern is formally defined by \m[blue]\fBhttp://rfc\&.zeromq\&.org/spec:28\fR\m[]\&. -.sp -Note: this pattern will be deprecated in favor of the client\-server pattern\&. -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBZMQ_REQ\fR -.RS 4 -.sp -A socket of type \fIZMQ_REQ\fR is used by a \fIclient\fR to send requests to and receive replies from a \fIservice\fR\&. This socket type allows only an alternating sequence of \fIzmq_send(request)\fR and subsequent \fIzmq_recv(reply)\fR calls\&. Each request sent is round\-robined among all \fIservices\fR, and each reply received is matched with the last issued request\&. -.sp -If no services are available, then any send operation on the socket shall block until at least one \fIservice\fR becomes available\&. The REQ socket shall not discard messages\&. -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.B Table\ \&13.\ \&Summary of ZMQ_REQ characteristics -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Compatible peer sockets -T}:T{ -.sp -\fIZMQ_REP\fR, \fIZMQ_ROUTER\fR -T} -T{ -.sp -Direction -T}:T{ -.sp -Bidirectional -T} -T{ -.sp -Send/receive pattern -T}:T{ -.sp -Send, Receive, Send, Receive, \&... -T} -T{ -.sp -Outgoing routing strategy -T}:T{ -.sp -Round\-robin -T} -T{ -.sp -Incoming routing strategy -T}:T{ -.sp -Last peer -T} -T{ -.sp -Action in mute state -T}:T{ -.sp -Block -T} -.TE -.sp 1 -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBZMQ_REP\fR -.RS 4 -.sp -A socket of type \fIZMQ_REP\fR is used by a \fIservice\fR to receive requests from and send replies to a \fIclient\fR\&. This socket type allows only an alternating sequence of \fIzmq_recv(request)\fR and subsequent \fIzmq_send(reply)\fR calls\&. Each request received is fair\-queued from among all \fIclients\fR, and each reply sent is routed to the \fIclient\fR that issued the last request\&. If the original requester does not exist any more the reply is silently discarded\&. -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.B Table\ \&14.\ \&Summary of ZMQ_REP characteristics -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Compatible peer sockets -T}:T{ -.sp -\fIZMQ_REQ\fR, \fIZMQ_DEALER\fR -T} -T{ -.sp -Direction -T}:T{ -.sp -Bidirectional -T} -T{ -.sp -Send/receive pattern -T}:T{ -.sp -Receive, Send, Receive, Send, \&... -T} -T{ -.sp -Incoming routing strategy -T}:T{ -.sp -Fair\-queued -T} -T{ -.sp -Outgoing routing strategy -T}:T{ -.sp -Last peer -T} -.TE -.sp 1 -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBZMQ_DEALER\fR -.RS 4 -.sp -A socket of type \fIZMQ_DEALER\fR is an advanced pattern used for extending request/reply sockets\&. Each message sent is round\-robined among all connected peers, and each message received is fair\-queued from all connected peers\&. -.sp -When a \fIZMQ_DEALER\fR socket enters the \fImute\fR state due to having reached the high water mark for all peers, or if there are no peers at all, then any \fBzmq_send\fR(3) operations on the socket shall block until the mute state ends or at least one peer becomes available for sending; messages are not discarded\&. -.sp -When a \fIZMQ_DEALER\fR socket is connected to a \fIZMQ_REP\fR socket each message sent must consist of an empty message part, the \fIdelimiter\fR, followed by one or more \fIbody parts\fR\&. -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.B Table\ \&15.\ \&Summary of ZMQ_DEALER characteristics -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Compatible peer sockets -T}:T{ -.sp -\fIZMQ_ROUTER\fR, \fIZMQ_REP\fR, \fIZMQ_DEALER\fR -T} -T{ -.sp -Direction -T}:T{ -.sp -Bidirectional -T} -T{ -.sp -Send/receive pattern -T}:T{ -.sp -Unrestricted -T} -T{ -.sp -Outgoing routing strategy -T}:T{ -.sp -Round\-robin -T} -T{ -.sp -Incoming routing strategy -T}:T{ -.sp -Fair\-queued -T} -T{ -.sp -Action in mute state -T}:T{ -.sp -Block -T} -.TE -.sp 1 -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBZMQ_ROUTER\fR -.RS 4 -.sp -A socket of type \fIZMQ_ROUTER\fR is an advanced socket type used for extending request/reply sockets\&. When receiving messages a \fIZMQ_ROUTER\fR socket shall prepend a message part containing the \fIidentity\fR of the originating peer to the message before passing it to the application\&. Messages received are fair\-queued from among all connected peers\&. When sending messages a \fIZMQ_ROUTER\fR socket shall remove the first part of the message and use it to determine the \fIidentity\fR of the peer the message shall be routed to\&. If the peer does not exist anymore the message shall be silently discarded by default, unless \fIZMQ_ROUTER_MANDATORY\fR socket option is set to \fI1\fR\&. -.sp -When a \fIZMQ_ROUTER\fR socket enters the \fImute\fR state due to having reached the high water mark for all peers, then any messages sent to the socket shall be dropped until the mute state ends\&. Likewise, any messages routed to a peer for which the individual high water mark has been reached shall also be dropped, unless \fIZMQ_ROUTER_MANDATORY\fR socket option is set\&. -.sp -When a \fIZMQ_REQ\fR socket is connected to a \fIZMQ_ROUTER\fR socket, in addition to the \fIidentity\fR of the originating peer each message received shall contain an empty \fIdelimiter\fR message part\&. Hence, the entire structure of each received message as seen by the application becomes: one or more \fIidentity\fR parts, \fIdelimiter\fR part, one or more \fIbody parts\fR\&. When sending replies to a \fIZMQ_REQ\fR socket the application must include the \fIdelimiter\fR part\&. -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.B Table\ \&16.\ \&Summary of ZMQ_ROUTER characteristics -.TS -tab(:); -lt lt -lt lt -lt lt -lt lt -lt lt -lt lt. -T{ -.sp -Compatible peer sockets -T}:T{ -.sp -\fIZMQ_DEALER\fR, \fIZMQ_REQ\fR, \fIZMQ_ROUTER\fR -T} -T{ -.sp -Direction -T}:T{ -.sp -Bidirectional -T} -T{ -.sp -Send/receive pattern -T}:T{ -.sp -Unrestricted -T} -T{ -.sp -Outgoing routing strategy -T}:T{ -.sp -See text -T} -T{ -.sp -Incoming routing strategy -T}:T{ -.sp -Fair\-queued -T} -T{ -.sp -Action in mute state -T}:T{ -.sp -Drop (see text) -T} -.TE -.sp 1 -.RE -.SH "RETURN VALUE" -.sp -The \fIzmq_socket()\fR function shall return an opaque handle to the newly created socket if successful\&. Otherwise, it shall return NULL and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEINVAL\fR -.RS 4 -The requested socket -\fItype\fR -is invalid\&. -.RE -.PP -\fBEFAULT\fR -.RS 4 -The provided -\fIcontext\fR -is invalid\&. -.RE -.PP -\fBEMFILE\fR -.RS 4 -The limit on the total number of open 0MQ sockets has been reached\&. -.RE -.PP -\fBETERM\fR -.RS 4 -The context specified was terminated\&. -.RE -.SH "EXAMPLE" -.PP -\fBCreating a simple HTTP server using ZMQ_STREAM\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -void *ctx = zmq_ctx_new (); -assert (ctx); -/* Create ZMQ_STREAM socket */ -void *socket = zmq_socket (ctx, ZMQ_STREAM); -assert (socket); -int rc = zmq_bind (socket, "tcp://*:8080"); -assert (rc == 0); -/* Data structure to hold the ZMQ_STREAM ID */ -uint8_t id [256]; -size_t id_size = 256; -/* Data structure to hold the ZMQ_STREAM received data */ -uint8_t raw [256]; -size_t raw_size = 256; -while (1) { - /* Get HTTP request; ID frame and then request */ - id_size = zmq_recv (socket, id, 256, 0); - assert (id_size > 0); - do { - raw_size = zmq_recv (socket, raw, 256, 0); - assert (raw_size >= 0); - } while (raw_size == 256); - /* Prepares the response */ - char http_response [] = - "HTTP/1\&.0 200 OK\er\en" - "Content\-Type: text/plain\er\en" - "\er\en" - "Hello, World!"; - /* Sends the ID frame followed by the response */ - zmq_send (socket, id, id_size, ZMQ_SNDMORE); - zmq_send (socket, http_response, strlen (http_response), 0); - /* Closes the connection by sending the ID frame followed by a zero response */ - zmq_send (socket, id, id_size, ZMQ_SNDMORE); - zmq_send (socket, 0, 0, 0); -} -zmq_close (socket); -zmq_ctx_destroy (ctx); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_init\fR(3) \fBzmq_setsockopt\fR(3) \fBzmq_bind\fR(3) \fBzmq_connect\fR(3) \fBzmq_send\fR(3) \fBzmq_recv\fR(3) \fBzmq_inproc\fR(7) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_socket_monitor.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_socket_monitor.3 deleted file mode 100644 index 26664be708..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_socket_monitor.3 +++ /dev/null @@ -1,241 +0,0 @@ -'\" t -.\" Title: zmq_socket_monitor -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_SOCKET_MONITOR" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_socket_monitor \- monitor socket events -.SH "SYNOPSIS" -.sp -\fBint zmq_socket_monitor (void \fR\fB\fI*socket\fR\fR\fB, char \fR\fB\fI*endpoint\fR\fR\fB, int \fR\fB\fIevents\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_socket_monitor()\fR method lets an application thread track socket events (like connects) on a ZeroMQ socket\&. Each call to this method creates a \fIZMQ_PAIR\fR socket and binds that to the specified inproc:// \fIendpoint\fR\&. To collect the socket events, you must create your own \fIZMQ_PAIR\fR socket, and connect that to the endpoint\&. -.sp -The \fIevents\fR argument is a bitmask of the socket events you wish to monitor, see \fISupported events\fR below\&. To monitor all events, use the event value ZMQ_EVENT_ALL\&. NOTE: as new events are added, the catch\-all value will start returning them\&. An application that relies on a strict and fixed sequence of events must not use ZMQ_EVENT_ALL in order to guarantee compatibility with future versions\&. -.sp -Each event is sent as two frames\&. The first frame contains an event number (16 bits), and an event value (32 bits) that provides additional data according to the event number\&. The second frame contains a string that specifies the affected TCP or IPC endpoint\&. -.sp -.if n \{\ -.RS 4 -.\} -.nf -The _zmq_socket_monitor()_ method supports only connection\-oriented -transports, that is, TCP, IPC, and TIPC\&. -.fi -.if n \{\ -.RE -.\} -.SH "SUPPORTED EVENTS" -.SS "ZMQ_EVENT_CONNECTED" -.sp -The socket has successfully connected to a remote peer\&. The event value is the file descriptor (FD) of the underlying network socket\&. Warning: there is no guarantee that the FD is still valid by the time your code receives this event\&. -.SS "ZMQ_EVENT_CONNECT_DELAYED" -.sp -A connect request on the socket is pending\&. The event value is unspecified\&. -.SS "ZMQ_EVENT_CONNECT_RETRIED" -.sp -A connect request failed, and is now being retried\&. The event value is the reconnect interval in milliseconds\&. Note that the reconnect interval is recalculated at each retry\&. -.SS "ZMQ_EVENT_LISTENING" -.sp -The socket was successfully bound to a network interface\&. The event value is the FD of the underlying network socket\&. Warning: there is no guarantee that the FD is still valid by the time your code receives this event\&. -.SS "ZMQ_EVENT_BIND_FAILED" -.sp -The socket could not bind to a given interface\&. The event value is the errno generated by the system bind call\&. -.SS "ZMQ_EVENT_ACCEPTED" -.sp -The socket has accepted a connection from a remote peer\&. The event value is the FD of the underlying network socket\&. Warning: there is no guarantee that the FD is still valid by the time your code receives this event\&. -.SS "ZMQ_EVENT_ACCEPT_FAILED" -.sp -The socket has rejected a connection from a remote peer\&. The event value is the errno generated by the accept call\&. -.SS "ZMQ_EVENT_CLOSED" -.sp -The socket was closed\&. The event value is the FD of the (now closed) network socket\&. -.SS "ZMQ_EVENT_CLOSE_FAILED" -.sp -The socket close failed\&. The event value is the errno returned by the system call\&. Note that this event occurs only on IPC transports\&. -.SS "ZMQ_EVENT_DISCONNECTED" -.sp -The socket was disconnected unexpectedly\&. The event value is the FD of the underlying network socket\&. Warning: this socket will be closed\&. -.SS "ZMQ_EVENT_MONITOR_STOPPED" -.sp -Monitoring on this socket ended\&. -.SS "ZMQ_EVENT_HANDSHAKE_FAILED" -.sp -The ZMTP security mechanism handshake failed\&. The event value is unspecified\&. NOTE: in DRAFT state, not yet available in stable releases\&. -.SS "ZMQ_EVENT_HANDSHAKE_SUCCEED" -.sp -The ZMTP security mechanism handshake succeeded\&. The event value is unspecified\&. NOTE: in DRAFT state, not yet available in stable releases\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_socket_monitor()\fR function returns a value of 0 or greater if successful\&. Otherwise it returns \-1 and sets \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBETERM\fR -.RS 4 -The 0MQ -\fIcontext\fR -associated with the specified -\fIsocket\fR -was terminated\&. -.RE -.PP -\fBEPROTONOSUPPORT\fR -.RS 4 -The requested -\fItransport\fR -protocol is not supported\&. Monitor sockets are required to use the inproc:// transport\&. -.RE -.PP -\fBEINVAL\fR -.RS 4 -The endpoint supplied is invalid\&. -.RE -.SH "EXAMPLE" -.PP -\fBMonitoring client and server sockets\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Read one event off the monitor socket; return value and address -// by reference, if not null, and event number by value\&. Returns \-1 -// in case of error\&. - -static int -get_monitor_event (void *monitor, int *value, char **address) -{ - // First frame in message contains event number and value - zmq_msg_t msg; - zmq_msg_init (&msg); - if (zmq_msg_recv (&msg, monitor, 0) == \-1) - return \-1; // Interrupted, presumably - assert (zmq_msg_more (&msg)); - - uint8_t *data = (uint8_t *) zmq_msg_data (&msg); - uint16_t event = *(uint16_t *) (data); - if (value) - *value = *(uint32_t *) (data + 2); - - // Second frame in message contains event address - zmq_msg_init (&msg); - if (zmq_msg_recv (&msg, monitor, 0) == \-1) - return \-1; // Interrupted, presumably - assert (!zmq_msg_more (&msg)); - - if (address) { - uint8_t *data = (uint8_t *) zmq_msg_data (&msg); - size_t size = zmq_msg_size (&msg); - *address = (char *) malloc (size + 1); - memcpy (*address, data, size); - (*address)[size] = 0; - } - return event; -} - -int main (void) -{ - void *ctx = zmq_ctx_new (); - assert (ctx); - - // We\*(Aqll monitor these two sockets - void *client = zmq_socket (ctx, ZMQ_DEALER); - assert (client); - void *server = zmq_socket (ctx, ZMQ_DEALER); - assert (server); - - // Socket monitoring only works over inproc:// - int rc = zmq_socket_monitor (client, "tcp://127\&.0\&.0\&.1:9999", 0); - assert (rc == \-1); - assert (zmq_errno () == EPROTONOSUPPORT); - - // Monitor all events on client and server sockets - rc = zmq_socket_monitor (client, "inproc://monitor\-client", ZMQ_EVENT_ALL); - assert (rc == 0); - rc = zmq_socket_monitor (server, "inproc://monitor\-server", ZMQ_EVENT_ALL); - assert (rc == 0); - - // Create two sockets for collecting monitor events - void *client_mon = zmq_socket (ctx, ZMQ_PAIR); - assert (client_mon); - void *server_mon = zmq_socket (ctx, ZMQ_PAIR); - assert (server_mon); - - // Connect these to the inproc endpoints so they\*(Aqll get events - rc = zmq_connect (client_mon, "inproc://monitor\-client"); - assert (rc == 0); - rc = zmq_connect (server_mon, "inproc://monitor\-server"); - assert (rc == 0); - - // Now do a basic ping test - rc = zmq_bind (server, "tcp://127\&.0\&.0\&.1:9998"); - assert (rc == 0); - rc = zmq_connect (client, "tcp://127\&.0\&.0\&.1:9998"); - assert (rc == 0); - bounce (client, server); - - // Close client and server - close_zero_linger (client); - close_zero_linger (server); - - // Now collect and check events from both sockets - int event = get_monitor_event (client_mon, NULL, NULL); - if (event == ZMQ_EVENT_CONNECT_DELAYED) - event = get_monitor_event (client_mon, NULL, NULL); - assert (event == ZMQ_EVENT_CONNECTED); - event = get_monitor_event (client_mon, NULL, NULL); - assert (event == ZMQ_EVENT_MONITOR_STOPPED); - - // This is the flow of server events - event = get_monitor_event (server_mon, NULL, NULL); - assert (event == ZMQ_EVENT_LISTENING); - event = get_monitor_event (server_mon, NULL, NULL); - assert (event == ZMQ_EVENT_ACCEPTED); - event = get_monitor_event (server_mon, NULL, NULL); - assert (event == ZMQ_EVENT_CLOSED); - event = get_monitor_event (server_mon, NULL, NULL); - assert (event == ZMQ_EVENT_MONITOR_STOPPED); - - // Close down the sockets - close_zero_linger (client_mon); - close_zero_linger (server_mon); - zmq_ctx_term (ctx); - - return 0 ; -} -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_strerror.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_strerror.3 deleted file mode 100644 index f77803861e..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_strerror.3 +++ /dev/null @@ -1,67 +0,0 @@ -'\" t -.\" Title: zmq_strerror -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_STRERROR" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_strerror \- get 0MQ error message string -.SH "SYNOPSIS" -.sp -\fBconst char *zmq_strerror (int \fR\fB\fIerrnum\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_strerror()\fR function shall return a pointer to an error message string corresponding to the error number specified by the \fIerrnum\fR argument\&. As 0MQ defines additional error numbers over and above those defined by the operating system, applications should use \fIzmq_strerror()\fR in preference to the standard \fIstrerror()\fR function\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_strerror()\fR function shall return a pointer to an error message string\&. -.SH "ERRORS" -.sp -No errors are defined\&. -.SH "EXAMPLE" -.PP -\fBDisplaying an error message when a 0MQ context cannot be initialised\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -void *ctx = zmq_init (1, 1, 0); -if (!ctx) { - printf ("Error occurred during zmq_init(): %s\en", zmq_strerror (errno)); - abort (); -} -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_unbind.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_unbind.3 deleted file mode 100644 index bef9c5002b..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_unbind.3 +++ /dev/null @@ -1,125 +0,0 @@ -'\" t -.\" Title: zmq_unbind -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_UNBIND" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_unbind \- Stop accepting connections on a socket -.SH "SYNOPSIS" -.sp -int zmq_unbind (void \fI*socket\fR, const char \fI*endpoint\fR); -.SH "DESCRIPTION" -.sp -The \fIzmq_unbind()\fR function shall unbind a socket specified by the \fIsocket\fR argument from the endpoint specified by the \fIendpoint\fR argument\&. -.sp -The \fIendpoint\fR argument is as described in \fBzmq_bind\fR(3) -.SS "Unbinding wild\-card address from a socket" -.sp -When wild\-card * \fIendpoint\fR (described in \fBzmq_tcp\fR(7), \fBzmq_ipc\fR(7) and \fBzmq_vmci\fR(7)) was used in \fIzmq_bind()\fR, the caller should use real \fIendpoint\fR obtained from the ZMQ_LAST_ENDPOINT socket option to unbind this \fIendpoint\fR from a socket\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_unbind()\fR function shall return zero if successful\&. Otherwise it shall return \-1 and set \fIerrno\fR to one of the values defined below\&. -.SH "ERRORS" -.PP -\fBEINVAL\fR -.RS 4 -The endpoint supplied is invalid\&. -.RE -.PP -\fBETERM\fR -.RS 4 -The 0MQ -\fIcontext\fR -associated with the specified -\fIsocket\fR -was terminated\&. -.RE -.PP -\fBENOTSOCK\fR -.RS 4 -The provided -\fIsocket\fR -was invalid\&. -.RE -.PP -\fBENOENT\fR -.RS 4 -The endpoint supplied was not previously bound\&. -.RE -.SH "EXAMPLES" -.PP -\fBUnbind a subscriber socket from a TCP transport\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -/* Create a ZMQ_SUB socket */ -void *socket = zmq_socket (context, ZMQ_SUB); -assert (socket); -/* Connect it to the host server001, port 5555 using a TCP transport */ -rc = zmq_bind (socket, "tcp://127\&.0\&.0\&.1:5555"); -assert (rc == 0); -/* Disconnect from the previously connected endpoint */ -rc = zmq_unbind (socket, "tcp://127\&.0\&.0\&.1:5555"); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.PP -\fBUnbind wild-card * binded socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -/* Create a ZMQ_SUB socket */ -void *socket = zmq_socket (context, ZMQ_SUB); -assert (socket); -/* Bind it to the system\-assigned ephemeral port using a TCP transport */ -rc = zmq_bind (socket, "tcp://127\&.0\&.0\&.1:*"); -assert (rc == 0); -/* Obtain real endpoint */ -const size_t buf_size = 32; -char buf[buf_size]; -rc = zmq_getsockopt (socket, ZMQ_LAST_ENDPOINT, buf, (size_t *)&buf_size); -assert (rc == 0); -/* Unbind socket by real endpoint */ -rc = zmq_unbind (socket, buf); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_bind\fR(3) \fBzmq_socket\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_version.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_version.3 deleted file mode 100644 index 2b0316947e..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_version.3 +++ /dev/null @@ -1,67 +0,0 @@ -'\" t -.\" Title: zmq_version -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_VERSION" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_version \- report 0MQ library version -.SH "SYNOPSIS" -.sp -\fBvoid zmq_version (int \fR\fB\fI*major\fR\fR\fB, int \fR\fB\fI*minor\fR\fR\fB, int \fR\fB\fI*patch\fR\fR\fB);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_version()\fR function shall fill in the integer variables pointed to by the \fImajor\fR, \fIminor\fR and \fIpatch\fR arguments with the major, minor and patch level components of the 0MQ library version\&. -.sp -This functionality is intended for applications or language bindings dynamically linking to the 0MQ library that wish to determine the actual version of the 0MQ library they are using\&. -.SH "RETURN VALUE" -.sp -There is no return value\&. -.SH "ERRORS" -.sp -No errors are defined\&. -.SH "EXAMPLE" -.PP -\fBPrinting out the version of the 0MQ library\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -int major, minor, patch; -zmq_version (&major, &minor, &patch); -printf ("Current 0MQ version is %d\&.%d\&.%d\en", major, minor, patch); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_z85_decode.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_z85_decode.3 deleted file mode 100644 index a8c054b8f3..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_z85_decode.3 +++ /dev/null @@ -1,64 +0,0 @@ -'\" t -.\" Title: zmq_z85_decode -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_Z85_DECODE" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_z85_decode \- decode a binary key from Z85 printable text -.SH "SYNOPSIS" -.sp -\fBuint8_t *zmq_z85_decode (uint8_t *dest, const char *string);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_z85_decode()\fR function shall decode \fIstring\fR into \fIdest\fR\&. The length of \fIstring\fR shall be divisible by 5\&. \fIdest\fR must be large enough for the decoded value (0\&.8 x strlen (string))\&. -.sp -The encoding shall follow the ZMQ RFC 32 specification\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_z85_decode()\fR function shall return \fIdest\fR if successful, else it shall return NULL\&. -.SH "EXAMPLE" -.PP -\fBDecoding a CURVE key\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -const char decoded [] = "rq:rM>}U?@Lns47E1%kR\&.o@n%FcmmsL/@{H8]yf7"; -uint8_t public_key [32]; -zmq_z85_decode (public_key, decoded); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_z85_decode\fR(3) \fBzmq_curve_keypair\fR(3) \fBzmq_curve_public\fR(3) \fBzmq_curve\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_z85_encode.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_z85_encode.3 deleted file mode 100644 index 442f6bb827..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmq_z85_encode.3 +++ /dev/null @@ -1,69 +0,0 @@ -'\" t -.\" Title: zmq_z85_encode -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_Z85_ENCODE" "3" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_z85_encode \- encode a binary key as Z85 printable text -.SH "SYNOPSIS" -.sp -\fBchar *zmq_z85_encode (char *dest, const uint8_t *data, size_t size);\fR -.SH "DESCRIPTION" -.sp -The \fIzmq_z85_encode()\fR function shall encode the binary block specified by \fIdata\fR and \fIsize\fR into a string in \fIdest\fR\&. The size of the binary block must be divisible by 4\&. The \fIdest\fR must have sufficient space for size * 1\&.25 plus 1 for a null terminator\&. A 32\-byte CURVE key is encoded as 40 ASCII characters plus a null terminator\&. -.sp -The encoding shall follow the ZMQ RFC 32 specification\&. -.SH "RETURN VALUE" -.sp -The \fIzmq_z85_encode()\fR function shall return \fIdest\fR if successful, else it shall return NULL\&. -.SH "EXAMPLE" -.PP -\fBEncoding a CURVE key\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -#include -uint8_t public_key [32]; -uint8_t secret_key [32]; -int rc = crypto_box_keypair (public_key, secret_key); -assert (rc == 0); -char encoded [41]; -zmq_z85_encode (encoded, public_key, 32); -puts (encoded); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_z85_decode\fR(3) \fBzmq_curve_keypair\fR(3) \fBzmq_curve_public\fR(3) \fBzmq_curve\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zmsg.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zmsg.3 deleted file mode 100644 index 0be48b58cf..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zmsg.3 +++ /dev/null @@ -1,545 +0,0 @@ -'\" t -.\" Title: zmsg -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZMSG" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmsg \- working with multipart messages -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// This class has draft methods, which may change over time\&. They are not -// in stable releases, by default\&. Use \-\-enable\-drafts to enable\&. -// Create a new empty message object -CZMQ_EXPORT zmsg_t * - zmsg_new (void); - -// Receive message from socket, returns zmsg_t object or NULL if the recv -// was interrupted\&. Does a blocking recv\&. If you want to not block then use -// the zloop class or zmsg_recv_nowait or zmq_poll to check for socket input -// before receiving\&. -CZMQ_EXPORT zmsg_t * - zmsg_recv (void *source); - -// Load/append an open file into new message, return the message\&. -// Returns NULL if the message could not be loaded\&. -CZMQ_EXPORT zmsg_t * - zmsg_load (FILE *file); - -// Decodes a serialized message frame created by zmsg_encode () and returns -// a new zmsg_t object\&. Returns NULL if the frame was badly formatted or -// there was insufficient memory to work\&. -CZMQ_EXPORT zmsg_t * - zmsg_decode (zframe_t *frame); - -// Generate a signal message encoding the given status\&. A signal is a short -// message carrying a 1\-byte success/failure code (by convention, 0 means -// OK)\&. Signals are encoded to be distinguishable from "normal" messages\&. -CZMQ_EXPORT zmsg_t * - zmsg_new_signal (byte status); - -// Destroy a message object and all frames it contains -CZMQ_EXPORT void - zmsg_destroy (zmsg_t **self_p); - -// Send message to destination socket, and destroy the message after sending -// it successfully\&. If the message has no frames, sends nothing but destroys -// the message anyhow\&. Nullifies the caller\*(Aqs reference to the message (as -// it is a destructor)\&. -CZMQ_EXPORT int - zmsg_send (zmsg_t **self_p, void *dest); - -// Send message to destination socket as part of a multipart sequence, and -// destroy the message after sending it successfully\&. Note that after a -// zmsg_sendm, you must call zmsg_send or another method that sends a final -// message part\&. If the message has no frames, sends nothing but destroys -// the message anyhow\&. Nullifies the caller\*(Aqs reference to the message (as -// it is a destructor)\&. -CZMQ_EXPORT int - zmsg_sendm (zmsg_t **self_p, void *dest); - -// Return size of message, i\&.e\&. number of frames (0 or more)\&. -CZMQ_EXPORT size_t - zmsg_size (zmsg_t *self); - -// Return total size of all frames in message\&. -CZMQ_EXPORT size_t - zmsg_content_size (zmsg_t *self); - -// Push frame to the front of the message, i\&.e\&. before all other frames\&. -// Message takes ownership of frame, will destroy it when message is sent\&. -// Returns 0 on success, \-1 on error\&. Deprecates zmsg_push, which did not -// nullify the caller\*(Aqs frame reference\&. -CZMQ_EXPORT int - zmsg_prepend (zmsg_t *self, zframe_t **frame_p); - -// Add frame to the end of the message, i\&.e\&. after all other frames\&. -// Message takes ownership of frame, will destroy it when message is sent\&. -// Returns 0 on success\&. Deprecates zmsg_add, which did not nullify the -// caller\*(Aqs frame reference\&. -CZMQ_EXPORT int - zmsg_append (zmsg_t *self, zframe_t **frame_p); - -// Remove first frame from message, if any\&. Returns frame, or NULL\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zframe_t * - zmsg_pop (zmsg_t *self); - -// Push block of memory to front of message, as a new frame\&. -// Returns 0 on success, \-1 on error\&. -CZMQ_EXPORT int - zmsg_pushmem (zmsg_t *self, const void *data, size_t size); - -// Add block of memory to the end of the message, as a new frame\&. -// Returns 0 on success, \-1 on error\&. -CZMQ_EXPORT int - zmsg_addmem (zmsg_t *self, const void *data, size_t size); - -// Push string as new frame to front of message\&. -// Returns 0 on success, \-1 on error\&. -CZMQ_EXPORT int - zmsg_pushstr (zmsg_t *self, const char *string); - -// Push string as new frame to end of message\&. -// Returns 0 on success, \-1 on error\&. -CZMQ_EXPORT int - zmsg_addstr (zmsg_t *self, const char *string); - -// Push formatted string as new frame to front of message\&. -// Returns 0 on success, \-1 on error\&. -CZMQ_EXPORT int - zmsg_pushstrf (zmsg_t *self, const char *format, \&.\&.\&.) CHECK_PRINTF (2); - -// Push formatted string as new frame to end of message\&. -// Returns 0 on success, \-1 on error\&. -CZMQ_EXPORT int - zmsg_addstrf (zmsg_t *self, const char *format, \&.\&.\&.) CHECK_PRINTF (2); - -// Pop frame off front of message, return as fresh string\&. If there were -// no more frames in the message, returns NULL\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zmsg_popstr (zmsg_t *self); - -// Push encoded message as a new frame\&. Message takes ownership of -// submessage, so the original is destroyed in this call\&. Returns 0 on -// success, \-1 on error\&. -CZMQ_EXPORT int - zmsg_addmsg (zmsg_t *self, zmsg_t **msg_p); - -// Remove first submessage from message, if any\&. Returns zmsg_t, or NULL if -// decoding was not successful\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zmsg_t * - zmsg_popmsg (zmsg_t *self); - -// Remove specified frame from list, if present\&. Does not destroy frame\&. -CZMQ_EXPORT void - zmsg_remove (zmsg_t *self, zframe_t *frame); - -// Set cursor to first frame in message\&. Returns frame, or NULL, if the -// message is empty\&. Use this to navigate the frames as a list\&. -CZMQ_EXPORT zframe_t * - zmsg_first (zmsg_t *self); - -// Return the next frame\&. If there are no more frames, returns NULL\&. To move -// to the first frame call zmsg_first()\&. Advances the cursor\&. -CZMQ_EXPORT zframe_t * - zmsg_next (zmsg_t *self); - -// Return the last frame\&. If there are no frames, returns NULL\&. -CZMQ_EXPORT zframe_t * - zmsg_last (zmsg_t *self); - -// Save message to an open file, return 0 if OK, else \-1\&. The message is -// saved as a series of frames, each with length and data\&. Note that the -// file is NOT guaranteed to be portable between operating systems, not -// versions of CZMQ\&. The file format is at present undocumented and liable -// to arbitrary change\&. -CZMQ_EXPORT int - zmsg_save (zmsg_t *self, FILE *file); - -// Serialize multipart message to a single message frame\&. Use this method -// to send structured messages across transports that do not support -// multipart data\&. Allocates and returns a new frame containing the -// serialized message\&. To decode a serialized message frame, use -// zmsg_decode ()\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zframe_t * - zmsg_encode (zmsg_t *self); - -// Create copy of message, as new message object\&. Returns a fresh zmsg_t -// object\&. If message is null, or memory was exhausted, returns null\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT zmsg_t * - zmsg_dup (zmsg_t *self); - -// Send message to zsys log sink (may be stdout, or system facility as -// configured by zsys_set_logstream)\&. -CZMQ_EXPORT void - zmsg_print (zmsg_t *self); - -// Return true if the two messages have the same number of frames and each -// frame in the first message is identical to the corresponding frame in the -// other message\&. As with zframe_eq, return false if either message is NULL\&. -CZMQ_EXPORT bool - zmsg_eq (zmsg_t *self, zmsg_t *other); - -// Return signal value, 0 or greater, if message is a signal, \-1 if not\&. -CZMQ_EXPORT int - zmsg_signal (zmsg_t *self); - -// Probe the supplied object, and report if it looks like a zmsg_t\&. -CZMQ_EXPORT bool - zmsg_is (void *self); - -// Self test of this class\&. -CZMQ_EXPORT void - zmsg_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Return message routing ID, if the message came from a ZMQ_SERVER socket\&. -// Else returns zero\&. -CZMQ_EXPORT uint32_t - zmsg_routing_id (zmsg_t *self); - -// *** Draft method, for development use, may change without warning *** -// Set routing ID on message\&. This is used if/when the message is sent to a -// ZMQ_SERVER socket\&. -CZMQ_EXPORT void - zmsg_set_routing_id (zmsg_t *self, uint32_t routing_id); - -#endif // CZMQ_BUILD_DRAFT_API -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zmsg\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -The zmsg class provides methods to send and receive multipart messages across 0MQ sockets\&. This class provides a list\-like container interface, with methods to work with the overall container\&. zmsg_t messages are composed of zero or more zframe_t frames\&. -.sp -Please add \fI@discuss\fR section in \fI\&./\&.\&./src/zmsg\&.c\fR\&. -.SH "EXAMPLE" -.PP -\fBFrom zmsg_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Create two PAIR sockets and connect over inproc -zsock_t *output = zsock_new_pair ("@inproc://zmsg\&.test"); -assert (output); -zsock_t *input = zsock_new_pair (">inproc://zmsg\&.test"); -assert (input); - -// Test send and receive of single\-frame message -zmsg_t *msg = zmsg_new (); -assert (msg); -zframe_t *frame = zframe_new ("Hello", 5); -assert (frame); -zmsg_prepend (msg, &frame); -assert (zmsg_size (msg) == 1); -assert (zmsg_content_size (msg) == 5); -rc = zmsg_send (&msg, output); -assert (msg == NULL); -assert (rc == 0); - -msg = zmsg_recv (input); -assert (msg); -assert (zmsg_size (msg) == 1); -assert (zmsg_content_size (msg) == 5); -zmsg_destroy (&msg); - -// Test send and receive of multi\-frame message -msg = zmsg_new (); -assert (msg); -rc = zmsg_addmem (msg, "Frame0", 6); -assert (rc == 0); -rc = zmsg_addmem (msg, "Frame1", 6); -assert (rc == 0); -rc = zmsg_addmem (msg, "Frame2", 6); -assert (rc == 0); -rc = zmsg_addmem (msg, "Frame3", 6); -assert (rc == 0); -rc = zmsg_addmem (msg, "Frame4", 6); -assert (rc == 0); -rc = zmsg_addmem (msg, "Frame5", 6); -assert (rc == 0); -rc = zmsg_addmem (msg, "Frame6", 6); -assert (rc == 0); -rc = zmsg_addmem (msg, "Frame7", 6); -assert (rc == 0); -rc = zmsg_addmem (msg, "Frame8", 6); -assert (rc == 0); -rc = zmsg_addmem (msg, "Frame9", 6); -assert (rc == 0); -zmsg_t *copy = zmsg_dup (msg); -assert (copy); -rc = zmsg_send (©, output); -assert (rc == 0); -rc = zmsg_send (&msg, output); -assert (rc == 0); - -copy = zmsg_recv (input); -assert (copy); -assert (zmsg_size (copy) == 10); -assert (zmsg_content_size (copy) == 60); -zmsg_destroy (©); - -msg = zmsg_recv (input); -assert (msg); -assert (zmsg_size (msg) == 10); -assert (zmsg_content_size (msg) == 60); - -// Save to a file, read back -FILE *file = fopen ("zmsg\&.test", "w"); -assert (file); -rc = zmsg_save (msg, file); -assert (rc == 0); -fclose (file); - -file = fopen ("zmsg\&.test", "r"); -rc = zmsg_save (msg, file); -assert (rc == \-1); -fclose (file); -zmsg_destroy (&msg); - -file = fopen ("zmsg\&.test", "r"); -msg = zmsg_load (file); -assert (msg); -fclose (file); -remove ("zmsg\&.test"); -assert (zmsg_size (msg) == 10); -assert (zmsg_content_size (msg) == 60); - -// Remove all frames except first and last -int frame_nbr; -for (frame_nbr = 0; frame_nbr < 8; frame_nbr++) { - zmsg_first (msg); - frame = zmsg_next (msg); - zmsg_remove (msg, frame); - zframe_destroy (&frame); -} -// Test message frame manipulation -assert (zmsg_size (msg) == 2); -frame = zmsg_last (msg); -assert (zframe_streq (frame, "Frame9")); -assert (zmsg_content_size (msg) == 12); -frame = zframe_new ("Address", 7); -assert (frame); -zmsg_prepend (msg, &frame); -assert (zmsg_size (msg) == 3); -rc = zmsg_addstr (msg, "Body"); -assert (rc == 0); -assert (zmsg_size (msg) == 4); -frame = zmsg_pop (msg); -zframe_destroy (&frame); -assert (zmsg_size (msg) == 3); -char *body = zmsg_popstr (msg); -assert (streq (body, "Frame0")); -free (body); -zmsg_destroy (&msg); - -// Test encoding/decoding -msg = zmsg_new (); -assert (msg); -byte *blank = (byte *) zmalloc (100000); -assert (blank); -rc = zmsg_addmem (msg, blank, 0); -assert (rc == 0); -rc = zmsg_addmem (msg, blank, 1); -assert (rc == 0); -rc = zmsg_addmem (msg, blank, 253); -assert (rc == 0); -rc = zmsg_addmem (msg, blank, 254); -assert (rc == 0); -rc = zmsg_addmem (msg, blank, 255); -assert (rc == 0); -rc = zmsg_addmem (msg, blank, 256); -assert (rc == 0); -rc = zmsg_addmem (msg, blank, 65535); -assert (rc == 0); -rc = zmsg_addmem (msg, blank, 65536); -assert (rc == 0); -rc = zmsg_addmem (msg, blank, 65537); -assert (rc == 0); -free (blank); -assert (zmsg_size (msg) == 9); -frame = zmsg_encode (msg); -zmsg_destroy (&msg); -msg = zmsg_decode (frame); -assert (msg); -zmsg_destroy (&msg); -zframe_destroy (&frame); - -// Test submessages -msg = zmsg_new (); -assert (msg); -zmsg_t *submsg = zmsg_new (); -zmsg_pushstr (msg, "matr"); -zmsg_pushstr (submsg, "joska"); -rc = zmsg_addmsg (msg, &submsg); -assert (rc == 0); -assert (submsg == NULL); -submsg = zmsg_popmsg (msg); -assert (submsg == NULL); // string "matr" is not encoded zmsg_t, so was discarded -submsg = zmsg_popmsg (msg); -assert (submsg); -body = zmsg_popstr (submsg); -assert (streq (body, "joska")); -free (body); -zmsg_destroy (&submsg); -frame = zmsg_pop (msg); -assert (frame == NULL); -zmsg_destroy (&msg); - -// Test comparison of two messages -msg = zmsg_new (); -zmsg_addstr (msg, "One"); -zmsg_addstr (msg, "Two"); -zmsg_addstr (msg, "Three"); -zmsg_t *msg_other = zmsg_new (); -zmsg_addstr (msg_other, "One"); -zmsg_addstr (msg_other, "Two"); -zmsg_addstr (msg_other, "One\-Hundred"); -zmsg_t *msg_dup = zmsg_dup (msg); -zmsg_t *empty_msg = zmsg_new (); -zmsg_t *empty_msg_2 = zmsg_new (); -assert (zmsg_eq (msg, msg_dup)); -assert (!zmsg_eq (msg, msg_other)); -assert (zmsg_eq (empty_msg, empty_msg_2)); -assert (!zmsg_eq (msg, NULL)); -assert (!zmsg_eq (NULL, empty_msg)); -assert (!zmsg_eq (NULL, NULL)); -zmsg_destroy (&msg); -zmsg_destroy (&msg_other); -zmsg_destroy (&msg_dup); -zmsg_destroy (&empty_msg); -zmsg_destroy (&empty_msg_2); - -// Test signal messages -msg = zmsg_new_signal (0); -assert (zmsg_signal (msg) == 0); -zmsg_destroy (&msg); -msg = zmsg_new_signal (\-1); -assert (zmsg_signal (msg) == 255); -zmsg_destroy (&msg); - -// Now try methods on an empty message -msg = zmsg_new (); -assert (msg); -assert (zmsg_size (msg) == 0); -assert (zmsg_unwrap (msg) == NULL); -assert (zmsg_first (msg) == NULL); -assert (zmsg_last (msg) == NULL); -assert (zmsg_next (msg) == NULL); -assert (zmsg_pop (msg) == NULL); -// Sending an empty message is valid and destroys the message -assert (zmsg_send (&msg, output) == 0); -assert (!msg); - -zsock_destroy (&input); -zsock_destroy (&output); - -#if defined (ZMQ_SERVER) -// Create server and client sockets and connect over inproc -zsock_t *server = zsock_new_server ("inproc://zmsg\-test\-routing"); -assert (server); -zsock_t *client = zsock_new_client ("inproc://zmsg\-test\-routing"); -assert (client); - -// Send request from client to server -zmsg_t *request = zmsg_new (); -assert (request); -zmsg_addstr (request, "Hello"); -rc = zmsg_send (&request, client); -assert (rc == 0); -assert (!request); - -// Read request and send reply -request = zmsg_recv (server); -assert (request); -char *string = zmsg_popstr (request); -assert (streq (string, "Hello")); -assert (zmsg_routing_id (request)); -zstr_free (&string); - -zmsg_t *reply = zmsg_new (); -assert (reply); -zmsg_addstr (reply, "World"); -zmsg_set_routing_id (reply, zmsg_routing_id (request)); -rc = zmsg_send (&reply, server); -assert (rc == 0); -zmsg_destroy (&request); - -// Read reply -reply = zmsg_recv (client); -string = zmsg_popstr (reply); -assert (streq (string, "World")); -assert (zmsg_routing_id (reply) == 0); -zmsg_destroy (&reply); -zstr_free (&string); - -// Client and server disallow multipart -msg = zmsg_new (); -zmsg_addstr (msg, "One"); -zmsg_addstr (msg, "Two"); -rc = zmsg_send (&msg, client); -assert (rc == \-1); -assert (zmsg_size (msg) == 2); -rc = zmsg_send (&msg, server); -assert (rc == \-1); -assert (zmsg_size (msg) == 2); -zmsg_destroy (&msg); - -zsock_destroy (&client); -zsock_destroy (&server); -#endif -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zpoller.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zpoller.3 deleted file mode 100644 index 33e0170d5e..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zpoller.3 +++ /dev/null @@ -1,216 +0,0 @@ -'\" t -.\" Title: zpoller -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZPOLLER" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zpoller \- trivial socket poller class -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// Create new poller, specifying zero or more readers\&. The list of -// readers ends in a NULL\&. Each reader can be a zsock_t instance, a -// zactor_t instance, a libzmq socket (void *), or a file handle\&. -CZMQ_EXPORT zpoller_t * - zpoller_new (void *reader, \&.\&.\&.); - -// Destroy a poller -CZMQ_EXPORT void - zpoller_destroy (zpoller_t **self_p); - -// Add a reader to be polled\&. Returns 0 if OK, \-1 on failure\&. The reader may -// be a libzmq void * socket, a zsock_t instance, or a zactor_t instance\&. -CZMQ_EXPORT int - zpoller_add (zpoller_t *self, void *reader); - -// Remove a reader from the poller; returns 0 if OK, \-1 on failure\&. The reader -// must have been passed during construction, or in an zpoller_add () call\&. -CZMQ_EXPORT int - zpoller_remove (zpoller_t *self, void *reader); - -// By default the poller stops if the process receives a SIGINT or SIGTERM -// signal\&. This makes it impossible to shut\-down message based architectures -// like zactors\&. This method lets you switch off break handling\&. The default -// nonstop setting is off (false)\&. -CZMQ_EXPORT void - zpoller_set_nonstop (zpoller_t *self, bool nonstop); - -// Poll the registered readers for I/O, return first reader that has input\&. -// The reader will be a libzmq void * socket, or a zsock_t or zactor_t -// instance as specified in zpoller_new/zpoller_add\&. The timeout should be -// zero or greater, or \-1 to wait indefinitely\&. Socket priority is defined -// by their order in the poll list\&. If you need a balanced poll, use the low -// level zmq_poll method directly\&. If the poll call was interrupted (SIGINT), -// or the ZMQ context was destroyed, or the timeout expired, returns NULL\&. -// You can test the actual exit condition by calling zpoller_expired () and -// zpoller_terminated ()\&. The timeout is in msec\&. -CZMQ_EXPORT void * - zpoller_wait (zpoller_t *self, int timeout); - -// Return true if the last zpoller_wait () call ended because the timeout -// expired, without any error\&. -CZMQ_EXPORT bool - zpoller_expired (zpoller_t *self); - -// Return true if the last zpoller_wait () call ended because the process -// was interrupted, or the parent context was destroyed\&. -CZMQ_EXPORT bool - zpoller_terminated (zpoller_t *self); - -// Self test of this class\&. -CZMQ_EXPORT void - zpoller_test (bool verbose); - -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zpoller\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -The zpoller class provides a minimalist interface to ZeroMQ\(cqs zmq_poll API, for the very common case of reading from a number of sockets\&. It does not provide polling for output, nor polling on file handles\&. If you need either of these, use the zmq_poll API directly\&. -.sp -The class implements the poller using the zmq_poller API if that exists, else does the work itself\&. -.SH "EXAMPLE" -.PP -\fBFrom zpoller_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Create a few sockets -zsock_t *vent = zsock_new (ZMQ_PUSH); -assert (vent); -int port_nbr = zsock_bind (vent, "tcp://127\&.0\&.0\&.1:*"); -assert (port_nbr != \-1); -zsock_t *sink = zsock_new (ZMQ_PULL); -assert (sink); -int rc = zsock_connect (sink, "tcp://127\&.0\&.0\&.1:%d", port_nbr); -assert (rc != \-1); -zsock_t *bowl = zsock_new (ZMQ_PULL); -assert (bowl); -zsock_t *dish = zsock_new (ZMQ_PULL); -assert (dish); - -// Set up poller -zpoller_t *poller = zpoller_new (bowl, dish, NULL); -assert (poller); - -// Add a reader to the existing poller -rc = zpoller_add (poller, sink); -assert (rc == 0); - -zstr_send (vent, "Hello, World"); - -// We expect a message only on the sink -zsock_t *which = (zsock_t *) zpoller_wait (poller, \-1); -assert (which == sink); -assert (zpoller_expired (poller) == false); -assert (zpoller_terminated (poller) == false); -char *message = zstr_recv (which); -assert (streq (message, "Hello, World")); -zstr_free (&message); - -// Stop polling reader -rc = zpoller_remove (poller, sink); -assert (rc == 0); - -// Check we can poll an FD -rc = zsock_connect (bowl, "tcp://127\&.0\&.0\&.1:%d", port_nbr); -assert (rc != \-1); -SOCKET fd = zsock_fd (bowl); -rc = zpoller_add (poller, (void *) &fd); -assert (rc != \-1); -zstr_send (vent, "Hello again, world"); -assert (zpoller_wait (poller, 500) == &fd); - -// Check zpoller_set_nonstop () -zsys_interrupted = 1; -zpoller_wait (poller, 0); -assert (zpoller_terminated (poller)); -zpoller_set_nonstop (poller, true); -zpoller_wait (poller, 0); -assert (!zpoller_terminated (poller)); -zsys_interrupted = 0; - -zpoller_destroy (&poller); -zsock_destroy (&vent); -zsock_destroy (&sink); -zsock_destroy (&bowl); -zsock_destroy (&dish); - -#ifdef ZMQ_SERVER -// Check thread safe sockets -zpoller_destroy (&poller); -zsock_t *client = zsock_new (ZMQ_CLIENT); -assert (client); -zsock_t *server = zsock_new (ZMQ_SERVER); -assert (server); -poller = zpoller_new (client, server, NULL); -assert (poller); -port_nbr = zsock_bind (server, "tcp://127\&.0\&.0\&.1:*"); -assert (port_nbr != \-1); -rc = zsock_connect (client, "tcp://127\&.0\&.0\&.1:%d", port_nbr); -assert (rc != \-1); - -zstr_send (client, "Hello, World"); - -// We expect a message only on the server -which = (zsock_t *) zpoller_wait (poller, \-1); -assert (which == server); -assert (zpoller_expired (poller) == false); -assert (zpoller_terminated (poller) == false); -message = zstr_recv (which); -assert (streq (message, "Hello, World")); -zstr_free (&message); - -zpoller_destroy (&poller); -zsock_destroy (&client); -zsock_destroy (&server); -#endif -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zproc.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zproc.3 deleted file mode 100644 index 9bfcfa9c84..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zproc.3 +++ /dev/null @@ -1,208 +0,0 @@ -'\" t -.\" Title: zproc -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZPROC" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zproc \- process configuration and status -.SH "SYNOPSIS" -.sp -.nf -// This is a draft class, and may change without notice\&. It is disabled in -// stable builds by default\&. If you use this in applications, please ask -// for it to be pushed to stable state\&. Use \-\-enable\-drafts to enable\&. -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Returns CZMQ version as a single 6\-digit integer encoding the major -// version (x 10000), the minor version (x 100) and the patch\&. -CZMQ_EXPORT int - zproc_czmq_version (void); - -// *** Draft method, for development use, may change without warning *** -// Returns true if the process received a SIGINT or SIGTERM signal\&. -// It is good practice to use this method to exit any infinite loop -// processing messages\&. -CZMQ_EXPORT bool - zproc_interrupted (void); - -// *** Draft method, for development use, may change without warning *** -// Returns true if the underlying libzmq supports CURVE security\&. -CZMQ_EXPORT bool - zproc_has_curve (void); - -// *** Draft method, for development use, may change without warning *** -// Return current host name, for use in public tcp:// endpoints\&. -// If the host name is not resolvable, returns NULL\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zproc_hostname (void); - -// *** Draft method, for development use, may change without warning *** -// Move the current process into the background\&. The precise effect -// depends on the operating system\&. On POSIX boxes, moves to a specified -// working directory (if specified), closes all file handles, reopens -// stdin, stdout, and stderr to the null device, and sets the process to -// ignore SIGHUP\&. On Windows, does nothing\&. Returns 0 if OK, \-1 if there -// was an error\&. -CZMQ_EXPORT void - zproc_daemonize (const char *workdir); - -// *** Draft method, for development use, may change without warning *** -// Drop the process ID into the lockfile, with exclusive lock, and -// switch the process to the specified group and/or user\&. Any of the -// arguments may be null, indicating a no\-op\&. Returns 0 on success, -// \-1 on failure\&. Note if you combine this with zsys_daemonize, run -// after, not before that method, or the lockfile will hold the wrong -// process ID\&. -CZMQ_EXPORT void - zproc_run_as (const char *lockfile, const char *group, const char *user); - -// *** Draft method, for development use, may change without warning *** -// Configure the number of I/O threads that ZeroMQ will use\&. A good -// rule of thumb is one thread per gigabit of traffic in or out\&. The -// default is 1, sufficient for most applications\&. If the environment -// variable ZSYS_IO_THREADS is defined, that provides the default\&. -// Note that this method is valid only before any socket is created\&. -CZMQ_EXPORT void - zproc_set_io_threads (size_t io_threads); - -// *** Draft method, for development use, may change without warning *** -// Configure the number of sockets that ZeroMQ will allow\&. The default -// is 1024\&. The actual limit depends on the system, and you can query it -// by using zsys_socket_limit ()\&. A value of zero means "maximum"\&. -// Note that this method is valid only before any socket is created\&. -CZMQ_EXPORT void - zproc_set_max_sockets (size_t max_sockets); - -// *** Draft method, for development use, may change without warning *** -// Set network interface name to use for broadcasts, particularly zbeacon\&. -// This lets the interface be configured for test environments where required\&. -// For example, on Mac OS X, zbeacon cannot bind to 255\&.255\&.255\&.255 which is -// the default when there is no specified interface\&. If the environment -// variable ZSYS_INTERFACE is set, use that as the default interface name\&. -// Setting the interface to "*" means "use all available interfaces"\&. -CZMQ_EXPORT void - zproc_set_biface (const char *value); - -// *** Draft method, for development use, may change without warning *** -// Return network interface to use for broadcasts, or "" if none was set\&. -CZMQ_EXPORT const char * - zproc_biface (void); - -// *** Draft method, for development use, may change without warning *** -// Set log identity, which is a string that prefixes all log messages sent -// by this process\&. The log identity defaults to the environment variable -// ZSYS_LOGIDENT, if that is set\&. -CZMQ_EXPORT void - zproc_set_log_ident (const char *value); - -// *** Draft method, for development use, may change without warning *** -// Sends log output to a PUB socket bound to the specified endpoint\&. To -// collect such log output, create a SUB socket, subscribe to the traffic -// you care about, and connect to the endpoint\&. Log traffic is sent as a -// single string frame, in the same format as when sent to stdout\&. The -// log system supports a single sender; multiple calls to this method will -// bind the same sender to multiple endpoints\&. To disable the sender, call -// this method with a null argument\&. -CZMQ_EXPORT void - zproc_set_log_sender (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Enable or disable logging to the system facility (syslog on POSIX boxes, -// event log on Windows)\&. By default this is disabled\&. -CZMQ_EXPORT void - zproc_set_log_system (bool logsystem); - -// *** Draft method, for development use, may change without warning *** -// Log error condition \- highest priority -CZMQ_EXPORT void - zproc_log_error (const char *format, \&.\&.\&.) CHECK_PRINTF (1); - -// *** Draft method, for development use, may change without warning *** -// Log warning condition \- high priority -CZMQ_EXPORT void - zproc_log_warning (const char *format, \&.\&.\&.) CHECK_PRINTF (1); - -// *** Draft method, for development use, may change without warning *** -// Log normal, but significant, condition \- normal priority -CZMQ_EXPORT void - zproc_log_notice (const char *format, \&.\&.\&.) CHECK_PRINTF (1); - -// *** Draft method, for development use, may change without warning *** -// Log informational message \- low priority -CZMQ_EXPORT void - zproc_log_info (const char *format, \&.\&.\&.) CHECK_PRINTF (1); - -// *** Draft method, for development use, may change without warning *** -// Log debug\-level message \- lowest priority -CZMQ_EXPORT void - zproc_log_debug (const char *format, \&.\&.\&.) CHECK_PRINTF (1); - -// *** Draft method, for development use, may change without warning *** -// Self test of this class\&. -CZMQ_EXPORT void - zproc_test (bool verbose); - -#endif // CZMQ_BUILD_DRAFT_API -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zproc\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -zproc \- process configuration and status -.sp -Please add \fI@discuss\fR section in \fI\&./\&.\&./src/zproc\&.c\fR\&. -.SH "EXAMPLE" -.PP -\fBFrom zproc_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -Please add \*(Aq@selftest\*(Aq section in \*(Aq\&./\&.\&./src/zproc\&.c\*(Aq\&. -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zproxy.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zproxy.3 deleted file mode 100644 index 037d3da6bb..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zproxy.3 +++ /dev/null @@ -1,402 +0,0 @@ -'\" t -.\" Title: zproxy -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZPROXY" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zproxy \- run a steerable proxy in the background -.SH "SYNOPSIS" -.sp -.nf -// Create new zproxy actor instance\&. The proxy switches messages between -// a frontend socket and a backend socket; use the FRONTEND and BACKEND -// commands to configure these: -// -// zactor_t *proxy = zactor_new (zproxy, NULL); -// -// Destroy zproxy instance\&. This destroys the two sockets and stops any -// message flow between them: -// -// zactor_destroy (&proxy); -// -// Note that all zproxy commands are synchronous, so your application always -// waits for a signal from the actor after each command\&. -// -// Enable verbose logging of commands and activity: -// -// zstr_send (proxy, "VERBOSE"); -// zsock_wait (proxy); -// -// Specify frontend socket type \-\- see zsock_type_str () \-\- and attach to -// endpoints, see zsock_attach ()\&. Note that a proxy socket is always -// serverish: -// -// zstr_sendx (proxy, "FRONTEND", "XSUB", endpoints, NULL); -// zsock_wait (proxy); -// -// Specify backend socket type \-\- see zsock_type_str () \-\- and attach to -// endpoints, see zsock_attach ()\&. Note that a proxy socket is always -// serverish: -// -// zstr_sendx (proxy, "BACKEND", "XPUB", endpoints, NULL); -// zsock_wait (proxy); -// -// Capture all proxied messages; these are delivered to the application -// via an inproc PULL socket that you have already bound to the specified -// endpoint: -// -// zstr_sendx (proxy, "CAPTURE", endpoint, NULL); -// zsock_wait (proxy); -// -// Pause the proxy\&. A paused proxy will cease processing messages, causing -// them to be queued up and potentially hit the high\-water mark on the -// frontend or backend socket, causing messages to be dropped, or writing -// applications to block: -// -// zstr_sendx (proxy, "PAUSE", NULL); -// zsock_wait (proxy); -// -// Resume the proxy\&. Note that the proxy starts automatically as soon as it -// has a properly attached frontend and backend socket: -// -// zstr_sendx (proxy, "RESUME", NULL); -// zsock_wait (proxy); -// -// Configure an authentication domain for the "FRONTEND" or "BACKEND" proxy -// socket \-\- see zsock_set_zap_domain ()\&. Call before binding socket: -// -// zstr_sendx (proxy, "DOMAIN", "FRONTEND", "global", NULL); -// zsock_wait (proxy); -// -// Configure PLAIN authentication for the "FRONTEND" or "BACKEND" proxy -// socket \-\- see zsock_set_plain_server ()\&. Call before binding socket: -// -// zstr_sendx (proxy, "PLAIN", "BACKEND", NULL); -// zsock_wait (proxy); -// -// Configure CURVE authentication for the "FRONTEND" or "BACKEND" proxy -// socket \-\- see zsock_set_curve_server () \-\- specifying both the public and -// secret keys of a certificate as Z85 armored strings \-\- see -// zcert_public_txt () and zcert_secret_txt ()\&. Call before binding socket: -// -// zstr_sendx (proxy, "CURVE", "FRONTEND", public_txt, secret_txt, NULL); -// zsock_wait (proxy); -// -// This is the zproxy constructor as a zactor_fn; the argument is a -// character string specifying frontend and backend socket types as two -// uppercase strings separated by a hyphen: -CZMQ_EXPORT void - zproxy (zsock_t *pipe, void *unused); - -// Selftest -CZMQ_EXPORT void - zproxy_test (bool verbose); -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zproxy\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -A zproxy actor switches messages between a frontend and a backend socket\&. It acts much like the zmq_proxy_steerable method, though it makes benefit of CZMQ\(cqs facilities, to be somewhat simpler to set\-up\&. -.sp -This class replaces zproxy_v2, and is meant for applications that use the CZMQ v3 API (meaning, zsock)\&. -.SH "EXAMPLE" -.PP -\fBFrom zproxy_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Create and configure our proxy -zactor_t *proxy = zactor_new (zproxy, NULL); -assert (proxy); -if (verbose) { - zstr_sendx (proxy, "VERBOSE", NULL); - zsock_wait (proxy); -} -zstr_sendx (proxy, "FRONTEND", "PULL", "inproc://frontend", NULL); -zsock_wait (proxy); -zstr_sendx (proxy, "BACKEND", "PUSH", "inproc://backend", NULL); -zsock_wait (proxy); - -// Connect application sockets to proxy -zsock_t *faucet = zsock_new_push (">inproc://frontend"); -assert (faucet); -zsock_t *sink = zsock_new_pull (">inproc://backend"); -assert (sink); - -// Send some messages and check they arrived -char *hello, *world; -zstr_sendx (faucet, "Hello", "World", NULL); -zstr_recvx (sink, &hello, &world, NULL); -assert (streq (hello, "Hello")); -assert (streq (world, "World")); -zstr_free (&hello); -zstr_free (&world); - -// Test pause/resume functionality -zstr_sendx (proxy, "PAUSE", NULL); -zsock_wait (proxy); -zstr_sendx (faucet, "Hello", "World", NULL); -zsock_set_rcvtimeo (sink, 100); -zstr_recvx (sink, &hello, &world, NULL); -assert (!hello && !world); - -zstr_sendx (proxy, "RESUME", NULL); -zsock_wait (proxy); -zstr_recvx (sink, &hello, &world, NULL); -assert (streq (hello, "Hello")); -assert (streq (world, "World")); -zstr_free (&hello); -zstr_free (&world); - -// Test capture functionality -zsock_t *capture = zsock_new_pull ("inproc://capture"); -assert (capture); - -// Switch on capturing, check that it works -zstr_sendx (proxy, "CAPTURE", "inproc://capture", NULL); -zsock_wait (proxy); -zstr_sendx (faucet, "Hello", "World", NULL); -zstr_recvx (sink, &hello, &world, NULL); -assert (streq (hello, "Hello")); -assert (streq (world, "World")); -zstr_free (&hello); -zstr_free (&world); - -zstr_recvx (capture, &hello, &world, NULL); -assert (streq (hello, "Hello")); -assert (streq (world, "World")); -zstr_free (&hello); -zstr_free (&world); - -zsock_destroy (&faucet); -zsock_destroy (&sink); -zsock_destroy (&capture); -zactor_destroy (&proxy); - -// Test socket creation dependency -proxy = zactor_new (zproxy, NULL); -assert (proxy); - -sink = zsock_new_sub (">ipc://backend", "whatever"); -assert (sink); - -zstr_sendx (proxy, "BACKEND", "XPUB", "ipc://backend", NULL); -zsock_wait (proxy); - -zsock_destroy(&sink); -zactor_destroy(&proxy); - -#if (ZMQ_VERSION_MAJOR == 4) -// Test authentication functionality -# define TESTDIR "\&.test_zproxy" - -// Create temporary directory for test files -zsys_dir_create (TESTDIR); - -char *frontend = NULL; -char *backend = NULL; - -// Check there\*(Aqs no authentication -s_create_test_sockets (&proxy, &faucet, &sink, verbose); -s_bind_test_sockets (proxy, &frontend, &backend); -bool success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose); -assert (success); - -// Install the authenticator -zactor_t *auth = zactor_new (zauth, NULL); -assert (auth); -if (verbose) { - zstr_sendx (auth, "VERBOSE", NULL); - zsock_wait (auth); -} - -// Check there\*(Aqs no authentication on a default NULL server -s_bind_test_sockets (proxy, &frontend, &backend); -success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose); -assert (success); - -// When we set a domain on the server, we switch on authentication -// for NULL sockets, but with no policies, the client connection -// will be allowed\&. -zstr_sendx (proxy, "DOMAIN", "FRONTEND", "global", NULL); -zsock_wait (proxy); -s_bind_test_sockets (proxy, &frontend, &backend); -success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose); -assert (success); - -// Blacklist 127\&.0\&.0\&.1, connection should fail -zstr_sendx (proxy, "DOMAIN", "FRONTEND", "global", NULL); -zsock_wait (proxy); -s_bind_test_sockets (proxy, &frontend, &backend); -zstr_sendx (auth, "DENY", "127\&.0\&.0\&.1", NULL); -zsock_wait (auth); -success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose); -assert (!success); - -// Whitelist our address, which overrides the blacklist -zstr_sendx (proxy, "DOMAIN", "FRONTEND", "global", NULL); -zsock_wait (proxy); -zstr_sendx (proxy, "DOMAIN", "BACKEND", "global", NULL); -zsock_wait (proxy); -s_bind_test_sockets (proxy, &frontend, &backend); -zstr_sendx (auth, "ALLOW", "127\&.0\&.0\&.1", NULL); -zsock_wait (auth); -success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose); -assert (success); - -// Try PLAIN authentication - -// Test negative case (no server\-side passwords defined) -zstr_sendx (proxy, "PLAIN", "FRONTEND", NULL); -zsock_wait (proxy); -s_bind_test_sockets (proxy, &frontend, &backend); -zsock_set_plain_username (faucet, "admin"); -zsock_set_plain_password (faucet, "Password"); -success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose); -assert (!success); - -// Test positive case (server\-side passwords defined) -FILE *password = fopen (TESTDIR "/password\-file", "w"); -assert (password); -fprintf (password, "admin=Password\en"); -fclose (password); -zstr_sendx (proxy, "PLAIN", "FRONTEND", NULL); -zsock_wait (proxy); -zstr_sendx (proxy, "PLAIN", "BACKEND", NULL); -zsock_wait (proxy); -s_bind_test_sockets (proxy, &frontend, &backend); -zsock_set_plain_username (faucet, "admin"); -zsock_set_plain_password (faucet, "Password"); -zsock_set_plain_username (sink, "admin"); -zsock_set_plain_password (sink, "Password"); -zstr_sendx (auth, "PLAIN", TESTDIR "/password\-file", NULL); -zsock_wait (auth); -success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose); -assert (success); - -// Test negative case (bad client password) -zstr_sendx (proxy, "PLAIN", "FRONTEND", NULL); -zsock_wait (proxy); -s_bind_test_sockets (proxy, &frontend, &backend); -zsock_set_plain_username (faucet, "admin"); -zsock_set_plain_password (faucet, "Bogus"); -success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose); -assert (!success); - -if (zsys_has_curve ()) { - // We\*(Aqll create two new certificates and save the client public - // certificate on disk - zcert_t *server_cert = zcert_new (); - assert (server_cert); - zcert_t *client_cert = zcert_new (); - assert (client_cert); - const char *public_key = zcert_public_txt (server_cert); - const char *secret_key = zcert_secret_txt (server_cert); - - // Try CURVE authentication - - // Test without setting\-up any authentication - zstr_sendx (proxy, "CURVE", "FRONTEND", public_key, secret_key, NULL); - zsock_wait (proxy); - s_bind_test_sockets (proxy, &frontend, &backend); - zcert_apply (client_cert, faucet); - zsock_set_curve_serverkey (faucet, public_key); - success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose); - assert (!success); - - // Test CURVE_ALLOW_ANY - zstr_sendx (proxy, "CURVE", "FRONTEND", public_key, secret_key, NULL); - zsock_wait (proxy); - s_bind_test_sockets (proxy, &frontend, &backend); - zcert_apply (client_cert, faucet); - zsock_set_curve_serverkey (faucet, public_key); - zstr_sendx (auth, "CURVE", CURVE_ALLOW_ANY, NULL); - zsock_wait (auth); - success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose); - assert (success); - - // Test with client certificate file in authentication folder - zstr_sendx (proxy, "CURVE", "FRONTEND", public_key, secret_key, NULL); - zsock_wait (proxy); - zstr_sendx (proxy, "CURVE", "BACKEND", public_key, secret_key, NULL); - zsock_wait (proxy); - s_bind_test_sockets (proxy, &frontend, &backend); - zcert_apply (client_cert, faucet); - zsock_set_curve_serverkey (faucet, public_key); - zcert_apply (client_cert, sink); - zsock_set_curve_serverkey (sink, public_key); - zcert_save_public (client_cert, TESTDIR "/mycert\&.txt"); - zstr_sendx (auth, "CURVE", TESTDIR, NULL); - zsock_wait (auth); - success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose); - assert (success); - - zcert_destroy (&server_cert); - zcert_destroy (&client_cert); -} - -// Remove the authenticator and check a normal connection works -zactor_destroy (&auth); -s_bind_test_sockets (proxy, &frontend, &backend); -success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose); -assert (success); - -// Cleanup -zsock_destroy (&faucet); -zsock_destroy (&sink); -zactor_destroy (&proxy); -zstr_free (&frontend); -zstr_free (&backend); - -// Delete temporary directory and test files -zsys_file_delete (TESTDIR "/password\-file"); -zsys_file_delete (TESTDIR "/mycert\&.txt"); -zsys_dir_delete (TESTDIR); -#endif -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zrex.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zrex.3 deleted file mode 100644 index 99c7337d40..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zrex.3 +++ /dev/null @@ -1,199 +0,0 @@ -'\" t -.\" Title: zrex -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZREX" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zrex \- work with regular expressions -.SH "SYNOPSIS" -.sp -.nf -// Constructor\&. Optionally, sets an expression against which we can match -// text and capture hits\&. If there is an error in the expression, reports -// zrex_valid() as false and provides the error in zrex_strerror()\&. If you -// set a pattern, you can call zrex_matches() to test it against text\&. -CZMQ_EXPORT zrex_t * - zrex_new (const char *expression); - -// Destructor -CZMQ_EXPORT void - zrex_destroy (zrex_t **self_p); - -// Return true if the expression was valid and compiled without errors\&. -CZMQ_EXPORT bool - zrex_valid (zrex_t *self); - -// Return the error message generated during compilation of the expression\&. -CZMQ_EXPORT const char * - zrex_strerror (zrex_t *self); - -// Returns true if the text matches the previously compiled expression\&. -// Use this method to compare one expression against many strings\&. -CZMQ_EXPORT bool - zrex_matches (zrex_t *self, const char *text); - -// Returns true if the text matches the supplied expression\&. Use this -// method to compare one string against several expressions\&. -CZMQ_EXPORT bool - zrex_eq (zrex_t *self, const char *text, const char *expression); - -// Returns number of hits from last zrex_matches or zrex_eq\&. If the text -// matched, returns 1 plus the number of capture groups\&. If the text did -// not match, returns zero\&. To retrieve individual capture groups, call -// zrex_hit ()\&. -CZMQ_EXPORT int - zrex_hits (zrex_t *self); - -// Returns the Nth capture group from the last expression match, where -// N is 0 to the value returned by zrex_hits()\&. Capture group 0 is the -// whole matching string\&. Sequence 1 is the first capture group, if any, -// and so on\&. -CZMQ_EXPORT const char * - zrex_hit (zrex_t *self, uint index); - -// Fetches hits into string variables provided by caller; this makes for -// nicer code than accessing hits by index\&. Caller should not modify nor -// free the returned values\&. Returns number of strings returned\&. This -// method starts at hit 1, i\&.e\&. first capture group, as hit 0 is always -// the original matched string\&. -CZMQ_EXPORT int - zrex_fetch (zrex_t *self, const char **string_p, \&.\&.\&.); - -// Self test of this class -CZMQ_EXPORT void - zrex_test (bool verbose); -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zrex\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -Wraps a very simple regular expression library (SLRE) as a CZMQ class\&. Supports this syntax: -.sp -.if n \{\ -.RS 4 -.\} -.nf -^ Match beginning of a buffer -$ Match end of a buffer -() Grouping and substring capturing -[\&.\&.\&.] Match any character from set -[^\&.\&.\&.] Match any character but ones from set -\&. Match any character -\es Match whitespace -\eS Match non\-whitespace -\ed Match decimal digit -\eD Match non decimal digit -\ea Match alphabetic character -\eA Match non\-alphabetic character -\ew Match alphanumeric character -\eW Match non\-alphanumeric character -\er Match carriage return -\en Match newline -+ Match one or more times (greedy) -+? Match one or more times (non\-greedy) -* Match zero or more times (greedy) -*? Match zero or more times (non\-greedy) -? Match zero or once -\exDD Match byte with hex value 0xDD -\emeta Match one of the meta character: ^$()\&.[*+?\e -.fi -.if n \{\ -.RE -.\} -.sp -Please add \fI@discuss\fR section in \fI\&./\&.\&./src/zrex\&.c\fR\&. -.SH "EXAMPLE" -.PP -\fBFrom zrex_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// This shows the pattern of matching many lines to a single pattern -zrex_t *rex = zrex_new ("\e\ed+\-\e\ed+\-\e\ed+"); -assert (rex); -assert (zrex_valid (rex)); -bool matches = zrex_matches (rex, "123\-456\-789"); -assert (matches); -assert (zrex_hits (rex) == 1); -assert (streq (zrex_hit (rex, 0), "123\-456\-789")); -assert (zrex_hit (rex, 1) == NULL); -zrex_destroy (&rex); - -// Here we pick out hits using capture groups -rex = zrex_new ("(\e\ed+)\-(\e\ed+)\-(\e\ed+)"); -assert (rex); -assert (zrex_valid (rex)); -matches = zrex_matches (rex, "123\-456\-ABC"); -assert (!matches); -matches = zrex_matches (rex, "123\-456\-789"); -assert (matches); -assert (zrex_hits (rex) == 4); -assert (streq (zrex_hit (rex, 0), "123\-456\-789")); -assert (streq (zrex_hit (rex, 1), "123")); -assert (streq (zrex_hit (rex, 2), "456")); -assert (streq (zrex_hit (rex, 3), "789")); -zrex_destroy (&rex); - -// This shows the pattern of matching one line against many -// patterns and then handling the case when it hits -rex = zrex_new (NULL); // No initial pattern -assert (rex); -char *input = "Mechanism: CURVE"; -matches = zrex_eq (rex, input, "Version: (\&.+)"); -assert (!matches); -assert (zrex_hits (rex) == 0); -matches = zrex_eq (rex, input, "Mechanism: (\&.+)"); -assert (matches); -assert (zrex_hits (rex) == 2); -const char *mechanism; -zrex_fetch (rex, &mechanism, NULL); -assert (streq (zrex_hit (rex, 1), "CURVE")); -assert (streq (mechanism, "CURVE")); -zrex_destroy (&rex); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zsock.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zsock.3 deleted file mode 100644 index fc4a7e8b44..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zsock.3 +++ /dev/null @@ -1,1469 +0,0 @@ -'\" t -.\" Title: zsock -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZSOCK" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zsock \- high\-level socket API that hides libzmq contexts and sockets -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// This class has draft methods, which may change over time\&. They are not -// in stable releases, by default\&. Use \-\-enable\-drafts to enable\&. -// Create a new socket\&. Returns the new socket, or NULL if the new socket -// could not be created\&. Note that the symbol zsock_new (and other -// constructors/destructors for zsock) are redirected to the *_checked -// variant, enabling intelligent socket leak detection\&. This can have -// performance implications if you use a LOT of sockets\&. To turn off this -// redirection behaviour, define ZSOCK_NOCHECK\&. -CZMQ_EXPORT zsock_t * - zsock_new (int type); - -// Create a PUB socket\&. Default action is bind\&. -CZMQ_EXPORT zsock_t * - zsock_new_pub (const char *endpoint); - -// Create a SUB socket, and optionally subscribe to some prefix string\&. Default -// action is connect\&. -CZMQ_EXPORT zsock_t * - zsock_new_sub (const char *endpoint, const char *subscribe); - -// Create a REQ socket\&. Default action is connect\&. -CZMQ_EXPORT zsock_t * - zsock_new_req (const char *endpoint); - -// Create a REP socket\&. Default action is bind\&. -CZMQ_EXPORT zsock_t * - zsock_new_rep (const char *endpoint); - -// Create a DEALER socket\&. Default action is connect\&. -CZMQ_EXPORT zsock_t * - zsock_new_dealer (const char *endpoint); - -// Create a ROUTER socket\&. Default action is bind\&. -CZMQ_EXPORT zsock_t * - zsock_new_router (const char *endpoint); - -// Create a PUSH socket\&. Default action is connect\&. -CZMQ_EXPORT zsock_t * - zsock_new_push (const char *endpoint); - -// Create a PULL socket\&. Default action is bind\&. -CZMQ_EXPORT zsock_t * - zsock_new_pull (const char *endpoint); - -// Create an XPUB socket\&. Default action is bind\&. -CZMQ_EXPORT zsock_t * - zsock_new_xpub (const char *endpoint); - -// Create an XSUB socket\&. Default action is connect\&. -CZMQ_EXPORT zsock_t * - zsock_new_xsub (const char *endpoint); - -// Create a PAIR socket\&. Default action is connect\&. -CZMQ_EXPORT zsock_t * - zsock_new_pair (const char *endpoint); - -// Create a STREAM socket\&. Default action is connect\&. -CZMQ_EXPORT zsock_t * - zsock_new_stream (const char *endpoint); - -// Destroy the socket\&. You must use this for any socket created via the -// zsock_new method\&. -CZMQ_EXPORT void - zsock_destroy (zsock_t **self_p); - -// Bind a socket to a formatted endpoint\&. For tcp:// endpoints, supports -// ephemeral ports, if you specify the port number as "*"\&. By default -// zsock uses the IANA designated range from C000 (49152) to FFFF (65535)\&. -// To override this range, follow the "*" with "[first\-last]"\&. Either or -// both first and last may be empty\&. To bind to a random port within the -// range, use "!" in place of "*"\&. -// -// Examples: -// tcp://127\&.0\&.0\&.1:* bind to first free port from C000 up -// tcp://127\&.0\&.0\&.1:! bind to random port from C000 to FFFF -// tcp://127\&.0\&.0\&.1:*[60000\-] bind to first free port from 60000 up -// tcp://127\&.0\&.0\&.1:![\-60000] bind to random port from C000 to 60000 -// tcp://127\&.0\&.0\&.1:![55000\-55999] -// bind to random port from 55000 to 55999 -// -// On success, returns the actual port number used, for tcp:// endpoints, -// and 0 for other transports\&. On failure, returns \-1\&. Note that when using -// ephemeral ports, a port may be reused by different services without -// clients being aware\&. Protocols that run on ephemeral ports should take -// this into account\&. -CZMQ_EXPORT int - zsock_bind (zsock_t *self, const char *format, \&.\&.\&.) CHECK_PRINTF (2); - -// Returns last bound endpoint, if any\&. -CZMQ_EXPORT const char * - zsock_endpoint (zsock_t *self); - -// Unbind a socket from a formatted endpoint\&. -// Returns 0 if OK, \-1 if the endpoint was invalid or the function -// isn\*(Aqt supported\&. -CZMQ_EXPORT int - zsock_unbind (zsock_t *self, const char *format, \&.\&.\&.) CHECK_PRINTF (2); - -// Connect a socket to a formatted endpoint -// Returns 0 if OK, \-1 if the endpoint was invalid\&. -CZMQ_EXPORT int - zsock_connect (zsock_t *self, const char *format, \&.\&.\&.) CHECK_PRINTF (2); - -// Disconnect a socket from a formatted endpoint -// Returns 0 if OK, \-1 if the endpoint was invalid or the function -// isn\*(Aqt supported\&. -CZMQ_EXPORT int - zsock_disconnect (zsock_t *self, const char *format, \&.\&.\&.) CHECK_PRINTF (2); - -// Attach a socket to zero or more endpoints\&. If endpoints is not null, -// parses as list of ZeroMQ endpoints, separated by commas, and prefixed by -// \*(Aq@\*(Aq (to bind the socket) or \*(Aq>\*(Aq (to connect the socket)\&. Returns 0 if all -// endpoints were valid, or \-1 if there was a syntax error\&. If the endpoint -// does not start with \*(Aq@\*(Aq or \*(Aq>\*(Aq, the serverish argument defines whether -// it is used to bind (serverish = true) or connect (serverish = false)\&. -CZMQ_EXPORT int - zsock_attach (zsock_t *self, const char *endpoints, bool serverish); - -// Returns socket type as printable constant string\&. -CZMQ_EXPORT const char * - zsock_type_str (zsock_t *self); - -// Send a \*(Aqpicture\*(Aq message to the socket (or actor)\&. The picture is a -// string that defines the type of each frame\&. This makes it easy to send -// a complex multiframe message in one call\&. The picture can contain any -// of these characters, each corresponding to one or two arguments: -// -// i = int (signed) -// 1 = uint8_t -// 2 = uint16_t -// 4 = uint32_t -// 8 = uint64_t -// s = char * -// b = byte *, size_t (2 arguments) -// c = zchunk_t * -// f = zframe_t * -// h = zhashx_t * -// U = zuuid_t * -// p = void * (sends the pointer value, only meaningful over inproc) -// m = zmsg_t * (sends all frames in the zmsg) -// z = sends zero\-sized frame (0 arguments) -// u = uint (deprecated) -// -// Note that s, b, c, and f are encoded the same way and the choice is -// offered as a convenience to the sender, which may or may not already -// have data in a zchunk or zframe\&. Does not change or take ownership of -// any arguments\&. Returns 0 if successful, \-1 if sending failed for any -// reason\&. -CZMQ_EXPORT int - zsock_send (void *self, const char *picture, \&.\&.\&.); - -// Send a \*(Aqpicture\*(Aq message to the socket (or actor)\&. This is a va_list -// version of zsock_send (), so please consult its documentation for the -// details\&. -CZMQ_EXPORT int - zsock_vsend (void *self, const char *picture, va_list argptr); - -// Receive a \*(Aqpicture\*(Aq message to the socket (or actor)\&. See zsock_send for -// the format and meaning of the picture\&. Returns the picture elements into -// a series of pointers as provided by the caller: -// -// i = int * (stores signed integer) -// 4 = uint32_t * (stores 32\-bit unsigned integer) -// 8 = uint64_t * (stores 64\-bit unsigned integer) -// s = char ** (allocates new string) -// b = byte **, size_t * (2 arguments) (allocates memory) -// c = zchunk_t ** (creates zchunk) -// f = zframe_t ** (creates zframe) -// U = zuuid_t * (creates a zuuid with the data) -// h = zhashx_t ** (creates zhashx) -// p = void ** (stores pointer) -// m = zmsg_t ** (creates a zmsg with the remaing frames) -// z = null, asserts empty frame (0 arguments) -// u = uint * (stores unsigned integer, deprecated) -// -// Note that zsock_recv creates the returned objects, and the caller must -// destroy them when finished with them\&. The supplied pointers do not need -// to be initialized\&. Returns 0 if successful, or \-1 if it failed to recv -// a message, in which case the pointers are not modified\&. When message -// frames are truncated (a short message), sets return values to zero/null\&. -// If an argument pointer is NULL, does not store any value (skips it)\&. -// An \*(Aqn\*(Aq picture matches an empty frame; if the message does not match, -// the method will return \-1\&. -CZMQ_EXPORT int - zsock_recv (void *self, const char *picture, \&.\&.\&.); - -// Receive a \*(Aqpicture\*(Aq message from the socket (or actor)\&. This is a -// va_list version of zsock_recv (), so please consult its documentation -// for the details\&. -CZMQ_EXPORT int - zsock_vrecv (void *self, const char *picture, va_list argptr); - -// Send a binary encoded \*(Aqpicture\*(Aq message to the socket (or actor)\&. This -// method is similar to zsock_send, except the arguments are encoded in a -// binary format that is compatible with zproto, and is designed to reduce -// memory allocations\&. The pattern argument is a string that defines the -// type of each argument\&. Supports these argument types: -// -// pattern C type zproto type: -// 1 uint8_t type = "number" size = "1" -// 2 uint16_t type = "number" size = "2" -// 4 uint32_t type = "number" size = "3" -// 8 uint64_t type = "number" size = "4" -// s char *, 0\-255 chars type = "string" -// S char *, 0\-2^32\-1 chars type = "longstr" -// c zchunk_t * type = "chunk" -// f zframe_t * type = "frame" -// u zuuid_t * type = "uuid" -// m zmsg_t * type = "msg" -// p void *, sends pointer value, only over inproc -// -// Does not change or take ownership of any arguments\&. Returns 0 if -// successful, \-1 if sending failed for any reason\&. -CZMQ_EXPORT int - zsock_bsend (void *self, const char *picture, \&.\&.\&.); - -// Receive a binary encoded \*(Aqpicture\*(Aq message from the socket (or actor)\&. -// This method is similar to zsock_recv, except the arguments are encoded -// in a binary format that is compatible with zproto, and is designed to -// reduce memory allocations\&. The pattern argument is a string that defines -// the type of each argument\&. See zsock_bsend for the supported argument -// types\&. All arguments must be pointers; this call sets them to point to -// values held on a per\-socket basis\&. -// Note that zsock_brecv creates the returned objects, and the caller must -// destroy them when finished with them\&. The supplied pointers do not need -// to be initialized\&. Returns 0 if successful, or \-1 if it failed to read -// a message\&. -CZMQ_EXPORT int - zsock_brecv (void *self, const char *picture, \&.\&.\&.); - -// Set socket to use unbounded pipes (HWM=0); use this in cases when you are -// totally certain the message volume can fit in memory\&. This method works -// across all versions of ZeroMQ\&. Takes a polymorphic socket reference\&. -CZMQ_EXPORT void - zsock_set_unbounded (void *self); - -// Send a signal over a socket\&. A signal is a short message carrying a -// success/failure code (by convention, 0 means OK)\&. Signals are encoded -// to be distinguishable from "normal" messages\&. Accepts a zsock_t or a -// zactor_t argument, and returns 0 if successful, \-1 if the signal could -// not be sent\&. Takes a polymorphic socket reference\&. -CZMQ_EXPORT int - zsock_signal (void *self, byte status); - -// Wait on a signal\&. Use this to coordinate between threads, over pipe -// pairs\&. Blocks until the signal is received\&. Returns \-1 on error, 0 or -// greater on success\&. Accepts a zsock_t or a zactor_t as argument\&. -// Takes a polymorphic socket reference\&. -CZMQ_EXPORT int - zsock_wait (void *self); - -// If there is a partial message still waiting on the socket, remove and -// discard it\&. This is useful when reading partial messages, to get specific -// message types\&. -CZMQ_EXPORT void - zsock_flush (void *self); - -// Probe the supplied object, and report if it looks like a zsock_t\&. -// Takes a polymorphic socket reference\&. -CZMQ_EXPORT bool - zsock_is (void *self); - -// Probe the supplied reference\&. If it looks like a zsock_t instance, return -// the underlying libzmq socket handle; else if it looks like a file -// descriptor, return NULL; else if it looks like a libzmq socket handle, -// return the supplied value\&. Takes a polymorphic socket reference\&. -CZMQ_EXPORT void * - zsock_resolve (void *self); - -// Get socket option `heartbeat_ivl`\&. -// Available from libzmq 4\&.2\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_heartbeat_ivl (void *self); - -// Set socket option `heartbeat_ivl`\&. -// Available from libzmq 4\&.2\&.0\&. -CZMQ_EXPORT void - zsock_set_heartbeat_ivl (void *self, int heartbeat_ivl); - -// Get socket option `heartbeat_ttl`\&. -// Available from libzmq 4\&.2\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_heartbeat_ttl (void *self); - -// Set socket option `heartbeat_ttl`\&. -// Available from libzmq 4\&.2\&.0\&. -CZMQ_EXPORT void - zsock_set_heartbeat_ttl (void *self, int heartbeat_ttl); - -// Get socket option `heartbeat_timeout`\&. -// Available from libzmq 4\&.2\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_heartbeat_timeout (void *self); - -// Set socket option `heartbeat_timeout`\&. -// Available from libzmq 4\&.2\&.0\&. -CZMQ_EXPORT void - zsock_set_heartbeat_timeout (void *self, int heartbeat_timeout); - -// Get socket option `use_fd`\&. -// Available from libzmq 4\&.2\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_use_fd (void *self); - -// Set socket option `use_fd`\&. -// Available from libzmq 4\&.2\&.0\&. -CZMQ_EXPORT void - zsock_set_use_fd (void *self, int use_fd); - -// Set socket option `xpub_manual`\&. -// Available from libzmq 4\&.2\&.0\&. -CZMQ_EXPORT void - zsock_set_xpub_manual (void *self, int xpub_manual); - -// Set socket option `xpub_welcome_msg`\&. -// Available from libzmq 4\&.2\&.0\&. -CZMQ_EXPORT void - zsock_set_xpub_welcome_msg (void *self, const char *xpub_welcome_msg); - -// Set socket option `stream_notify`\&. -// Available from libzmq 4\&.2\&.0\&. -CZMQ_EXPORT void - zsock_set_stream_notify (void *self, int stream_notify); - -// Get socket option `invert_matching`\&. -// Available from libzmq 4\&.2\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_invert_matching (void *self); - -// Set socket option `invert_matching`\&. -// Available from libzmq 4\&.2\&.0\&. -CZMQ_EXPORT void - zsock_set_invert_matching (void *self, int invert_matching); - -// Set socket option `xpub_verboser`\&. -// Available from libzmq 4\&.2\&.0\&. -CZMQ_EXPORT void - zsock_set_xpub_verboser (void *self, int xpub_verboser); - -// Get socket option `connect_timeout`\&. -// Available from libzmq 4\&.2\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_connect_timeout (void *self); - -// Set socket option `connect_timeout`\&. -// Available from libzmq 4\&.2\&.0\&. -CZMQ_EXPORT void - zsock_set_connect_timeout (void *self, int connect_timeout); - -// Get socket option `tcp_maxrt`\&. -// Available from libzmq 4\&.2\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_tcp_maxrt (void *self); - -// Set socket option `tcp_maxrt`\&. -// Available from libzmq 4\&.2\&.0\&. -CZMQ_EXPORT void - zsock_set_tcp_maxrt (void *self, int tcp_maxrt); - -// Get socket option `thread_safe`\&. -// Available from libzmq 4\&.2\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_thread_safe (void *self); - -// Get socket option `multicast_maxtpdu`\&. -// Available from libzmq 4\&.2\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_multicast_maxtpdu (void *self); - -// Set socket option `multicast_maxtpdu`\&. -// Available from libzmq 4\&.2\&.0\&. -CZMQ_EXPORT void - zsock_set_multicast_maxtpdu (void *self, int multicast_maxtpdu); - -// Get socket option `vmci_buffer_size`\&. -// Available from libzmq 4\&.2\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_vmci_buffer_size (void *self); - -// Set socket option `vmci_buffer_size`\&. -// Available from libzmq 4\&.2\&.0\&. -CZMQ_EXPORT void - zsock_set_vmci_buffer_size (void *self, int vmci_buffer_size); - -// Get socket option `vmci_buffer_min_size`\&. -// Available from libzmq 4\&.2\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_vmci_buffer_min_size (void *self); - -// Set socket option `vmci_buffer_min_size`\&. -// Available from libzmq 4\&.2\&.0\&. -CZMQ_EXPORT void - zsock_set_vmci_buffer_min_size (void *self, int vmci_buffer_min_size); - -// Get socket option `vmci_buffer_max_size`\&. -// Available from libzmq 4\&.2\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_vmci_buffer_max_size (void *self); - -// Set socket option `vmci_buffer_max_size`\&. -// Available from libzmq 4\&.2\&.0\&. -CZMQ_EXPORT void - zsock_set_vmci_buffer_max_size (void *self, int vmci_buffer_max_size); - -// Get socket option `vmci_connect_timeout`\&. -// Available from libzmq 4\&.2\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_vmci_connect_timeout (void *self); - -// Set socket option `vmci_connect_timeout`\&. -// Available from libzmq 4\&.2\&.0\&. -CZMQ_EXPORT void - zsock_set_vmci_connect_timeout (void *self, int vmci_connect_timeout); - -// Get socket option `tos`\&. -// Available from libzmq 4\&.1\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_tos (void *self); - -// Set socket option `tos`\&. -// Available from libzmq 4\&.1\&.0\&. -CZMQ_EXPORT void - zsock_set_tos (void *self, int tos); - -// Set socket option `router_handover`\&. -// Available from libzmq 4\&.1\&.0\&. -CZMQ_EXPORT void - zsock_set_router_handover (void *self, int router_handover); - -// Set socket option `connect_rid`\&. -// Available from libzmq 4\&.1\&.0\&. -CZMQ_EXPORT void - zsock_set_connect_rid (void *self, const char *connect_rid); - -// Set socket option `connect_rid` from 32\-octet binary -// Available from libzmq 4\&.1\&.0\&. -CZMQ_EXPORT void - zsock_set_connect_rid_bin (void *self, const byte *connect_rid); - -// Get socket option `handshake_ivl`\&. -// Available from libzmq 4\&.1\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_handshake_ivl (void *self); - -// Set socket option `handshake_ivl`\&. -// Available from libzmq 4\&.1\&.0\&. -CZMQ_EXPORT void - zsock_set_handshake_ivl (void *self, int handshake_ivl); - -// Get socket option `socks_proxy`\&. -// Available from libzmq 4\&.1\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zsock_socks_proxy (void *self); - -// Set socket option `socks_proxy`\&. -// Available from libzmq 4\&.1\&.0\&. -CZMQ_EXPORT void - zsock_set_socks_proxy (void *self, const char *socks_proxy); - -// Set socket option `xpub_nodrop`\&. -// Available from libzmq 4\&.1\&.0\&. -CZMQ_EXPORT void - zsock_set_xpub_nodrop (void *self, int xpub_nodrop); - -// Set socket option `router_mandatory`\&. -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_router_mandatory (void *self, int router_mandatory); - -// Set socket option `probe_router`\&. -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_probe_router (void *self, int probe_router); - -// Set socket option `req_relaxed`\&. -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_req_relaxed (void *self, int req_relaxed); - -// Set socket option `req_correlate`\&. -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_req_correlate (void *self, int req_correlate); - -// Set socket option `conflate`\&. -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_conflate (void *self, int conflate); - -// Get socket option `zap_domain`\&. -// Available from libzmq 4\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zsock_zap_domain (void *self); - -// Set socket option `zap_domain`\&. -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_zap_domain (void *self, const char *zap_domain); - -// Get socket option `mechanism`\&. -// Available from libzmq 4\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_mechanism (void *self); - -// Get socket option `plain_server`\&. -// Available from libzmq 4\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_plain_server (void *self); - -// Set socket option `plain_server`\&. -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_plain_server (void *self, int plain_server); - -// Get socket option `plain_username`\&. -// Available from libzmq 4\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zsock_plain_username (void *self); - -// Set socket option `plain_username`\&. -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_plain_username (void *self, const char *plain_username); - -// Get socket option `plain_password`\&. -// Available from libzmq 4\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zsock_plain_password (void *self); - -// Set socket option `plain_password`\&. -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_plain_password (void *self, const char *plain_password); - -// Get socket option `curve_server`\&. -// Available from libzmq 4\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_curve_server (void *self); - -// Set socket option `curve_server`\&. -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_curve_server (void *self, int curve_server); - -// Get socket option `curve_publickey`\&. -// Available from libzmq 4\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zsock_curve_publickey (void *self); - -// Set socket option `curve_publickey`\&. -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_curve_publickey (void *self, const char *curve_publickey); - -// Set socket option `curve_publickey` from 32\-octet binary -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_curve_publickey_bin (void *self, const byte *curve_publickey); - -// Get socket option `curve_secretkey`\&. -// Available from libzmq 4\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zsock_curve_secretkey (void *self); - -// Set socket option `curve_secretkey`\&. -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_curve_secretkey (void *self, const char *curve_secretkey); - -// Set socket option `curve_secretkey` from 32\-octet binary -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_curve_secretkey_bin (void *self, const byte *curve_secretkey); - -// Get socket option `curve_serverkey`\&. -// Available from libzmq 4\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zsock_curve_serverkey (void *self); - -// Set socket option `curve_serverkey`\&. -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_curve_serverkey (void *self, const char *curve_serverkey); - -// Set socket option `curve_serverkey` from 32\-octet binary -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_curve_serverkey_bin (void *self, const byte *curve_serverkey); - -// Get socket option `gssapi_server`\&. -// Available from libzmq 4\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_gssapi_server (void *self); - -// Set socket option `gssapi_server`\&. -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_gssapi_server (void *self, int gssapi_server); - -// Get socket option `gssapi_plaintext`\&. -// Available from libzmq 4\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_gssapi_plaintext (void *self); - -// Set socket option `gssapi_plaintext`\&. -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_gssapi_plaintext (void *self, int gssapi_plaintext); - -// Get socket option `gssapi_principal`\&. -// Available from libzmq 4\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zsock_gssapi_principal (void *self); - -// Set socket option `gssapi_principal`\&. -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_gssapi_principal (void *self, const char *gssapi_principal); - -// Get socket option `gssapi_service_principal`\&. -// Available from libzmq 4\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zsock_gssapi_service_principal (void *self); - -// Set socket option `gssapi_service_principal`\&. -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_gssapi_service_principal (void *self, const char *gssapi_service_principal); - -// Get socket option `ipv6`\&. -// Available from libzmq 4\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_ipv6 (void *self); - -// Set socket option `ipv6`\&. -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_ipv6 (void *self, int ipv6); - -// Get socket option `immediate`\&. -// Available from libzmq 4\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_immediate (void *self); - -// Set socket option `immediate`\&. -// Available from libzmq 4\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_immediate (void *self, int immediate); - -// Get socket option `type`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_type (void *self); - -// Get socket option `sndhwm`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_sndhwm (void *self); - -// Set socket option `sndhwm`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_sndhwm (void *self, int sndhwm); - -// Get socket option `rcvhwm`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_rcvhwm (void *self); - -// Set socket option `rcvhwm`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_rcvhwm (void *self, int rcvhwm); - -// Get socket option `affinity`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_affinity (void *self); - -// Set socket option `affinity`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_affinity (void *self, int affinity); - -// Set socket option `subscribe`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_subscribe (void *self, const char *subscribe); - -// Set socket option `unsubscribe`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_unsubscribe (void *self, const char *unsubscribe); - -// Get socket option `identity`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zsock_identity (void *self); - -// Set socket option `identity`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_identity (void *self, const char *identity); - -// Get socket option `rate`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_rate (void *self); - -// Set socket option `rate`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_rate (void *self, int rate); - -// Get socket option `recovery_ivl`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_recovery_ivl (void *self); - -// Set socket option `recovery_ivl`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_recovery_ivl (void *self, int recovery_ivl); - -// Get socket option `sndbuf`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_sndbuf (void *self); - -// Set socket option `sndbuf`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_sndbuf (void *self, int sndbuf); - -// Get socket option `rcvbuf`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_rcvbuf (void *self); - -// Set socket option `rcvbuf`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_rcvbuf (void *self, int rcvbuf); - -// Get socket option `linger`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_linger (void *self); - -// Set socket option `linger`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_linger (void *self, int linger); - -// Get socket option `reconnect_ivl`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_reconnect_ivl (void *self); - -// Set socket option `reconnect_ivl`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_reconnect_ivl (void *self, int reconnect_ivl); - -// Get socket option `reconnect_ivl_max`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_reconnect_ivl_max (void *self); - -// Set socket option `reconnect_ivl_max`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_reconnect_ivl_max (void *self, int reconnect_ivl_max); - -// Get socket option `backlog`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_backlog (void *self); - -// Set socket option `backlog`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_backlog (void *self, int backlog); - -// Get socket option `maxmsgsize`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_maxmsgsize (void *self); - -// Set socket option `maxmsgsize`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_maxmsgsize (void *self, int maxmsgsize); - -// Get socket option `multicast_hops`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_multicast_hops (void *self); - -// Set socket option `multicast_hops`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_multicast_hops (void *self, int multicast_hops); - -// Get socket option `rcvtimeo`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_rcvtimeo (void *self); - -// Set socket option `rcvtimeo`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_rcvtimeo (void *self, int rcvtimeo); - -// Get socket option `sndtimeo`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_sndtimeo (void *self); - -// Set socket option `sndtimeo`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_sndtimeo (void *self, int sndtimeo); - -// Set socket option `xpub_verbose`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_xpub_verbose (void *self, int xpub_verbose); - -// Get socket option `tcp_keepalive`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_tcp_keepalive (void *self); - -// Set socket option `tcp_keepalive`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_tcp_keepalive (void *self, int tcp_keepalive); - -// Get socket option `tcp_keepalive_idle`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_tcp_keepalive_idle (void *self); - -// Set socket option `tcp_keepalive_idle`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_tcp_keepalive_idle (void *self, int tcp_keepalive_idle); - -// Get socket option `tcp_keepalive_cnt`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_tcp_keepalive_cnt (void *self); - -// Set socket option `tcp_keepalive_cnt`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_tcp_keepalive_cnt (void *self, int tcp_keepalive_cnt); - -// Get socket option `tcp_keepalive_intvl`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_tcp_keepalive_intvl (void *self); - -// Set socket option `tcp_keepalive_intvl`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_tcp_keepalive_intvl (void *self, int tcp_keepalive_intvl); - -// Get socket option `tcp_accept_filter`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zsock_tcp_accept_filter (void *self); - -// Set socket option `tcp_accept_filter`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_tcp_accept_filter (void *self, const char *tcp_accept_filter); - -// Get socket option `rcvmore`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_rcvmore (void *self); - -// Get socket option `fd`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT SOCKET - zsock_fd (void *self); - -// Get socket option `events`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_events (void *self); - -// Get socket option `last_endpoint`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zsock_last_endpoint (void *self); - -// Set socket option `router_raw`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_router_raw (void *self, int router_raw); - -// Get socket option `ipv4only`\&. -// Available from libzmq 3\&.0\&.0\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT int - zsock_ipv4only (void *self); - -// Set socket option `ipv4only`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_ipv4only (void *self, int ipv4only); - -// Set socket option `delay_attach_on_connect`\&. -// Available from libzmq 3\&.0\&.0\&. -CZMQ_EXPORT void - zsock_set_delay_attach_on_connect (void *self, int delay_attach_on_connect); - -// Self test of this class\&. -CZMQ_EXPORT void - zsock_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Create a SERVER socket\&. Default action is bind\&. -CZMQ_EXPORT zsock_t * - zsock_new_server (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a CLIENT socket\&. Default action is connect\&. -CZMQ_EXPORT zsock_t * - zsock_new_client (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a RADIO socket\&. Default action is bind\&. -CZMQ_EXPORT zsock_t * - zsock_new_radio (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a DISH socket\&. Default action is connect\&. -CZMQ_EXPORT zsock_t * - zsock_new_dish (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a GATHER socket\&. Default action is bind\&. -CZMQ_EXPORT zsock_t * - zsock_new_gather (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a SCATTER socket\&. Default action is connect\&. -CZMQ_EXPORT zsock_t * - zsock_new_scatter (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Return socket routing ID if any\&. This returns 0 if the socket is not -// of type ZMQ_SERVER or if no request was already received on it\&. -CZMQ_EXPORT uint32_t - zsock_routing_id (zsock_t *self); - -// *** Draft method, for development use, may change without warning *** -// Set routing ID on socket\&. The socket MUST be of type ZMQ_SERVER\&. -// This will be used when sending messages on the socket via the zsock API\&. -CZMQ_EXPORT void - zsock_set_routing_id (zsock_t *self, uint32_t routing_id); - -// *** Draft method, for development use, may change without warning *** -// Join a group for the RADIO\-DISH pattern\&. Call only on ZMQ_DISH\&. -// Returns 0 if OK, \-1 if failed\&. -CZMQ_EXPORT int - zsock_join (void *self, const char *group); - -// *** Draft method, for development use, may change without warning *** -// Leave a group for the RADIO\-DISH pattern\&. Call only on ZMQ_DISH\&. -// Returns 0 if OK, \-1 if failed\&. -CZMQ_EXPORT int - zsock_leave (void *self, const char *group); - -#endif // CZMQ_BUILD_DRAFT_API -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zsock\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -The zsock class wraps the libzmq socket handle (a void *) with a proper structure that follows the CLASS rules for construction and destruction\&. Some zsock methods take a void * "polymorphic" reference, which can be either a zsock_t or a zactor_t reference, or a libzmq void *\&. -.sp -Please add \fI@discuss\fR section in \fI\&./\&.\&./src/zsock\&.c\fR\&. -.SH "EXAMPLE" -.PP -\fBFrom zsock_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -zsock_t *writer = zsock_new_push ("@tcp://127\&.0\&.0\&.1:5560"); -assert (writer); -assert (zsock_resolve (writer) != writer); -assert (streq (zsock_type_str (writer), "PUSH")); - -int rc; -#if (ZMQ_VERSION >= ZMQ_MAKE_VERSION (3, 2, 0)) -// Check unbind -rc = zsock_unbind (writer, "tcp://127\&.0\&.0\&.1:%d", 5560); -assert (rc == 0); - -// In some cases and especially when running under Valgrind, doing -// a bind immediately after an unbind causes an EADDRINUSE error\&. -// Even a short sleep allows the OS to release the port for reuse\&. -zclock_sleep (100); - -// Bind again -rc = zsock_bind (writer, "tcp://127\&.0\&.0\&.1:%d", 5560); -assert (rc == 5560); -assert (streq (zsock_endpoint (writer), "tcp://127\&.0\&.0\&.1:5560")); -#endif - -zsock_t *reader = zsock_new_pull (">tcp://127\&.0\&.0\&.1:5560"); -assert (reader); -assert (zsock_resolve (reader) != reader); -assert (streq (zsock_type_str (reader), "PULL")); - -// Basic Hello, World -zstr_send (writer, "Hello, World"); -zmsg_t *msg = zmsg_recv (reader); -assert (msg); -char *string = zmsg_popstr (msg); -assert (streq (string, "Hello, World")); -free (string); -zmsg_destroy (&msg); - -// Test resolve libzmq socket -#if (ZMQ_VERSION >= ZMQ_MAKE_VERSION (3, 2, 0)) -void *zmq_ctx = zmq_ctx_new (); -#else -void *zmq_ctx = zmq_ctx_new (1); -#endif -assert (zmq_ctx); -void *zmq_sock = zmq_socket (zmq_ctx, ZMQ_PUB); -assert (zmq_sock); -assert (zsock_resolve (zmq_sock) == zmq_sock); -zmq_close (zmq_sock); -zmq_ctx_term (zmq_ctx); - -// Test resolve zsock -zsock_t *resolve = zsock_new_pub("@tcp://127\&.0\&.0\&.1:5561"); -assert (resolve); -assert (zsock_resolve (resolve) == resolve\->handle); -zsock_destroy (&resolve); - -// Test resolve FD -SOCKET fd = zsock_fd (reader); -assert (zsock_resolve ((void *) &fd) == NULL); - -// Test binding to ephemeral ports, sequential and random -int port = zsock_bind (writer, "tcp://127\&.0\&.0\&.1:*"); -assert (port >= DYNAMIC_FIRST && port <= DYNAMIC_LAST); -port = zsock_bind (writer, "tcp://127\&.0\&.0\&.1:*[50000\-]"); -assert (port >= 50000 && port <= DYNAMIC_LAST); -port = zsock_bind (writer, "tcp://127\&.0\&.0\&.1:*[\-50001]"); -assert (port >= DYNAMIC_FIRST && port <= 50001); -port = zsock_bind (writer, "tcp://127\&.0\&.0\&.1:*[60000\-60050]"); -assert (port >= 60000 && port <= 60050); - -port = zsock_bind (writer, "tcp://127\&.0\&.0\&.1:!"); -assert (port >= DYNAMIC_FIRST && port <= DYNAMIC_LAST); -port = zsock_bind (writer, "tcp://127\&.0\&.0\&.1:![50000\-]"); -assert (port >= 50000 && port <= DYNAMIC_LAST); -port = zsock_bind (writer, "tcp://127\&.0\&.0\&.1:![\-50001]"); -assert (port >= DYNAMIC_FIRST && port <= 50001); -port = zsock_bind (writer, "tcp://127\&.0\&.0\&.1:![60000\-60050]"); -assert (port >= 60000 && port <= 60050); - -// Test zsock_attach method -zsock_t *server = zsock_new (ZMQ_DEALER); -assert (server); -rc = zsock_attach (server, "@inproc://myendpoint,tcp://127\&.0\&.0\&.1:5556,inproc://others", true); -assert (rc == 0); -rc = zsock_attach (server, "", false); -assert (rc == 0); -rc = zsock_attach (server, NULL, true); -assert (rc == 0); -rc = zsock_attach (server, ">a,@b, c,, ", false); -assert (rc == \-1); -zsock_destroy (&server); - -// Test zsock_endpoint method -rc = zsock_bind (writer, "inproc://test\&.%s", "writer"); -assert (rc == 0); -assert (streq (zsock_endpoint (writer), "inproc://test\&.writer")); - -// Test error state when connecting to an invalid socket type -// (\*(Aqtxp://\*(Aq instead of \*(Aqtcp://\*(Aq, typo intentional) -rc = zsock_connect (reader, "txp://127\&.0\&.0\&.1:5560"); -assert (rc == \-1); - -// Test signal/wait methods -rc = zsock_signal (writer, 123); -assert (rc == 0); -rc = zsock_wait (reader); -assert (rc == 123); - -// Test zsock_send/recv pictures -uint8_t number1 = 123; -uint16_t number2 = 123 * 123; -uint32_t number4 = 123 * 123; -number4 *= 123; -uint32_t number4_MAX = UINT32_MAX; -uint64_t number8 = 123 * 123; -number8 *= 123; -number8 *= 123; -uint64_t number8_MAX = UINT64_MAX; - -zchunk_t *chunk = zchunk_new ("HELLO", 5); -assert (chunk); -zframe_t *frame = zframe_new ("WORLD", 5); -assert (frame); -zhashx_t *hash = zhashx_new (); -assert (hash); -zuuid_t *uuid = zuuid_new (); -assert (uuid); -zhashx_set_destructor (hash, (zhashx_destructor_fn *) zstr_free); -zhashx_set_duplicator (hash, (zhashx_duplicator_fn *) strdup); -zhashx_insert (hash, "1", "value A"); -zhashx_insert (hash, "2", "value B"); -char *original = "pointer"; - -// Test zsock_recv into each supported type -zsock_send (writer, "i124488zsbcfUhp", - \-12345, number1, number2, number4, number4_MAX, - number8, number8_MAX, - "This is a string", "ABCDE", 5, - chunk, frame, uuid, hash, original); -char *uuid_str = strdup (zuuid_str (uuid)); -zchunk_destroy (&chunk); -zframe_destroy (&frame); -zuuid_destroy (&uuid); -zhashx_destroy (&hash); - -int integer; -byte *data; -size_t size; -char *pointer; -number8_MAX = number8 = number4_MAX = number4 = number2 = number1 = 0ULL; -rc = zsock_recv (reader, "i124488zsbcfUhp", - &integer, &number1, &number2, &number4, &number4_MAX, - &number8, &number8_MAX, &string, &data, &size, &chunk, - &frame, &uuid, &hash, &pointer); -assert (rc == 0); -assert (integer == \-12345); -assert (number1 == 123); -assert (number2 == 123 * 123); -assert (number4 == 123 * 123 * 123); -assert (number4_MAX == UINT32_MAX); -assert (number8 == 123 * 123 * 123 * 123); -assert (number8_MAX == UINT64_MAX); -assert (streq (string, "This is a string")); -assert (memcmp (data, "ABCDE", 5) == 0); -assert (size == 5); -assert (memcmp (zchunk_data (chunk), "HELLO", 5) == 0); -assert (zchunk_size (chunk) == 5); -assert (streq (uuid_str, zuuid_str (uuid))); -assert (memcmp (zframe_data (frame), "WORLD", 5) == 0); -assert (zframe_size (frame) == 5); -char *value = (char *) zhashx_lookup (hash, "1"); -assert (streq (value, "value A")); -value = (char *) zhashx_lookup (hash, "2"); -assert (streq (value, "value B")); -assert (original == pointer); -free (string); -free (data); -free (uuid_str); -zframe_destroy (&frame); -zchunk_destroy (&chunk); -zhashx_destroy (&hash); -zuuid_destroy (&uuid); - -// Test zsock_recv of short message; this lets us return a failure -// with a status code and then nothing else; the receiver will get -// the status code and NULL/zero for all other values -zsock_send (writer, "i", \-1); -zsock_recv (reader, "izsbcfp", - &integer, &string, &data, &size, &chunk, &frame, &pointer); -assert (integer == \-1); -assert (string == NULL); -assert (data == NULL); -assert (size == 0); -assert (chunk == NULL); -assert (frame == NULL); -assert (pointer == NULL); - -msg = zmsg_new (); -zmsg_addstr (msg, "frame 1"); -zmsg_addstr (msg, "frame 2"); -zsock_send (writer, "szm", "header", msg); -zmsg_destroy (&msg); - -zsock_recv (reader, "szm", &string, &msg); - -assert (streq ("header", string)); -assert (zmsg_size (msg) == 2); -assert (zframe_streq (zmsg_first (msg), "frame 1")); -assert (zframe_streq (zmsg_next (msg), "frame 2")); -zstr_free (&string); -zmsg_destroy (&msg); - -// Test zsock_recv with null arguments -chunk = zchunk_new ("HELLO", 5); -assert (chunk); -frame = zframe_new ("WORLD", 5); -assert (frame); -zsock_send (writer, "izsbcfp", - \-12345, "This is a string", "ABCDE", 5, chunk, frame, original); -zframe_destroy (&frame); -zchunk_destroy (&chunk); -zsock_recv (reader, "izsbcfp", &integer, NULL, NULL, NULL, &chunk, NULL, NULL); -assert (integer == \-12345); -assert (memcmp (zchunk_data (chunk), "HELLO", 5) == 0); -assert (zchunk_size (chunk) == 5); -zchunk_destroy (&chunk); - -// Test zsock_bsend/brecv pictures with binary encoding -frame = zframe_new ("Hello", 5); -chunk = zchunk_new ("World", 5); - -msg = zmsg_new (); -zmsg_addstr (msg, "Hello"); -zmsg_addstr (msg, "World"); - -zsock_bsend (writer, "1248sSpcfm", - number1, number2, number4, number8, - "Hello, World", - "Goodbye cruel World!", - original, - chunk, frame, msg); -zchunk_destroy (&chunk); -zframe_destroy (&frame); -zmsg_destroy (&msg); - -number8 = number4 = number2 = number1 = 0; -char *longstr; -zsock_brecv (reader, "1248sSpcfm", - &number1, &number2, &number4, &number8, - &string, &longstr, - &pointer, - &chunk, &frame, &msg); -assert (number1 == 123); -assert (number2 == 123 * 123); -assert (number4 == 123 * 123 * 123); -assert (number8 == 123 * 123 * 123 * 123); -assert (streq (string, "Hello, World")); -assert (streq (longstr, "Goodbye cruel World!")); -assert (pointer == original); -zstr_free (&longstr); -zchunk_destroy (&chunk); -zframe_destroy (&frame); -zmsg_destroy (&msg); - -#ifdef ZMQ_SERVER - -// Test zsock_bsend/brecv pictures with binary encoding on SERVER and CLIENT sockets -server = zsock_new_server ("tcp://127\&.0\&.0\&.1:5561"); -assert (server); -zsock_t* client = zsock_new_client ("tcp://127\&.0\&.0\&.1:5561"); -assert (client); - -// From client to server -chunk = zchunk_new ("World", 5); -zsock_bsend (client, "1248sSpc", - number1, number2, number4, number8, - "Hello, World", - "Goodbye cruel World!", - original, - chunk); -zchunk_destroy (&chunk); - -number8 = number4 = number2 = number1 = 0; -zsock_brecv (server, "1248sSpc", - &number1, &number2, &number4, &number8, - &string, &longstr, - &pointer, - &chunk); -assert (number1 == 123); -assert (number2 == 123 * 123); -assert (number4 == 123 * 123 * 123); -assert (number8 == 123 * 123 * 123 * 123); -assert (streq (string, "Hello, World")); -assert (streq (longstr, "Goodbye cruel World!")); -assert (pointer == original); -assert (zsock_routing_id (server)); -zstr_free (&longstr); -zchunk_destroy (&chunk); - -// From server to client -chunk = zchunk_new ("World", 5); -zsock_bsend (server, "1248sSpc", - number1, number2, number4, number8, - "Hello, World", - "Goodbye cruel World!", - original, - chunk); -zchunk_destroy (&chunk); - -number8 = number4 = number2 = number1 = 0; -zsock_brecv (client, "1248sSpc", - &number1, &number2, &number4, &number8, - &string, &longstr, - &pointer, - &chunk); -assert (number1 == 123); -assert (number2 == 123 * 123); -assert (number4 == 123 * 123 * 123); -assert (number8 == 123 * 123 * 123 * 123); -assert (streq (string, "Hello, World")); -assert (streq (longstr, "Goodbye cruel World!")); -assert (pointer == original); -assert (zsock_routing_id (client) == 0); -zstr_free (&longstr); -zchunk_destroy (&chunk); - -zsock_destroy (&client); -zsock_destroy (&server); - -#endif - -#ifdef ZMQ_SCATTER - -zsock_t* gather = zsock_new_gather ("inproc://test\-gather\-scatter"); -assert (gather); -zsock_t* scatter = zsock_new_scatter ("inproc://test\-gather\-scatter"); -assert (scatter); - -rc = zstr_send (scatter, "HELLO"); -assert (rc == 0); - -char* message; -message = zstr_recv (gather); -assert (streq(message, "HELLO")); -zstr_free (&message); - -zsock_destroy (&gather); -zsock_destroy (&scatter); - -#endif - -// Check that we can send a zproto format message -zsock_bsend (writer, "1111sS4", 0xAA, 0xA0, 0x02, 0x01, "key", "value", 1234); -zgossip_msg_t *gossip = zgossip_msg_new (); -zgossip_msg_recv (gossip, reader); -assert (zgossip_msg_id (gossip) == ZGOSSIP_MSG_PUBLISH); -zgossip_msg_destroy (&gossip); - -zsock_destroy (&reader); -zsock_destroy (&writer); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zstr.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zstr.3 deleted file mode 100644 index c4ea427545..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zstr.3 +++ /dev/null @@ -1,242 +0,0 @@ -'\" t -.\" Title: zstr -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZSTR" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zstr \- sending and receiving strings -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// This class has draft methods, which may change over time\&. They are not -// in stable releases, by default\&. Use \-\-enable\-drafts to enable\&. -// Receive C string from socket\&. Caller must free returned string using -// zstr_free()\&. Returns NULL if the context is being terminated or the -// process was interrupted\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zstr_recv (void *source); - -// Receive a series of strings (until NULL) from multipart data\&. -// Each string is allocated and filled with string data; if there -// are not enough frames, unallocated strings are set to NULL\&. -// Returns \-1 if the message could not be read, else returns the -// number of strings filled, zero or more\&. Free each returned string -// using zstr_free()\&. If not enough strings are provided, remaining -// multipart frames in the message are dropped\&. -CZMQ_EXPORT int - zstr_recvx (void *source, char **string_p, \&.\&.\&.); - -// Send a C string to a socket, as a frame\&. The string is sent without -// trailing null byte; to read this you can use zstr_recv, or a similar -// method that adds a null terminator on the received string\&. String -// may be NULL, which is sent as ""\&. -CZMQ_EXPORT int - zstr_send (void *dest, const char *string); - -// Send a C string to a socket, as zstr_send(), with a MORE flag, so that -// you can send further strings in the same multi\-part message\&. -CZMQ_EXPORT int - zstr_sendm (void *dest, const char *string); - -// Send a formatted string to a socket\&. Note that you should NOT use -// user\-supplied strings in the format (they may contain \*(Aq%\*(Aq which -// will create security holes)\&. -CZMQ_EXPORT int - zstr_sendf (void *dest, const char *format, \&.\&.\&.) CHECK_PRINTF (2); - -// Send a formatted string to a socket, as for zstr_sendf(), with a -// MORE flag, so that you can send further strings in the same multi\-part -// message\&. -CZMQ_EXPORT int - zstr_sendfm (void *dest, const char *format, \&.\&.\&.) CHECK_PRINTF (2); - -// Send a series of strings (until NULL) as multipart data -// Returns 0 if the strings could be sent OK, or \-1 on error\&. -CZMQ_EXPORT int - zstr_sendx (void *dest, const char *string, \&.\&.\&.); - -// Free a provided string, and nullify the parent pointer\&. Safe to call on -// a null pointer\&. -CZMQ_EXPORT void - zstr_free (char **string_p); - -// Self test of this class\&. -CZMQ_EXPORT void - zstr_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Accepts a void pointer and returns a fresh character string\&. If source -// is null, returns an empty string\&. -// Caller owns return value and must destroy it when done\&. -CZMQ_EXPORT char * - zstr_str (void *source); - -#endif // CZMQ_BUILD_DRAFT_API -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zstr\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -The zstr class provides utility functions for sending and receiving C strings across 0MQ sockets\&. It sends strings without a terminating null, and appends a null byte on received strings\&. This class is for simple message sending\&. -.sp -.if n \{\ -.RS 4 -.\} -.nf - Memory Wire - +\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-+ +\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-+ -Send | S t r i n g | 0 | \-\-\-\-> | 6 | S t r i n g | - +\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-+ +\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-+ -.fi -.if n \{\ -.RE -.\} -.sp -.if n \{\ -.RS 4 -.\} -.nf - Wire Heap - +\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-+ +\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-+ -Recv | 6 | S t r i n g | \-\-\-\-> | S t r i n g | 0 | - +\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-+ +\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-+ -.fi -.if n \{\ -.RE -.\} -.SH "EXAMPLE" -.PP -\fBFrom zstr_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Create two PAIR sockets and connect over inproc -zsock_t *output = zsock_new_pair ("@inproc://zstr\&.test"); -assert (output); -zsock_t *input = zsock_new_pair (">inproc://zstr\&.test"); -assert (input); - -// Send ten strings, five strings with MORE flag and then END -int string_nbr; -for (string_nbr = 0; string_nbr < 10; string_nbr++) - zstr_sendf (output, "this is string %d", string_nbr); -zstr_sendx (output, "This", "is", "almost", "the", "very", "END", NULL); - -// Read and count until we receive END -string_nbr = 0; -for (string_nbr = 0;; string_nbr++) { - char *string = zstr_recv (input); - assert (string); - if (streq (string, "END")) { - zstr_free (&string); - break; - } - zstr_free (&string); -} -assert (string_nbr == 15); - -zsock_destroy (&input); -zsock_destroy (&output); - -#if defined (ZMQ_SERVER) -// Test SERVER/CLIENT over zstr -zsock_t *server = zsock_new_server ("inproc://zstr\-test\-routing"); -zsock_t *client = zsock_new_client ("inproc://zstr\-test\-routing");; -assert (server); -assert (client); - -// Try normal ping\-pong to check reply routing ID -int rc = zstr_send (client, "Hello"); -assert (rc == 0); -char *request = zstr_recv (server); -assert (streq (request, "Hello")); -assert (zsock_routing_id (server)); -free (request); - -rc = zstr_send (server, "World"); -assert (rc == 0); -char *reply = zstr_recv (client); -assert (streq (reply, "World")); -free (reply); - -rc = zstr_sendf (server, "%s", "World"); -assert (rc == 0); -reply = zstr_recv (client); -assert (streq (reply, "World")); -free (reply); - -// Try ping\-pong using sendx and recx -rc = zstr_sendx (client, "Hello", NULL); -assert (rc == 0); -rc = zstr_recvx (server, &request, NULL); -assert (rc >= 0); -assert (streq (request, "Hello")); -free (request); - -rc = zstr_sendx (server, "World", NULL); -assert (rc == 0); -rc = zstr_recvx (client, &reply, NULL); -assert (rc >= 0); -assert (streq (reply, "World")); -free (reply); - -// Client and server disallow multipart -rc = zstr_sendm (client, "Hello"); -assert (rc == \-1); -rc = zstr_sendm (server, "World"); -assert (rc == \-1); - -zsock_destroy (&client); -zsock_destroy (&server); -#endif -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zsys.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zsys.3 deleted file mode 100644 index 2d4f5c2e45..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zsys.3 +++ /dev/null @@ -1,539 +0,0 @@ -'\" t -.\" Title: zsys -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZSYS" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zsys \- system\-level methods -.SH "SYNOPSIS" -.sp -.nf -#define UDP_FRAME_MAX 255 // Max size of UDP frame - -// Callback for interrupt signal handler -typedef void (zsys_handler_fn) (int signal_value); - -// Initialize CZMQ zsys layer; this happens automatically when you create -// a socket or an actor; however this call lets you force initialization -// earlier, so e\&.g\&. logging is properly set\-up before you start working\&. -// Not threadsafe, so call only from main thread\&. Safe to call multiple -// times\&. Returns global CZMQ context\&. -CZMQ_EXPORT void * - zsys_init (void); - -// Optionally shut down the CZMQ zsys layer; this normally happens automatically -// when the process exits; however this call lets you force a shutdown -// earlier, avoiding any potential problems with atexit() ordering, especially -// with Windows dlls\&. -CZMQ_EXPORT void - zsys_shutdown (void); - -// Get a new ZMQ socket, automagically creating a ZMQ context if this is -// the first time\&. Caller is responsible for destroying the ZMQ socket -// before process exits, to avoid a ZMQ deadlock\&. Note: you should not use -// this method in CZMQ apps, use zsock_new() instead\&. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT void * - zsys_socket (int type, const char *filename, size_t line_nbr); - -// Destroy/close a ZMQ socket\&. You should call this for every socket you -// create using zsys_socket()\&. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT int - zsys_close (void *handle, const char *filename, size_t line_nbr); - -// Return ZMQ socket name for socket type -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT char * - zsys_sockname (int socktype); - -// Create a pipe, which consists of two PAIR sockets connected over inproc\&. -// The pipe is configured to use the zsys_pipehwm setting\&. Returns the -// frontend socket successful, NULL if failed\&. -CZMQ_EXPORT zsock_t * - zsys_create_pipe (zsock_t **backend_p); - -// Set interrupt handler; this saves the default handlers so that a -// zsys_handler_reset () can restore them\&. If you call this multiple times -// then the last handler will take affect\&. If handler_fn is NULL, disables -// default SIGINT/SIGTERM handling in CZMQ\&. -CZMQ_EXPORT void - zsys_handler_set (zsys_handler_fn *handler_fn); - -// Reset interrupt handler, call this at exit if needed -CZMQ_EXPORT void - zsys_handler_reset (void); - -// Set default interrupt handler, so Ctrl\-C or SIGTERM will set -// zsys_interrupted\&. Idempotent; safe to call multiple times\&. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT void - zsys_catch_interrupts (void); - -// Return 1 if file exists, else zero -CZMQ_EXPORT bool - zsys_file_exists (const char *filename); - -// Return size of file, or \-1 if not found -CZMQ_EXPORT ssize_t - zsys_file_size (const char *filename); - -// Return file modification time\&. Returns 0 if the file does not exist\&. -CZMQ_EXPORT time_t - zsys_file_modified (const char *filename); - -// Return file mode; provides at least support for the POSIX S_ISREG(m) -// and S_ISDIR(m) macros and the S_IRUSR and S_IWUSR bits, on all boxes\&. -// Returns a mode_t cast to int, or \-1 in case of error\&. -CZMQ_EXPORT int - zsys_file_mode (const char *filename); - -// Delete file\&. Does not complain if the file is absent -CZMQ_EXPORT int - zsys_file_delete (const char *filename); - -// Check if file is \*(Aqstable\*(Aq -CZMQ_EXPORT bool - zsys_file_stable (const char *filename); - -// Create a file path if it doesn\*(Aqt exist\&. The file path is treated as a -// printf format\&. -CZMQ_EXPORT int - zsys_dir_create (const char *pathname, \&.\&.\&.); - -// Remove a file path if empty; the pathname is treated as printf format\&. -CZMQ_EXPORT int - zsys_dir_delete (const char *pathname, \&.\&.\&.); - -// Move to a specified working directory\&. Returns 0 if OK, \-1 if this failed\&. -CZMQ_EXPORT int - zsys_dir_change (const char *pathname); - -// Set private file creation mode; all files created from here will be -// readable/writable by the owner only\&. -CZMQ_EXPORT void - zsys_file_mode_private (void); - -// Reset default file creation mode; all files created from here will use -// process file mode defaults\&. -CZMQ_EXPORT void - zsys_file_mode_default (void); - -// Return the CZMQ version for run\-time API detection; returns version -// number into provided fields, providing reference isn\*(Aqt null in each case\&. -CZMQ_EXPORT void - zsys_version (int *major, int *minor, int *patch); - -// Format a string using printf formatting, returning a freshly allocated -// buffer\&. If there was insufficient memory, returns NULL\&. Free the returned -// string using zstr_free()\&. -CZMQ_EXPORT char * - zsys_sprintf (const char *format, \&.\&.\&.); - -// Format a string with a va_list argument, returning a freshly allocated -// buffer\&. If there was insufficient memory, returns NULL\&. Free the returned -// string using zstr_free()\&. -CZMQ_EXPORT char * - zsys_vprintf (const char *format, va_list argptr); - -// Create UDP beacon socket; if the routable option is true, uses -// multicast (not yet implemented), else uses broadcast\&. This method -// and related ones might _eventually_ be moved to a zudp class\&. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT SOCKET - zsys_udp_new (bool routable); - -// Close a UDP socket -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT int - zsys_udp_close (SOCKET handle); - -// Send zframe to UDP socket, return \-1 if sending failed due to -// interface having disappeared (happens easily with WiFi) -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT int - zsys_udp_send (SOCKET udpsock, zframe_t *frame, inaddr_t *address, int addrlen); - -// Receive zframe from UDP socket, and set address of peer that sent it -// The peername must be a char [INET_ADDRSTRLEN] array\&. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT zframe_t * - zsys_udp_recv (SOCKET udpsock, char *peername, int peerlen); - -// Handle an I/O error on some socket operation; will report and die on -// fatal errors, and continue silently on "try again" errors\&. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT void - zsys_socket_error (const char *reason); - -// Return current host name, for use in public tcp:// endpoints\&. Caller gets -// a freshly allocated string, should free it using zstr_free()\&. If the host -// name is not resolvable, returns NULL\&. -CZMQ_EXPORT char * - zsys_hostname (void); - -// Move the current process into the background\&. The precise effect depends -// on the operating system\&. On POSIX boxes, moves to a specified working -// directory (if specified), closes all file handles, reopens stdin, stdout, -// and stderr to the null device, and sets the process to ignore SIGHUP\&. On -// Windows, does nothing\&. Returns 0 if OK, \-1 if there was an error\&. -CZMQ_EXPORT int - zsys_daemonize (const char *workdir); - -// Drop the process ID into the lockfile, with exclusive lock, and switch -// the process to the specified group and/or user\&. Any of the arguments -// may be null, indicating a no\-op\&. Returns 0 on success, \-1 on failure\&. -// Note if you combine this with zsys_daemonize, run after, not before -// that method, or the lockfile will hold the wrong process ID\&. -CZMQ_EXPORT int - zsys_run_as (const char *lockfile, const char *group, const char *user); - -// Returns true if the underlying libzmq supports CURVE security\&. -// Uses a heuristic probe according to the version of libzmq being used\&. -CZMQ_EXPORT bool - zsys_has_curve (void); - -// Configure the number of I/O threads that ZeroMQ will use\&. A good -// rule of thumb is one thread per gigabit of traffic in or out\&. The -// default is 1, sufficient for most applications\&. If the environment -// variable ZSYS_IO_THREADS is defined, that provides the default\&. -// Note that this method is valid only before any socket is created\&. -CZMQ_EXPORT void - zsys_set_io_threads (size_t io_threads); - -// Configure the number of sockets that ZeroMQ will allow\&. The default -// is 1024\&. The actual limit depends on the system, and you can query it -// by using zsys_socket_limit ()\&. A value of zero means "maximum"\&. -// Note that this method is valid only before any socket is created\&. -CZMQ_EXPORT void - zsys_set_max_sockets (size_t max_sockets); - -// Return maximum number of ZeroMQ sockets that the system will support\&. -CZMQ_EXPORT size_t - zsys_socket_limit (void); - -// Configure the maximum allowed size of a message sent\&. -// The default is INT_MAX\&. -CZMQ_EXPORT void - zsys_set_max_msgsz (int max_msgsz); - -// Return maximum message size\&. -CZMQ_EXPORT int - zsys_max_msgsz (void); - -// Configure the default linger timeout in msecs for new zsock instances\&. -// You can also set this separately on each zsock_t instance\&. The default -// linger time is zero, i\&.e\&. any pending messages will be dropped\&. If the -// environment variable ZSYS_LINGER is defined, that provides the default\&. -// Note that process exit will typically be delayed by the linger time\&. -CZMQ_EXPORT void - zsys_set_linger (size_t linger); - -// Configure the default outgoing pipe limit (HWM) for new zsock instances\&. -// You can also set this separately on each zsock_t instance\&. The default -// HWM is 1,000, on all versions of ZeroMQ\&. If the environment variable -// ZSYS_SNDHWM is defined, that provides the default\&. Note that a value of -// zero means no limit, i\&.e\&. infinite memory consumption\&. -CZMQ_EXPORT void - zsys_set_sndhwm (size_t sndhwm); - -// Configure the default incoming pipe limit (HWM) for new zsock instances\&. -// You can also set this separately on each zsock_t instance\&. The default -// HWM is 1,000, on all versions of ZeroMQ\&. If the environment variable -// ZSYS_RCVHWM is defined, that provides the default\&. Note that a value of -// zero means no limit, i\&.e\&. infinite memory consumption\&. -CZMQ_EXPORT void - zsys_set_rcvhwm (size_t rcvhwm); - -// Configure the default HWM for zactor internal pipes; this is set on both -// ends of the pipe, for outgoing messages only (sndhwm)\&. The default HWM is -// 1,000, on all versions of ZeroMQ\&. If the environment var ZSYS_ACTORHWM is -// defined, that provides the default\&. Note that a value of zero means no -// limit, i\&.e\&. infinite memory consumption\&. -CZMQ_EXPORT void - zsys_set_pipehwm (size_t pipehwm); - -// Return the HWM for zactor internal pipes\&. -CZMQ_EXPORT size_t - zsys_pipehwm (void); - -// Configure use of IPv6 for new zsock instances\&. By default sockets accept -// and make only IPv4 connections\&. When you enable IPv6, sockets will accept -// and connect to both IPv4 and IPv6 peers\&. You can override the setting on -// each zsock_t instance\&. The default is IPv4 only (ipv6 set to 0)\&. If the -// environment variable ZSYS_IPV6 is defined (as 1 or 0), this provides the -// default\&. Note: has no effect on ZMQ v2\&. -CZMQ_EXPORT void - zsys_set_ipv6 (int ipv6); - -// Return use of IPv6 for zsock instances\&. -CZMQ_EXPORT int - zsys_ipv6 (void); - -// Set network interface name to use for broadcasts, particularly zbeacon\&. -// This lets the interface be configured for test environments where required\&. -// For example, on Mac OS X, zbeacon cannot bind to 255\&.255\&.255\&.255 which is -// the default when there is no specified interface\&. If the environment -// variable ZSYS_INTERFACE is set, use that as the default interface name\&. -// Setting the interface to "*" means "use all available interfaces"\&. -CZMQ_EXPORT void - zsys_set_interface (const char *value); - -// Return network interface to use for broadcasts, or "" if none was set\&. -CZMQ_EXPORT const char * - zsys_interface (void); - -// Set IPv6 address to use zbeacon socket, particularly for receiving zbeacon\&. -// This needs to be set IPv6 is enabled as IPv6 can have multiple addresses -// on a given interface\&. If the environment variable ZSYS_IPV6_ADDRESS is set, -// use that as the default IPv6 address\&. -CZMQ_EXPORT void - zsys_set_ipv6_address (const char *value); - -// Return IPv6 address to use for zbeacon reception, or "" if none was set\&. -CZMQ_EXPORT const char * - zsys_ipv6_address (void); - -// Set IPv6 milticast address to use for sending zbeacon messages\&. This needs -// to be set if IPv6 is enabled\&. If the environment variable -// ZSYS_IPV6_MCAST_ADDRESS is set, use that as the default IPv6 multicast -// address\&. -CZMQ_EXPORT void - zsys_set_ipv6_mcast_address (const char *value); - -// Return IPv6 multicast address to use for sending zbeacon, or "" if none was -// set\&. -CZMQ_EXPORT const char * - zsys_ipv6_mcast_address (void); - -// Configure the automatic use of pre\-allocated FDs when creating new sockets\&. -// If 0 (default), nothing will happen\&. Else, when a new socket is bound, the -// system API will be used to check if an existing pre\-allocated FD with a -// matching port (if TCP) or path (if IPC) exists, and if it does it will be -// set via the ZMQ_USE_FD socket option so that the library will use it -// instead of creating a new socket\&. -CZMQ_EXPORT void - zsys_set_auto_use_fd (int auto_use_fd); - -// Return use of automatic pre\-allocated FDs for zsock instances\&. -CZMQ_EXPORT int - zsys_auto_use_fd (void); - -// Set log identity, which is a string that prefixes all log messages sent -// by this process\&. The log identity defaults to the environment variable -// ZSYS_LOGIDENT, if that is set\&. -CZMQ_EXPORT void - zsys_set_logident (const char *value); - -// Set stream to receive log traffic\&. By default, log traffic is sent to -// stdout\&. If you set the stream to NULL, no stream will receive the log -// traffic (it may still be sent to the system facility)\&. -CZMQ_EXPORT void - zsys_set_logstream (FILE *stream); - -// Sends log output to a PUB socket bound to the specified endpoint\&. To -// collect such log output, create a SUB socket, subscribe to the traffic -// you care about, and connect to the endpoint\&. Log traffic is sent as a -// single string frame, in the same format as when sent to stdout\&. The -// log system supports a single sender; multiple calls to this method will -// bind the same sender to multiple endpoints\&. To disable the sender, call -// this method with a null argument\&. -CZMQ_EXPORT void - zsys_set_logsender (const char *endpoint); - -// Enable or disable logging to the system facility (syslog on POSIX boxes, -// event log on Windows)\&. By default this is disabled\&. -CZMQ_EXPORT void - zsys_set_logsystem (bool logsystem); - -// Log error condition \- highest priority -CZMQ_EXPORT void - zsys_error (const char *format, \&.\&.\&.); - -// Log warning condition \- high priority -CZMQ_EXPORT void - zsys_warning (const char *format, \&.\&.\&.); - -// Log normal, but significant, condition \- normal priority -CZMQ_EXPORT void - zsys_notice (const char *format, \&.\&.\&.); - -// Log informational message \- low priority -CZMQ_EXPORT void - zsys_info (const char *format, \&.\&.\&.); - -// Log debug\-level message \- lowest priority -CZMQ_EXPORT void - zsys_debug (const char *format, \&.\&.\&.); - -// Self test of this class -CZMQ_EXPORT void - zsys_test (bool verbose); - -// Global signal indicator, TRUE when user presses Ctrl\-C or the process -// gets a SIGTERM signal\&. -CZMQ_EXPORT extern volatile int zsys_interrupted; -// Deprecated name for this variable -CZMQ_EXPORT extern volatile int zctx_interrupted; -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zsys\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -The zsys class provides a portable wrapper for system calls\&. We collect them here to reduce the number of weird #ifdefs in other classes\&. As far as possible, the bulk of CZMQ classes are fully portable\&. -.sp -Please add \fI@discuss\fR section in \fI\&./\&.\&./src/zsys\&.c\fR\&. -.SH "EXAMPLE" -.PP -\fBFrom zsys_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -zsys_catch_interrupts (); - -// Check capabilities without using the return value -int rc = zsys_has_curve (); - -if (verbose) { - char *hostname = zsys_hostname (); - zsys_info ("host name is %s", hostname); - free (hostname); - zsys_info ("system limit is %zu ZeroMQ sockets", zsys_socket_limit ()); -} -zsys_set_linger (0); -zsys_set_sndhwm (1000); -zsys_set_rcvhwm (1000); -zsys_set_pipehwm (2500); -assert (zsys_pipehwm () == 2500); -zsys_set_ipv6 (0); - -// Test pipe creation -zsock_t *pipe_back; -zsock_t *pipe_front = zsys_create_pipe (&pipe_back); -zstr_send (pipe_front, "Hello"); -char *string = zstr_recv (pipe_back); -assert (streq (string, "Hello")); -free (string); -zsock_destroy (&pipe_back); -zsock_destroy (&pipe_front); - -// Test file manipulation -rc = zsys_file_delete ("nosuchfile"); -assert (rc == \-1); - -bool rc_bool = zsys_file_exists ("nosuchfile"); -assert (rc_bool != true); - -rc = (int) zsys_file_size ("nosuchfile"); -assert (rc == \-1); - -time_t when = zsys_file_modified ("\&."); -assert (when > 0); - -int mode = zsys_file_mode ("\&."); -assert (S_ISDIR (mode)); -assert (mode & S_IRUSR); -assert (mode & S_IWUSR); - -zsys_file_mode_private (); -rc = zsys_dir_create ("%s/%s", "\&.", "\&.testsys/subdir"); -assert (rc == 0); -when = zsys_file_modified ("\&./\&.testsys/subdir"); -assert (when > 0); -assert (!zsys_file_stable ("\&./\&.testsys/subdir")); -rc = zsys_dir_delete ("%s/%s", "\&.", "\&.testsys/subdir"); -assert (rc == 0); -rc = zsys_dir_delete ("%s/%s", "\&.", "\&.testsys"); -assert (rc == 0); -zsys_file_mode_default (); -assert (zsys_dir_change ("\&.") == 0); - -int major, minor, patch; -zsys_version (&major, &minor, &patch); -assert (major == CZMQ_VERSION_MAJOR); -assert (minor == CZMQ_VERSION_MINOR); -assert (patch == CZMQ_VERSION_PATCH); - -string = zsys_sprintf ("%s %02x", "Hello", 16); -assert (streq (string, "Hello 10")); -free (string); - -char *str64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890,\&."; -int num10 = 1234567890; -string = zsys_sprintf ("%s%s%s%s%d", str64, str64, str64, str64, num10); -assert (strlen (string) == (4 * 64 + 10)); -free (string); - -// Test logging system -zsys_set_logident ("czmq_selftest"); -zsys_set_logsender ("inproc://logging"); -void *logger = zsys_socket (ZMQ_SUB, NULL, 0); -assert (logger); -rc = zmq_connect (logger, "inproc://logging"); -assert (rc == 0); -rc = zmq_setsockopt (logger, ZMQ_SUBSCRIBE, "", 0); -assert (rc == 0); - -if (verbose) { - zsys_error ("This is an %s message", "error"); - zsys_warning ("This is a %s message", "warning"); - zsys_notice ("This is a %s message", "notice"); - zsys_info ("This is a %s message", "info"); - zsys_debug ("This is a %s message", "debug"); - zsys_set_logident ("hello, world"); - zsys_info ("This is a %s message", "info"); - zsys_debug ("This is a %s message", "debug"); - - // Check that logsender functionality is working - char *received = zstr_recv (logger); - assert (received); - zstr_free (&received); -} -zsys_close (logger, NULL, 0); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/ztimerset.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/ztimerset.3 deleted file mode 100644 index 1eaa5ab949..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/ztimerset.3 +++ /dev/null @@ -1,180 +0,0 @@ -'\" t -.\" Title: ztimerset -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZTIMERSET" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -ztimerset \- timer set -.SH "SYNOPSIS" -.sp -.nf -// This is a draft class, and may change without notice\&. It is disabled in -// stable builds by default\&. If you use this in applications, please ask -// for it to be pushed to stable state\&. Use \-\-enable\-drafts to enable\&. -#ifdef CZMQ_BUILD_DRAFT_API -// Callback function for timer event\&. -typedef void (ztimerset_fn) ( - int timer_id, void *arg); - -// *** Draft method, for development use, may change without warning *** -// Create new timer set\&. -CZMQ_EXPORT ztimerset_t * - ztimerset_new (void); - -// *** Draft method, for development use, may change without warning *** -// Destroy a timer set -CZMQ_EXPORT void - ztimerset_destroy (ztimerset_t **self_p); - -// *** Draft method, for development use, may change without warning *** -// Add a timer to the set\&. Returns timer id if OK, \-1 on failure\&. -CZMQ_EXPORT int - ztimerset_add (ztimerset_t *self, size_t interval, ztimerset_fn handler, void *arg); - -// *** Draft method, for development use, may change without warning *** -// Cancel a timer\&. Returns 0 if OK, \-1 on failure\&. -CZMQ_EXPORT int - ztimerset_cancel (ztimerset_t *self, int timer_id); - -// *** Draft method, for development use, may change without warning *** -// Set timer interval\&. Returns 0 if OK, \-1 on failure\&. -// This method is slow, canceling the timer and adding a new one yield better performance\&. -CZMQ_EXPORT int - ztimerset_set_interval (ztimerset_t *self, int timer_id, size_t interval); - -// *** Draft method, for development use, may change without warning *** -// Reset timer to start interval counting from current time\&. Returns 0 if OK, \-1 on failure\&. -// This method is slow, canceling the timer and adding a new one yield better performance\&. -CZMQ_EXPORT int - ztimerset_reset (ztimerset_t *self, int timer_id); - -// *** Draft method, for development use, may change without warning *** -// Return the time until the next interval\&. -// Should be used as timeout parameter for the zpoller wait method\&. -// The timeout is in msec\&. -CZMQ_EXPORT int - ztimerset_timeout (ztimerset_t *self); - -// *** Draft method, for development use, may change without warning *** -// Invoke callback function of all timers which their interval has elapsed\&. -// Should be call after zpoller wait method\&. -// Returns 0 if OK, \-1 on failure\&. -CZMQ_EXPORT int - ztimerset_execute (ztimerset_t *self); - -// *** Draft method, for development use, may change without warning *** -// Self test of this class\&. -CZMQ_EXPORT void - ztimerset_test (bool verbose); - -#endif // CZMQ_BUILD_DRAFT_API -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/ztimerset\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -ztimerset \- timer set -.sp -Please add \fI@discuss\fR section in \fI\&./\&.\&./src/ztimerset\&.c\fR\&. -.SH "EXAMPLE" -.PP -\fBFrom ztimerset_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Simple create/destroy test -ztimerset_t *self = ztimerset_new (); -assert (self); - -// Adding timer -bool timer_invoked = false; -int timer_id = ztimerset_add (self, 100, handler, &timer_invoked); -assert (timer_id != \-1); -int rc = ztimerset_execute (self); -assert (rc == 0); -assert (!timer_invoked); -int timeout = ztimerset_timeout (self); -assert (timeout > 0); -zclock_sleep (timeout); -rc = ztimerset_execute (self); -assert (rc == 0); -assert (timer_invoked); - -// Cancel timer -timeout = ztimerset_timeout (self); -assert (timeout > 0); -rc = ztimerset_cancel (self, timer_id); -assert (rc == 0); -timeout = ztimerset_timeout (self); -assert(timeout == \-1); - -// Reset a timer -timer_id = ztimerset_add (self, 100, handler, &timer_invoked); -assert (timer_id != \-1); -timeout = ztimerset_timeout (self); -assert (timeout > 0); -zclock_sleep (timeout / 2); -timeout = ztimerset_timeout (self); -rc = ztimerset_reset(self, timer_id); -assert (rc == 0); -int timeout2 = ztimerset_timeout (self); -assert (timeout2 > timeout); -rc = ztimerset_cancel (self, timer_id); -assert (rc == 0); - -// Set interval -timer_id = ztimerset_add (self, 100, handler, &timer_invoked); -assert (timer_id != \-1); -timeout = ztimerset_timeout (self); -rc = ztimerset_set_interval(self, timer_id, 200); -timeout2 = ztimerset_timeout (self); -assert (timeout2 > timeout); - -ztimerset_destroy (&self); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/ztrie.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/ztrie.3 deleted file mode 100644 index 6cfb401a34..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/ztrie.3 +++ /dev/null @@ -1,292 +0,0 @@ -'\" t -.\" Title: ztrie -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZTRIE" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -ztrie \- simple trie for tokenizable strings -.SH "SYNOPSIS" -.sp -.nf -// This is a draft class, and may change without notice\&. It is disabled in -// stable builds by default\&. If you use this in applications, please ask -// for it to be pushed to stable state\&. Use \-\-enable\-drafts to enable\&. -#ifdef CZMQ_BUILD_DRAFT_API -// Callback function for ztrie_node to destroy node data\&. -typedef void (ztrie_destroy_data_fn) ( - void **data); - -// *** Draft method, for development use, may change without warning *** -// Creates a new ztrie\&. -CZMQ_EXPORT ztrie_t * - ztrie_new (char delimiter); - -// *** Draft method, for development use, may change without warning *** -// Destroy the ztrie\&. -CZMQ_EXPORT void - ztrie_destroy (ztrie_t **self_p); - -// *** Draft method, for development use, may change without warning *** -// Inserts a new route into the tree and attaches the data\&. Returns \-1 -// if the route already exists, otherwise 0\&. This method takes ownership of -// the provided data if a destroy_data_fn is provided\&. -CZMQ_EXPORT int - ztrie_insert_route (ztrie_t *self, const char *path, void *data, ztrie_destroy_data_fn destroy_data_fn); - -// *** Draft method, for development use, may change without warning *** -// Removes a route from the trie and destroys its data\&. Returns \-1 if the -// route does not exists, otherwise 0\&. -// the start of the list call zlist_first ()\&. Advances the cursor\&. -CZMQ_EXPORT int - ztrie_remove_route (ztrie_t *self, const char *path); - -// *** Draft method, for development use, may change without warning *** -// Returns true if the path matches a route in the tree, otherwise false\&. -CZMQ_EXPORT bool - ztrie_matches (ztrie_t *self, const char *path); - -// *** Draft method, for development use, may change without warning *** -// Returns the data of a matched route from last ztrie_matches\&. If the path -// did not match, returns NULL\&. Do not delete the data as it\*(Aqs owned by -// ztrie\&. -CZMQ_EXPORT void * - ztrie_hit_data (ztrie_t *self); - -// *** Draft method, for development use, may change without warning *** -// Returns the count of parameters that a matched route has\&. -CZMQ_EXPORT size_t - ztrie_hit_parameter_count (ztrie_t *self); - -// *** Draft method, for development use, may change without warning *** -// Returns the parameters of a matched route with named regexes from last -// ztrie_matches\&. If the path did not match or the route did not contain any -// named regexes, returns NULL\&. -CZMQ_EXPORT zhashx_t * - ztrie_hit_parameters (ztrie_t *self); - -// *** Draft method, for development use, may change without warning *** -// Returns the asterisk matched part of a route, if there has been no match -// or no asterisk match, returns NULL\&. -CZMQ_EXPORT const char * - ztrie_hit_asterisk_match (ztrie_t *self); - -// *** Draft method, for development use, may change without warning *** -// Print the trie -CZMQ_EXPORT void - ztrie_print (ztrie_t *self); - -// *** Draft method, for development use, may change without warning *** -// Self test of this class\&. -CZMQ_EXPORT void - ztrie_test (bool verbose); - -#endif // CZMQ_BUILD_DRAFT_API -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/ztrie\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -This is a variant of a trie or prefix tree where all the descendants of a node have a common prefix of the string associated with that node\&. This implementation is specialized for strings that can be tokenized by a delimiter like a URL, URI or URN\&. Routes in the tree can be matched by regular expressions and by using capturing groups parts of a matched route can be easily obtained\&. -.sp -Note that the performance for pure string based matching is okay but on short strings zhash and zhashx are 3\-4 times faster\&. -.SH "EXAMPLE" -.PP -\fBFrom ztrie_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Create a new trie for matching strings that can be tokenized by a slash -// (e\&.g\&. URLs minus the protocol, address and port)\&. -ztrie_t *self = ztrie_new (\*(Aq/\*(Aq); -assert (self); - -int ret = 0; - -// Let\*(Aqs start by inserting a couple of routes into the trie\&. -// This one is for the route \*(Aq/foo/bar\*(Aq the slash at the beginning of the -// route is important because everything before the first delimiter will be -// discarded\&. A slash at the end of a route is optional though\&. The data -// associated with this node is passed without destroy function which means -// it must be destroyed by the caller\&. -int foo_bar_data = 10; -ret = ztrie_insert_route (self, "/foo/bar", &foo_bar_data, NULL); -assert (ret == 0); - -// Now suppose we like to match all routes with two tokens that start with -// \*(Aq/foo/\*(Aq but aren\*(Aqt \*(Aq/foo/bar\*(Aq\&. This is possible by using regular -// expressions which are enclosed in an opening and closing curly bracket\&. -// Tokens that contain regular expressions are always match after string -// based tokens\&. -// Note: There is no order in which regular expressions are sorted thus -// if you enter multiple expressions for a route you will have to make -// sure they don\*(Aqt have overlapping results\&. For example \*(Aq/foo/{[^/]+}\*(Aq -// and \*(Aq/foo/{\ed+} having could turn out badly\&. -int foo_other_data = 100; -ret = ztrie_insert_route (self, "/foo/{[^/]+}", &foo_other_data, NULL); -assert (ret == 0); - -// Regular expression are only matched against tokens of the same level\&. -// This allows us to append to are route with a regular expression as if -// it were a string\&. -ret = ztrie_insert_route (self, "/foo/{[^/]+}/gulp", NULL, NULL); -assert (ret == 0); - -// Routes are identified by their endpoint, which is the last token of the route\&. -// It is possible to insert routes for a node that already exists but isn\*(Aqt an -// endpoint yet\&. The delimiter at the end of a route is optional and has no effect\&. -ret = ztrie_insert_route (self, "/foo/", NULL, NULL); -assert (ret == 0); - -// If you try to insert a route which already exists the method will return \-1\&. -ret = ztrie_insert_route (self, "/foo", NULL, NULL); -assert (ret == \-1); - -// It is not allowed to insert routes with empty tokens\&. -ret = ztrie_insert_route (self, "//foo", NULL, NULL); -assert (ret == \-1); - -// Everything before the first delimiter is ignored so \*(Aqfoo/bar/baz\*(Aq is equivalent -// to \*(Aq/bar/baz\*(Aq\&. -ret = ztrie_insert_route (self, "foo/bar/baz", NULL, NULL); -assert (ret == 0); -ret = ztrie_insert_route (self, "/bar/baz", NULL, NULL); -assert (ret == \-1); - -// Of course you are allowed to remove routes, in case there is data associated with a -// route and a destroy data function has been supplied that data will be destroyed\&. -ret = ztrie_remove_route (self, "/foo"); -assert (ret == 0); - -// Removing a non existent route will as well return \-1\&. -ret = ztrie_remove_route (self, "/foo"); -assert (ret == \-1); - -// Removing a route with a regular expression must exactly match the entered one\&. -ret = ztrie_remove_route (self, "/foo/{[^/]+}"); -assert (ret == 0); - -// Next we like to match a path by regular expressions and also extract matched -// parts of a route\&. This can be done by naming the regular expression\&. The name of a -// regular expression is entered at the beginning of the curly brackets and separated -// by a colon from the regular expression\&. The first one in this examples is named -// \*(Aqname\*(Aq and names the expression \*(Aq[^/]\*(Aq\&. If there is no capturing group defined in -// the expression the whole matched string will be associated with this parameter\&. In -// case you don\*(Aqt like the get the whole matched string use a capturing group, like -// it has been done for the \*(Aqid\*(Aq parameter\&. This is nice but you can even match as -// many parameter for a token as you like\&. Therefore simply put the parameter names -// separated by colons in front of the regular expression and make sure to add a -// capturing group for each parameter\&. The first parameter will be associated with -// the first capturing and so on\&. -char *data = (char *) malloc (80); -sprintf (data, "%s", "Hello World!"); -ret = ztrie_insert_route (self, "/baz/{name:[^/]+}/{id:\-\-(\e\ed+)}/{street:nr:(\e\ea+)(\e\ed+)}", data, NULL); -assert (ret == 0); - -// There is a lot you can do with regular expression but matching routes -// of arbitrary length wont work\&. Therefore we make use of the asterisk -// operator\&. Just place it at the end of your route, e\&.g\&. \*(Aq/config/bar/*\*(Aq\&. -ret = ztrie_insert_route (self, "/config/bar/*", NULL, NULL); -assert (ret == 0); - -// Appending to an asterisk as you would to with a regular expression -// isn\*(Aqt valid\&. -ret = ztrie_insert_route (self, "/config/bar/*/bar", NULL, NULL); -assert (ret == \-1); - -// The asterisk operator will only work as a leaf in the tree\&. If you -// enter an asterisk in the middle of your route it will simply be -// interpreted as a string\&. -ret = ztrie_insert_route (self, "/test/*/bar", NULL, NULL); -assert (ret == 0); - -// If a parent has an asterisk as child it is not allowed to have -// other siblings\&. -ret = ztrie_insert_route (self, "/config/bar/foo/glup", NULL, NULL); -assert (ret != 0); - -// Test matches -bool hasMatch = false; - -// The route \*(Aq/bar/foo\*(Aq will fail to match as this route has never been inserted\&. -hasMatch = ztrie_matches (self, "/bar/foo"); -assert (!hasMatch); - -// The route \*(Aq/foo/bar\*(Aq will match and we can obtain the data associated with it\&. -hasMatch = ztrie_matches (self, "/foo/bar"); -assert (hasMatch); -int foo_bar_hit_data = *((int *) ztrie_hit_data (self)); -assert (foo_bar_data == foo_bar_hit_data); - -// This route is part of another but is no endpoint itself thus the matches will fail\&. -hasMatch = ztrie_matches (self, "/baz/blub"); -assert (!hasMatch); - -// This route will match our named regular expressions route\&. Thus we can extract data -// from the route by their names\&. -hasMatch = ztrie_matches (self, "/baz/blub/\-\-11/abc23"); -assert (hasMatch); -char *match_data = (char *) ztrie_hit_data (self); -assert (streq ("Hello World!", match_data)); -zhashx_t *parameters = ztrie_hit_parameters (self); -assert (zhashx_size (parameters) == 4); -assert (streq ("blub", (char *) zhashx_lookup (parameters, "name"))); -assert (streq ("11", (char *) zhashx_lookup (parameters, "id"))); -assert (streq ("abc", (char *) zhashx_lookup (parameters, "street"))); -assert (streq ("23", (char *) zhashx_lookup (parameters, "nr"))); -zhashx_destroy (¶meters); - -// This will match our asterisk route \*(Aq/config/bar/*\*(Aq\&. As the result we -// can obtain the asterisk matched part of the route\&. -hasMatch = ztrie_matches (self, "/config/bar/foo/bar"); -assert (hasMatch); -assert (streq (ztrie_hit_asterisk_match (self), "foo/bar")); - -zstr_free (&data); -ztrie_destroy (&self); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man3/zuuid.3 b/phonelibs/zmq/aarch64-linux/share/man/man3/zuuid.3 deleted file mode 100644 index c5431245eb..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man3/zuuid.3 +++ /dev/null @@ -1,171 +0,0 @@ -'\" t -.\" Title: zuuid -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "ZUUID" "3" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zuuid \- UUID support class -.SH "SYNOPSIS" -.sp -.nf -// This is a stable class, and may not change except for emergencies\&. It -// is provided in stable builds\&. -// Create a new UUID object\&. -CZMQ_EXPORT zuuid_t * - zuuid_new (void); - -// Create UUID object from supplied ZUUID_LEN\-octet value\&. -CZMQ_EXPORT zuuid_t * - zuuid_new_from (const byte *source); - -// Destroy a specified UUID object\&. -CZMQ_EXPORT void - zuuid_destroy (zuuid_t **self_p); - -// Set UUID to new supplied ZUUID_LEN\-octet value\&. -CZMQ_EXPORT void - zuuid_set (zuuid_t *self, const byte *source); - -// Set UUID to new supplied string value skipping \*(Aq\-\*(Aq and \*(Aq{\*(Aq \*(Aq}\*(Aq -// optional delimiters\&. Return 0 if OK, else returns \-1\&. -CZMQ_EXPORT int - zuuid_set_str (zuuid_t *self, const char *source); - -// Return UUID binary data\&. -CZMQ_EXPORT const byte * - zuuid_data (zuuid_t *self); - -// Return UUID binary size -CZMQ_EXPORT size_t - zuuid_size (zuuid_t *self); - -// Returns UUID as string -CZMQ_EXPORT const char * - zuuid_str (zuuid_t *self); - -// Return UUID in the canonical string format: 8\-4\-4\-4\-12, in lower -// case\&. Caller does not modify or free returned value\&. See -// http://en\&.wikipedia\&.org/wiki/Universally_unique_identifier -CZMQ_EXPORT const char * - zuuid_str_canonical (zuuid_t *self); - -// Store UUID blob in target array -CZMQ_EXPORT void - zuuid_export (zuuid_t *self, byte *target); - -// Check if UUID is same as supplied value -CZMQ_EXPORT bool - zuuid_eq (zuuid_t *self, const byte *compare); - -// Check if UUID is different from supplied value -CZMQ_EXPORT bool - zuuid_neq (zuuid_t *self, const byte *compare); - -// Make copy of UUID object; if uuid is null, or memory was exhausted, -// returns null\&. -CZMQ_EXPORT zuuid_t * - zuuid_dup (zuuid_t *self); - -// Self test of this class\&. -CZMQ_EXPORT void - zuuid_test (bool verbose); - -Please add \*(Aq@interface\*(Aq section in \*(Aq\&./\&.\&./src/zuuid\&.c\*(Aq\&. -.fi -.SH "DESCRIPTION" -.sp -The zuuid class generates UUIDs and provides methods for working with them\&. If you build CZMQ with libuuid, on Unix/Linux, it will use that library\&. On Windows it will use UuidCreate()\&. Otherwise it will use a random number generator to produce convincing imitations of UUIDs\&. -.sp -Please add \fI@discuss\fR section in \fI\&./\&.\&./src/zuuid\&.c\fR\&. -.SH "EXAMPLE" -.PP -\fBFrom zuuid_test method\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Simple create/destroy test -assert (ZUUID_LEN == 16); -assert (ZUUID_STR_LEN == 32); - -zuuid_t *uuid = zuuid_new (); -assert (uuid); -assert (zuuid_size (uuid) == ZUUID_LEN); -assert (strlen (zuuid_str (uuid)) == ZUUID_STR_LEN); -zuuid_t *copy = zuuid_dup (uuid); -assert (streq (zuuid_str (uuid), zuuid_str (copy))); - -// Check set/set_str/export methods -const char *myuuid = "8CB3E9A9649B4BEF8DE225E9C2CEBB38"; -const char *myuuid2 = "8CB3E9A9\-649B\-4BEF\-8DE2\-25E9C2CEBB38"; -const char *myuuid3 = "{8CB3E9A9\-649B\-4BEF\-8DE2\-25E9C2CEBB38}"; -const char *myuuid4 = "8CB3E9A9649B4BEF8DE225E9C2CEBB3838"; -int rc = zuuid_set_str (uuid, myuuid); -assert (rc == 0); -assert (streq (zuuid_str (uuid), myuuid)); -rc = zuuid_set_str (uuid, myuuid2); -assert (rc == 0); -assert (streq (zuuid_str (uuid), myuuid)); -rc = zuuid_set_str (uuid, myuuid3); -assert (rc == 0); -assert (streq (zuuid_str (uuid), myuuid)); -rc = zuuid_set_str (uuid, myuuid4); -assert (rc == \-1); -byte copy_uuid [ZUUID_LEN]; -zuuid_export (uuid, copy_uuid); -zuuid_set (uuid, copy_uuid); -assert (streq (zuuid_str (uuid), myuuid)); - -// Check the canonical string format -assert (streq (zuuid_str_canonical (uuid), - "8cb3e9a9\-649b\-4bef\-8de2\-25e9c2cebb38")); - -zuuid_destroy (&uuid); -zuuid_destroy (©); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man7/czmq.7 b/phonelibs/zmq/aarch64-linux/share/man/man7/czmq.7 deleted file mode 100644 index 6de419cb00..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man7/czmq.7 +++ /dev/null @@ -1,1358 +0,0 @@ -'\" t -.\" Title: czmq -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.76.1 -.\" Date: 12/31/2016 -.\" Manual: CZMQ Manual -.\" Source: CZMQ 4.0.2 -.\" Language: English -.\" -.TH "CZMQ" "7" "12/31/2016" "CZMQ 4\&.0\&.2" "CZMQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -czmq \- high\-level C binding for ZeroMQ -.SH "SYNOPSIS" -.sp -.nf -#include - -cc [\*(Aqflags\*(Aq] \*(Aqfiles\*(Aq \-lzmq \-lczmq [\*(Aqlibraries\*(Aq] -.fi -.SH "DESCRIPTION" -.SS "Classes" -.sp -These classes provide the main socket and message API: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzsock\fR(3) -\- working with ZeroMQ sockets (high\-level) -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzstr\fR(3) -\- sending and receiving strings -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzmsg\fR(3) -\- working with multipart messages -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzframe\fR(3) -\- working with single message frames -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzactor\fR(3) -\- Actor class (socket + thread) -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzloop\fR(3) -\- event\-driven reactor -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzpoller\fR(3) -\- trivial socket poller class -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzproxy\fR(3) -\- proxy actor (like zmq_proxy_steerable) -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzmonitor\fR(3) -\- monitor events on ZeroMQ sockets -.RE -.sp -These classes support authentication and encryption: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzauth\fR(3) -\- authentication actor for ZeroMQ servers -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzcert\fR(3) -\- work with CURVE security certificates -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzcertstore\fR(3) -\- work with CURVE security certificate stores -.RE -.sp -These classes provide generic containers: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzhash\fR(3) -\- simple generic hash container -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzhashx\fR(3) -\- extended generic hash container -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzlist\fR(3) -\- simple generic list container -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzlistx\fR(3) -\- extended generic list container -.RE -.sp -These classes wrap\-up non\-portable functionality: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzbeacon\fR(3) -\- LAN discovery and presence -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzclock\fR(3) -\- millisecond clocks and delays -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzdir\fR(3) -\- work with file\-system directories -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzdir_patch\fR(3) -\- work with directory differences -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzfile\fR(3) -\- work with file\-system files -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzsys\fR(3) -\- system\-level methods -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzuuid\fR(3) -\- UUID support class -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBziflist\fR(3) -\- list available network interfaces -.RE -.sp -And these utility classes add value: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzchunk\fR(3) -\- work with memory chunks -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzconfig\fR(3) -\- work with textual config files -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzrex\fR(3) -\- work with regular expressions -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzgossip\fR(3) -\- decentralized configuration management -.RE -.sp -These classes are deprecated: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzctx\fR(3) -\- working with ZeroMQ contexts -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzsocket\fR(3) -\- working with ZeroMQ sockets (low\-level) -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzsockopt\fR(3) -\- get/set ZeroMQ socket options -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzthread\fR(3) -\- working with system threads -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzauth_v2\fR(3) -\- authentication for ZeroMQ servers -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzbeacon_v2\fR(3) -\- LAN discovery and presence -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzmonitor_v2\fR(3) -\- socket event monitor -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBzproxy_v2\fR(3) -\- zmq_proxy wrapper -.RE -.SS "Scope and Goals" -.sp -CZMQ has these goals: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -To wrap the \(/OMQ core API in semantics that are natural and lead to shorter, more readable applications\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -To hide the differences between versions of \(/OMQ\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -To provide a space for development of more sophisticated API semantics\&. -.RE -.SS "Ownership and License" -.sp -CZMQ is maintained by the ZeroMQ community at github\&.com/zeromq\&. Its other authors and contributors are listed in the AUTHORS file\&. -.sp -The contributors are listed in AUTHORS\&. This project uses the MPL v2 license, see LICENSE\&. -.SS "Contributing" -.sp -To submit an issue use the issue tracker at \m[blue]\fBhttp://github\&.com/zeromq/czmq/issues\fR\m[]\&. All discussion happens on the zeromq\-dev list or #zeromq IRC channel at irc\&.freenode\&.net\&. -.sp -The proper way to submit patches is to clone this repository, make your changes, and use git to create a patch or a pull request\&. See \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. All contributors are listed in AUTHORS\&. -.sp -All classes are maintained by a single person, who is the responsible editor for that class and who is named in the header as such\&. This is usually the originator of the class\&. When several people collaborate on a class, one single person is always the lead maintainer and the one to blame when it breaks\&. -.sp -The general rule is, if you contribute code to CZMQ you must be willing to maintain it as long as there are users of it\&. Code with no active maintainer will in general be deprecated and/or removed\&. -.SH "USING CZMQ" -.SS "Building and Installing" -.sp -CZMQ uses autotools for packaging\&. To build from git (all example commands are for Linux): -.sp -.if n \{\ -.RS 4 -.\} -.nf - git clone git://github\&.com/zeromq/czmq\&.git - cd czmq - sh autogen\&.sh - \&./configure - make all - sudo make install - sudo ldconfig -.fi -.if n \{\ -.RE -.\} -.sp -You will need the pkg\-config, libtool, and autoreconf packages\&. Set the LD_LIBRARY_PATH to /usr/local/libs unless you install elsewhere\&. -.sp -After building, you can run the CZMQ selftests: -.sp -.if n \{\ -.RS 4 -.\} -.nf - cd src - \&./czmq_selftest -.fi -.if n \{\ -.RE -.\} -.SS "Linking with an Application" -.sp -Include czmq\&.h in your application and link with CZMQ\&. Here is a typical gcc link command: -.sp -.if n \{\ -.RS 4 -.\} -.nf - gcc \-lczmq \-lzmq myapp\&.c \-o myapp -.fi -.if n \{\ -.RE -.\} -.sp -You should read czmq\&.h\&. This file includes zmq\&.h and the system header files that typical \(/OMQ applications will need\&. The provided \fIc\fR shell script lets you write simple portable build scripts: -.sp -.if n \{\ -.RS 4 -.\} -.nf - c \-lczmq \-lzmq \-l myapp -.fi -.if n \{\ -.RE -.\} -.SS "The Class Model" -.sp -CZMQ consists of classes, each class consisting of a \&.h and a \&.c\&. Classes may depend on other classes\&. -.sp -czmq\&.h includes all classes header files, all the time\&. For the user, CZMQ forms one single package\&. All classes start by including czmq\&.h\&. All applications that use CZMQ start by including czmq\&.h\&. czmq\&.h also defines a limited number of small, useful macros and typedefs that have proven useful for writing clearer C code\&. -.sp -All classes (with some exceptions) are based on a flat C class system and follow these rules (where \fIzclass\fR is the class name): -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Class typedef: -zclass_t -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Constructor: -zclass_new -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Destructor: -zclass_destroy -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Property methods: -zclass_property_set, -zclass_property -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Class structures are private (defined in the \&.c source but not the \&.h) -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Properties are accessed only via methods named as described above\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -In the class source code the object is always called -self\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -The constructor may take arbitrary arguments, and returns NULL on failure, or a new object\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -The destructor takes a pointer to an object reference and nullifies it\&. -.RE -.sp -Return values for methods are: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -For methods that return an object reference, either the reference, or NULL on failure\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -For methods that signal success/failure, a return value of 0 means success, \-1 failure\&. -.RE -.sp -Private/static functions in a class are named s_functionname and are not exported via the header file\&. -.sp -All classes (with some exceptions) have a test method called zclass_test\&. -.SH "DESIGN IDEOLOGY" -.SS "The Problem with C" -.sp -C has the significant advantage of being a small language that, if we take a little care with formatting and naming, can be easily interchanged between developers\&. Every C developer will use much the same 90% of the language\&. Larger languages like C++ provide powerful abstractions like STL containers but at the cost of interchange\&. -.sp -The huge problem with C is that any realistic application needs packages of functionality to bring the language up to the levels we expect for the 21st century\&. Much can be done by using external libraries but every additional library is a dependency that makes the resulting applications harder to build and port\&. While C itself is a highly portable language (and can be made more so by careful use of the preprocessor), most C libraries consider themselves part of the operating system, and as such do not attempt to be portable\&. -.sp -The answer to this, as we learned from building enterprise\-level C applications at iMatix from 1995\-2005, is to create our own fully portable, high\-quality libraries of pre\-packaged functionality, in C\&. Doing this right solves both the requirements of richness of the language, and of portability of the final applications\&. -.SS "A Simple Class Model" -.sp -C has no standard API style\&. It is one thing to write a useful component, but something else to provide an API that is consistent and obvious across many components\&. We learned from building OpenAMQ (\m[blue]\fBhttp://www\&.openamq\&.org\fR\m[]), a messaging client and server of 0\&.5M LoC, that a consistent model for extending C makes life for the application developer much easier\&. -.sp -The general model is that of a class (the source package) that provides objects (in fact C structures)\&. The application creates objects and then works with them\&. When done, the application destroys the object\&. In C, we tend to use the same name for the object as the class, when we can, and it looks like this (to take a fictitious CZMQ class): -.sp -.if n \{\ -.RS 4 -.\} -.nf - zregexp_t *regexp = zregexp_new (regexp_string); - if (!regexp) - printf ("E: invalid regular expression: %s\en", regexp_string); - else - if (zregexp_match (regexp, input_buffer)) - printf ("I: successful match for %s\en", input buffer); - zregexp_destroy (&regexp); -.fi -.if n \{\ -.RE -.\} -.sp -As far as the C program is concerned, the object is a reference to a structure (not a void pointer)\&. We pass the object reference to all methods, since this is still C\&. We could do weird stuff like put method addresses into the structure so that we can emulate a C++ syntax but it\(cqs not worthwhile\&. The goal is not to emulate an OO system, it\(cqs simply to gain consistency\&. The constructor returns an object reference, or NULL if it fails\&. The destructor nullifies the class pointer, and is idempotent\&. -.sp -What we aim at here is the simplest possible consistent syntax\&. -.sp -No model is fully consistent, and classes can define their own rules if it helps make a better result\&. For example: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Some classes may not be opaque\&. For example, we have cases of generated serialization classes that encode and decode structures to/from binary buffers\&. It feels clumsy to have to use methods to access the properties of these classes\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -While every class has a new method that is the formal constructor, some methods may also act as constructors\&. For example, a "dup" method might take one object and return a second object\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -While every class has a destroy method that is the formal destructor, some methods may also act as destructors\&. For example, a method that sends an object may also destroy the object (so that ownership of any buffers can passed to background threads)\&. Such methods take the same "pointer to a reference" argument as the destroy method\&. -.RE -.SS "Naming Style" -.sp -CZMQ aims for short, consistent names, following the theory that names we use most often should be shortest\&. Classes get one\-word names, unless they are part of a family of classes in which case they may be two words, the first being the family name\&. Methods, similarly, get one\-word names and we aim for consistency across classes (so a method that does something semantically similar in two classes will get the same name in both)\&. So the canonical name for any method is: -.sp -.if n \{\ -.RS 4 -.\} -.nf - zclassname_methodname -.fi -.if n \{\ -.RE -.\} -.sp -And the reader can easily parse this without needing special syntax to separate the class name from the method name\&. -.SS "Containers" -.sp -After a long experiment with containers, we\(cqve decided that we need exactly two containers: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -A singly\-linked list\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -A hash table using text keys\&. -.RE -.sp -These are zlist and zhash, respectively\&. Both store void pointers, with no attempt to manage the details of contained objects\&. You can use these containers to create lists of lists, hashes of lists, hashes of hashes, etc\&. -.sp -We assume that at some point we\(cqll need to switch to a doubly\-linked list\&. -.SS "Portability" -.sp -Creating a portable C application can be rewarding in terms of maintaining a single code base across many platforms, and keeping (expensive) system\-specific knowledge separate from application developers\&. In most projects (like \(/OMQ core), there is no portability layer and application code does conditional compilation for all mixes of platforms\&. This leads to quite messy code\&. -.sp -czmq acts as a portability layer, similar to but thinner than libraries like the [Apache Portable Runtime](\m[blue]\fBhttp://apr\&.apache\&.org\fR\m[]) (APR)\&. -.sp -These are the places a C application is subject to arbitrary system differences: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Different compilers may offer slightly different variants of the C language, often lacking specific types or using neat non\-portable names\&. Windows is a big culprit here\&. We solve this by -\fIpatching\fR -the language in czmq_prelude\&.h, e\&.g\&. defining int64_t on Windows\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -System header files are inconsistent, i\&.e\&. you need to include different files depending on the OS type and version\&. We solve this by pulling in all necessary header files in czmq_prelude\&.h\&. This is a proven brute\-force approach that increases recompilation times but eliminates a major source of pain\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -System libraries are inconsistent, i\&.e\&. you need to link with different libraries depending on the OS type and version\&. We solve this with an external compilation tool, -\fIC\fR, which detects the OS type and version (at runtime) and builds the necessary link commands\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -System functions are inconsistent, i\&.e\&. you need to call different functions depending, again, on OS type and version\&. We solve this by building small abstract classes that handle specific areas of functionality, and doing conditional compilation in these\&. -.RE -.sp -An example of the last: -.sp -.if n \{\ -.RS 4 -.\} -.nf - #if (defined (__UNIX__)) - pid = GetCurrentProcessId(); - #elif (defined (__WINDOWS__)) - pid = getpid (); - #else - pid = 0; - #endif -.fi -.if n \{\ -.RE -.\} -.sp -CZMQ uses the GNU autotools system, so non\-portable code can use the macros this defines\&. It can also use macros defined by the czmq_prelude\&.h header file\&. -.SS "Technical Aspects" -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBThread safety\fR: the use of opaque structures is thread safe, though \(/OMQ applications should not share state between threads in any case\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBName spaces\fR: we prefix class names with -z, which ensures that all exported functions are globally safe\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBLibrary versioning\fR: we don\(cqt make any attempt to version the library at this stage\&. Classes are in our experience highly stable once they are built and tested, the only changes typically being added methods\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBPerformance\fR: for critical path processing, you may want to avoid creating and destroying classes\&. However on modern Linux systems the heap allocator is very fast\&. Individual classes can choose whether or not to nullify their data on allocation\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBSelf\-testing\fR: every class has a -selftest -method that runs through the methods of the class\&. In theory, calling all selftest functions of all classes does a full unit test of the library\&. The -czmq_selftest -application does this\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} - -\fBMemory management\fR: CZMQ classes do not use any special memory management techiques to detect leaks\&. We\(cqve done this in the past but it makes the code relatively complex\&. Instead, we do memory leak testing using tools like valgrind\&. -.RE -.SH "UNDER THE HOOD" -.SS "Adding a New Class" -.sp -If you define a new CZMQ class myclass you need to: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Write the -zmyclass\&.c -and -zmyclass\&.h -source files, in -src -and -include -respectively\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Add`#include ` to -include/czmq\&.h\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Add the myclass header and test call to -src/czmq_selftest\&.c\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Add a reference documentation to -\fIdoc/zmyclass\&.txt\fR\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Add myclass to \*(Aqsrc/Makefile\&.am` and -doc/Makefile\&.am\&. -.RE -.sp -The bin/newclass\&.sh shell script will automate these steps for you\&. -.SS "Coding Style" -.sp -In general the zctx class defines the style for the whole library\&. The overriding rules for coding style are consistency, clarity, and ease of maintenance\&. We use the C99 standard for syntax including principally: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -The // comment style\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Variables definitions placed in or before the code that uses them\&. -.RE -.sp -So while ANSI C code might say: -.sp -.if n \{\ -.RS 4 -.\} -.nf - zblob_t *file_buffer; /* Buffer for our file */ - \&.\&.\&. (100 lines of code) - file_buffer = zblob_new (); - \&.\&.\&. -.fi -.if n \{\ -.RE -.\} -.sp -The style in CZMQ would be: -.sp -.if n \{\ -.RS 4 -.\} -.nf - zblob_t *file_buffer = zblob_new (); -.fi -.if n \{\ -.RE -.\} -.SS "Assertions" -.sp -We use assertions heavily to catch bad argument values\&. The CZMQ classes do not attempt to validate arguments and report errors; bad arguments are treated as fatal application programming errors\&. -.sp -We also use assertions heavily on calls to system functions that are never supposed to fail, where failure is to be treated as a fatal non\-recoverable error (e\&.g\&. running out of memory)\&. -.sp -Assertion code should always take this form: -.sp -.if n \{\ -.RS 4 -.\} -.nf - int rc = some_function (arguments); - assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.sp -Rather than the side\-effect form: -.sp -.if n \{\ -.RS 4 -.\} -.nf - assert (some_function (arguments) == 0); -.fi -.if n \{\ -.RE -.\} -.sp -Since assertions may be removed by an optimizing compiler\&. -.SS "Documentation" -.sp -Man pages are generated from the class header and source files via the doc/mkman tool, and similar functionality in the gitdown tool (\m[blue]\fBhttp://github\&.com/imatix/gitdown\fR\m[])\&. The header file for a class must wrap its interface as follows (example is from include/zclock\&.h): -.sp -.if n \{\ -.RS 4 -.\} -.nf - // @interface - // Sleep for a number of milliseconds - void - zclock_sleep (int msecs); - - // Return current system clock as milliseconds - int64_t - zclock_time (void); - - // Self test of this class - int - zclock_test (Bool verbose); - // @end -.fi -.if n \{\ -.RE -.\} -.sp -The source file for a class must provide documentation as follows: -.sp -.if n \{\ -.RS 4 -.\} -.nf - /* - @header - \&.\&.\&.short explanation of class\&.\&.\&. - @discuss - \&.\&.\&.longer discussion of how it works\&.\&.\&. - @end - */ -.fi -.if n \{\ -.RE -.\} -.sp -The source file for a class then provides the self test example as follows: -.sp -.if n \{\ -.RS 4 -.\} -.nf - // @selftest - int64_t start = zclock_time (); - zclock_sleep (10); - assert ((zclock_time () \- start) >= 10); - // @end -.fi -.if n \{\ -.RE -.\} -.sp -The template for man pages is in doc/mkman\&. -.SS "Development" -.sp -CZMQ is developed through a test\-driven process that guarantees no memory violations or leaks in the code: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Modify a class or method\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Update the test method for that class\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Run the -\fIselftest\fR -script, which uses the Valgrind memcheck tool\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Repeat until perfect\&. -.RE -.SS "Porting CZMQ" -.sp -When you try CZMQ on an OS that it\(cqs not been used on (ever, or for a while), you will hit code that does not compile\&. In some cases the patches are trivial, in other cases (usually when porting to Windows), the work needed to build equivalent functionality may be quite heavy\&. In any case, the benefit is that once ported, the functionality is available to all applications\&. -.sp -Before attempting to patch code for portability, please read the czmq_prelude\&.h header file\&. There are several typical types of changes you may need to make to get functionality working on a specific operating system: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Defining typedefs which are missing on that specific compiler: do this in czmq_prelude\&.h\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Defining macros that rename exotic library functions to more conventional names: do this in czmq_prelude\&.h\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Reimplementing specific methods to use a non\-standard API: this is typically needed on Windows\&. Do this in the relevant class, using #ifdefs to properly differentiate code for different platforms\&. -.RE -.sp -The canonical \fIstandard operating system\fR for all CZMQ code is Linux, gcc, POSIX\&. -.SH "AUTHORS" -.sp -The czmq manual was written by the authors in the AUTHORS file\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fB\%\fR\m[] -.sp -Report bugs to the email <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYRIGHT" -.sp -Copyright (c) the Contributors as noted in the AUTHORS file\&. This file is part of CZMQ, the high\-level C binding for 0MQ: http://czmq\&.zeromq\&.org\&. This Source Code Form is subject to the terms of the Mozilla Public License, v\&. 2\&.0\&. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla\&.org/MPL/2\&.0/\&. LICENSE included with the czmq distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq.7 b/phonelibs/zmq/aarch64-linux/share/man/man7/zmq.7 deleted file mode 100644 index 45224c4859..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq.7 +++ /dev/null @@ -1,275 +0,0 @@ -'\" t -.\" Title: zmq -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ" "7" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq \- 0MQ lightweight messaging kernel -.SH "SYNOPSIS" -.sp -\fB#include \fR -.sp -\fBcc\fR [\fIflags\fR] \fIfiles\fR \fB\-lzmq\fR [\fIlibraries\fR] -.SH "DESCRIPTION" -.sp -The 0MQ lightweight messaging kernel is a library which extends the standard socket interfaces with features traditionally provided by specialised \fImessaging middleware\fR products\&. 0MQ sockets provide an abstraction of asynchronous \fImessage queues\fR, multiple \fImessaging patterns\fR, message filtering (\fIsubscriptions\fR), seamless access to multiple \fItransport protocols\fR and more\&. -.sp -This documentation presents an overview of 0MQ concepts, describes how 0MQ abstracts standard sockets and provides a reference manual for the functions provided by the 0MQ library\&. -.SS "Context" -.sp -The 0MQ \fIcontext\fR keeps the list of sockets and manages the async I/O thread and internal queries\&. -.sp -Before using any 0MQ library functions you must create a 0MQ \fIcontext\fR\&. When you exit your application you must destroy the \fIcontext\fR\&. These functions let you work with \fIcontexts\fR: -.PP -Create a new 0MQ context -.RS 4 -\fBzmq_ctx_new\fR(3) -.RE -.PP -Work with context properties -.RS 4 -\fBzmq_ctx_set\fR(3)\fBzmq_ctx_get\fR(3) -.RE -.PP -Destroy a 0MQ context -.RS 4 -\fBzmq_ctx_shutdown\fR(3)\fBzmq_ctx_term\fR(3) -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBThread safety\fR -.RS 4 -.sp -A 0MQ \fIcontext\fR is thread safe and may be shared among as many application threads as necessary, without any additional locking required on the part of the caller\&. -.sp -Individual 0MQ \fIsockets\fR are \fInot\fR thread safe except in the case where full memory barriers are issued when migrating a socket from one thread to another\&. In practice this means applications can create a socket in one thread with \fIzmq_socket()\fR and then pass it to a \fInewly created\fR thread as part of thread initialisation, for example via a structure passed as an argument to \fIpthread_create()\fR\&. -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBMultiple contexts\fR -.RS 4 -.sp -Multiple \fIcontexts\fR may coexist within a single application\&. Thus, an application can use 0MQ directly and at the same time make use of any number of additional libraries or components which themselves make use of 0MQ as long as the above guidelines regarding thread safety are adhered to\&. -.RE -.SS "Messages" -.sp -A 0MQ message is a discrete unit of data passed between applications or components of the same application\&. 0MQ messages have no internal structure and from the point of view of 0MQ itself they are considered to be opaque binary data\&. -.sp -The following functions are provided to work with messages: -.PP -Initialise a message -.RS 4 -\fBzmq_msg_init\fR(3)\fBzmq_msg_init_size\fR(3)\fBzmq_msg_init_data\fR(3) -.RE -.PP -Sending and receiving a message -.RS 4 -\fBzmq_msg_send\fR(3)\fBzmq_msg_recv\fR(3) -.RE -.PP -Release a message -.RS 4 -\fBzmq_msg_close\fR(3) -.RE -.PP -Access message content -.RS 4 -\fBzmq_msg_data\fR(3)\fBzmq_msg_size\fR(3)\fBzmq_msg_more\fR(3) -.RE -.PP -Work with message properties -.RS 4 -\fBzmq_msg_gets\fR(3)\fBzmq_msg_get\fR(3)\fBzmq_msg_set\fR(3) -.RE -.PP -Message manipulation -.RS 4 -\fBzmq_msg_copy\fR(3)\fBzmq_msg_move\fR(3) -.RE -.SS "Sockets" -.sp -0MQ sockets present an abstraction of a asynchronous \fImessage queue\fR, with the exact queueing semantics depending on the socket type in use\&. See \fBzmq_socket\fR(3) for the socket types provided\&. -.sp -The following functions are provided to work with sockets: -.PP -Creating a socket -.RS 4 -\fBzmq_socket\fR(3) -.RE -.PP -Closing a socket -.RS 4 -\fBzmq_close\fR(3) -.RE -.PP -Manipulating socket options -.RS 4 -\fBzmq_getsockopt\fR(3)\fBzmq_setsockopt\fR(3) -.RE -.PP -Establishing a message flow -.RS 4 -\fBzmq_bind\fR(3)\fBzmq_connect\fR(3) -.RE -.PP -Sending and receiving messages -.RS 4 -\fBzmq_msg_send\fR(3)\fBzmq_msg_recv\fR(3)\fBzmq_send\fR(3)\fBzmq_recv\fR(3)\fBzmq_send_const\fR(3) -.RE -.PP -Monitoring socket events -.RS 4 -\fBzmq_socket_monitor\fR(3) -.RE -.PP -\fBInput/output multiplexing\fR. 0MQ provides a mechanism for applications to multiplex input/output events over a set containing both 0MQ sockets and standard sockets\&. This mechanism mirrors the standard -\fIpoll()\fR -system call, and is described in detail in -\fBzmq_poll\fR(3)\&. -.SS "Transports" -.sp -A 0MQ socket can use multiple different underlying transport mechanisms\&. Each transport mechanism is suited to a particular purpose and has its own advantages and drawbacks\&. -.sp -The following transport mechanisms are provided: -.PP -Unicast transport using TCP -.RS 4 -\fBzmq_tcp\fR(7) -.RE -.PP -Reliable multicast transport using PGM -.RS 4 -\fBzmq_pgm\fR(7) -.RE -.PP -Local inter\-process communication transport -.RS 4 -\fBzmq_ipc\fR(7) -.RE -.PP -Local in\-process (inter\-thread) communication transport -.RS 4 -\fBzmq_inproc\fR(7) -.RE -.PP -Virtual Machine Communications Interface (VMC) transport -.RS 4 -\fBzmq_vmci\fR(7) -.RE -.PP -Unreliable unicast and multicast using UDP -.RS 4 -\fBzmq_udp\fR(7) -.RE -.SS "Proxies" -.sp -0MQ provides \fIproxies\fR to create fanout and fan\-in topologies\&. A proxy connects a \fIfrontend\fR socket to a \fIbackend\fR socket and switches all messages between the two sockets, opaquely\&. A proxy may optionally capture all traffic to a third socket\&. To start a proxy in an application thread, use \fBzmq_proxy\fR(3)\&. -.SS "Security" -.sp -A 0MQ socket can select a security mechanism\&. Both peers must use the same security mechanism\&. -.sp -The following security mechanisms are provided for IPC and TCP connections: -.PP -Null security -.RS 4 -\fBzmq_null\fR(7) -.RE -.PP -Plain\-text authentication using username and password -.RS 4 -\fBzmq_plain\fR(7) -.RE -.PP -Elliptic curve authentication and encryption -.RS 4 -\fBzmq_curve\fR(7) -.RE -.PP -Generate a CURVE keypair in armored text format -.RS 4 -\fBzmq_curve_keypair\fR(3) -.RE -.sp -Derive a CURVE public key from a secret key: \fBzmq_curve_public\fR(3) -.PP -Converting keys to/from armoured text strings -.RS 4 -\fBzmq_z85_decode\fR(3)\fBzmq_z85_encode\fR(3) -.RE -.SH "ERROR HANDLING" -.sp -The 0MQ library functions handle errors using the standard conventions found on POSIX systems\&. Generally, this means that upon failure a 0MQ library function shall return either a NULL value (if returning a pointer) or a negative value (if returning an integer), and the actual error code shall be stored in the \fIerrno\fR variable\&. -.sp -On non\-POSIX systems some users may experience issues with retrieving the correct value of the \fIerrno\fR variable\&. The \fIzmq_errno()\fR function is provided to assist in these cases; for details refer to \fBzmq_errno\fR(3)\&. -.sp -The \fIzmq_strerror()\fR function is provided to translate 0MQ\-specific error codes into error message strings; for details refer to \fBzmq_strerror\fR(3)\&. -.SH "UTILITY" -.sp -The following utility functions are provided: -.PP -Working with atomic counters -.RS 4 -\fBzmq_atomic_counter_new\fR(3)\fBzmq_atomic_counter_set\fR(3)\fBzmq_atomic_counter_inc\fR(3)\fBzmq_atomic_counter_dec\fR(3)\fBzmq_atomic_counter_value\fR(3)\fBzmq_atomic_counter_destroy\fR(3) -.RE -.SH "MISCELLANEOUS" -.sp -The following miscellaneous functions are provided: -.PP -Report 0MQ library version -.RS 4 -\fBzmq_version\fR(3) -.RE -.SH "LANGUAGE BINDINGS" -.sp -The 0MQ library provides interfaces suitable for calling from programs in any language; this documentation documents those interfaces as they would be used by C programmers\&. The intent is that programmers using 0MQ from other languages shall refer to this documentation alongside any documentation provided by the vendor of their language binding\&. -.sp -Language bindings (C++, Python, PHP, Ruby, Java and more) are provided by members of the 0MQ community and pointers can be found on the 0MQ website\&. -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. -.SH "RESOURCES" -.sp -Main web site: \m[blue]\fBhttp://www\&.zeromq\&.org/\fR\m[] -.sp -Report bugs to the 0MQ development mailing list: <\m[blue]\fBzeromq\-dev@lists\&.zeromq\&.org\fR\m[]\&\s-2\u[1]\d\s+2> -.SH "COPYING" -.sp -Free use of this software is granted under the terms of the GNU Lesser General Public License (LGPL)\&. For details see the files COPYING and COPYING\&.LESSER included with the 0MQ distribution\&. -.SH "NOTES" -.IP " 1." 4 -zeromq-dev@lists.zeromq.org -.RS 4 -\%mailto:zeromq-dev@lists.zeromq.org -.RE diff --git a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_curve.7 b/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_curve.7 deleted file mode 100644 index 675effc437..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_curve.7 +++ /dev/null @@ -1,93 +0,0 @@ -'\" t -.\" Title: zmq_curve -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_CURVE" "7" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_curve \- secure authentication and confidentiality -.SH "SYNOPSIS" -.sp -The CURVE mechanism defines a mechanism for secure authentication and confidentiality for communications between a client and a server\&. CURVE is intended for use on public networks\&. The CURVE mechanism is defined by this document: \m[blue]\fBhttp://rfc\&.zeromq\&.org/spec:25\fR\m[]\&. -.SH "CLIENT AND SERVER ROLES" -.sp -A socket using CURVE can be either client or server, at any moment, but not both\&. The role is independent of bind/connect direction\&. -.sp -A socket can change roles at any point by setting new options\&. The role affects all zmq_connect and zmq_bind calls that follow it\&. -.sp -To become a CURVE server, the application sets the ZMQ_CURVE_SERVER option on the socket, and then sets the ZMQ_CURVE_SECRETKEY option to provide the socket with its long\-term secret key\&. The application does not provide the socket with its long\-term public key, which is used only by clients\&. -.sp -To become a CURVE client, the application sets the ZMQ_CURVE_SERVERKEY option with the long\-term public key of the server it intends to connect to, or accept connections from, next\&. The application then sets the ZMQ_CURVE_PUBLICKEY and ZMQ_CURVE_SECRETKEY options with its client long\-term key pair\&. -.sp -If the server does authentication it will be based on the client\(cqs long term public key\&. -.SH "KEY ENCODING" -.sp -The standard representation for keys in source code is either 32 bytes of base 256 (binary) data, or 40 characters of base 85 data encoded using the Z85 algorithm defined by \m[blue]\fBhttp://rfc\&.zeromq\&.org/spec:32\fR\m[]\&. -.sp -The Z85 algorithm is designed to produce printable key strings for use in configuration files, the command line, and code\&. There is a reference implementation in C at \m[blue]\fBhttps://github\&.com/zeromq/rfc/tree/master/src\fR\m[]\&. -.SH "TEST KEY VALUES" -.sp -For test cases, the client shall use this long\-term key pair (specified as hexadecimal and in Z85): -.sp -.if n \{\ -.RS 4 -.\} -.nf -public: - BB88471D65E2659B30C55A5321CEBB5AAB2B70A398645C26DCA2B2FCB43FC518 - Yne@$w\-vo}U?@Lns47E1%kR\&.o@n%FcmmsL/@{H8]yf7 - -secret: - 8E0BDD697628B91D8F245587EE95C5B04D48963F79259877B49CD9063AEAD3B7 - JTKVSB%%)wK0E\&.X)V>+}o?pNmC{O&4W4b!Ni{Lh6 -.fi -.if n \{\ -.RE -.\} -.SH "SEE ALSO" -.sp -\fBzmq_z85_encode\fR(3) \fBzmq_z85_decode\fR(3) \fBzmq_setsockopt\fR(3) \fBzmq_null\fR(7) \fBzmq_plain\fR(7) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_inproc.7 b/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_inproc.7 deleted file mode 100644 index a0b0e72d3f..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_inproc.7 +++ /dev/null @@ -1,103 +0,0 @@ -'\" t -.\" Title: zmq_inproc -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_INPROC" "7" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_inproc \- 0MQ local in\-process (inter\-thread) communication transport -.SH "SYNOPSIS" -.sp -The in\-process transport passes messages via memory directly between threads sharing a single 0MQ \fIcontext\fR\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -No I/O threads are involved in passing messages using the \fIinproc\fR transport\&. Therefore, if you are using a 0MQ \fIcontext\fR for in\-process messaging only you can initialise the \fIcontext\fR with zero I/O threads\&. See \fBzmq_init\fR(3) for details\&. -.sp .5v -.RE -.SH "ADDRESSING" -.sp -A 0MQ endpoint is a string consisting of a \fItransport\fR:// followed by an \fIaddress\fR\&. The \fItransport\fR specifies the underlying protocol to use\&. The \fIaddress\fR specifies the transport\-specific address to connect to\&. -.sp -For the in\-process transport, the transport is inproc, and the meaning of the \fIaddress\fR part is defined below\&. -.SS "Assigning a local address to a socket" -.sp -When assigning a local address to a \fIsocket\fR using \fIzmq_bind()\fR with the \fIinproc\fR transport, the \fIendpoint\fR shall be interpreted as an arbitrary string identifying the \fIname\fR to create\&. The \fIname\fR must be unique within the 0MQ \fIcontext\fR associated with the \fIsocket\fR and may be up to 256 characters in length\&. No other restrictions are placed on the format of the \fIname\fR\&. -.SS "Connecting a socket" -.sp -When connecting a \fIsocket\fR to a peer address using \fIzmq_connect()\fR with the \fIinproc\fR transport, the \fIendpoint\fR shall be interpreted as an arbitrary string identifying the \fIname\fR to connect to\&. Before version 4\&.0 he \fIname\fR must have been previously created by assigning it to at least one \fIsocket\fR within the same 0MQ \fIcontext\fR as the \fIsocket\fR being connected\&. Since version 4\&.0 the order of \fIzmq_bind()\fR and \fIzmq_connect()\fR does not matter just like for the tcp transport type\&. -.SH "EXAMPLES" -.PP -\fBAssigning a local address to a socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Assign the in\-process name "#1" -rc = zmq_bind(socket, "inproc://#1"); -assert (rc == 0); -// Assign the in\-process name "my\-endpoint" -rc = zmq_bind(socket, "inproc://my\-endpoint"); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.PP -\fBConnecting a socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Connect to the in\-process name "#1" -rc = zmq_connect(socket, "inproc://#1"); -assert (rc == 0); -// Connect to the in\-process name "my\-endpoint" -rc = zmq_connect(socket, "inproc://my\-endpoint"); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_bind\fR(3) \fBzmq_connect\fR(3) \fBzmq_ipc\fR(7) \fBzmq_tcp\fR(7) \fBzmq_pgm\fR(7) \fBzmq_vmci\fR(7) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_ipc.7 b/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_ipc.7 deleted file mode 100644 index c190b6f121..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_ipc.7 +++ /dev/null @@ -1,166 +0,0 @@ -'\" t -.\" Title: zmq_ipc -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_IPC" "7" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_ipc \- 0MQ local inter\-process communication transport -.SH "SYNOPSIS" -.sp -The inter\-process transport passes messages between local processes using a system\-dependent IPC mechanism\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -The inter\-process transport is currently only implemented on operating systems that provide UNIX domain sockets\&. -.sp .5v -.RE -.SH "ADDRESSING" -.sp -A 0MQ endpoint is a string consisting of a \fItransport\fR:// followed by an \fIaddress\fR\&. The \fItransport\fR specifies the underlying protocol to use\&. The \fIaddress\fR specifies the transport\-specific address to connect to\&. -.sp -For the inter\-process transport, the transport is ipc, and the meaning of the \fIaddress\fR part is defined below\&. -.SS "Binding a socket" -.sp -When binding a \fIsocket\fR to a local address using \fIzmq_bind()\fR with the \fIipc\fR transport, the \fIendpoint\fR shall be interpreted as an arbitrary string identifying the \fIpathname\fR to create\&. The \fIpathname\fR must be unique within the operating system namespace used by the \fIipc\fR implementation, and must fulfill any restrictions placed by the operating system on the format and length of a \fIpathname\fR\&. -.sp -When the address is wild\-card *, \fIzmq_bind()\fR shall generate a unique temporary pathname\&. The caller should retrieve this pathname using the ZMQ_LAST_ENDPOINT socket option\&. See \fBzmq_getsockopt\fR(3) for details\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -any existing binding to the same endpoint shall be overridden\&. That is, if a second process binds to an endpoint already bound by a process, this will succeed and the first process will lose its binding\&. In this behaviour, the \fIipc\fR transport is not consistent with the \fItcp\fR or \fIinproc\fR transports\&. -.sp .5v -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -the endpoint pathname must be writable by the process\&. When the endpoint starts with \fI/\fR, e\&.g\&., ipc:///pathname, this will be an \fIabsolute\fR pathname\&. If the endpoint specifies a directory that does not exist, the bind shall fail\&. -.sp .5v -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -on Linux only, when the endpoint pathname starts with @, the abstract namespace shall be used\&. The abstract namespace is independent of the filesystem and if a process attempts to bind an endpoint already bound by a process, it will fail\&. See unix(7) for details\&. -.sp .5v -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -IPC pathnames have a maximum size that depends on the operating system\&. On Linux, the maximum is 113 characters including the "ipc://" prefix (107 characters for the real path name)\&. -.sp .5v -.RE -.SS "Unbinding wild\-card address from a socket" -.sp -When wild\-card * \fIendpoint\fR was used in \fIzmq_bind()\fR, the caller should use real \fIendpoint\fR obtained from the ZMQ_LAST_ENDPOINT socket option to unbind this \fIendpoint\fR from a socket using \fIzmq_unbind()\fR\&. -.SS "Connecting a socket" -.sp -When connecting a \fIsocket\fR to a peer address using \fIzmq_connect()\fR with the \fIipc\fR transport, the \fIendpoint\fR shall be interpreted as an arbitrary string identifying the \fIpathname\fR to connect to\&. The \fIpathname\fR must have been previously created within the operating system namespace by assigning it to a \fIsocket\fR with \fIzmq_bind()\fR\&. -.SH "EXAMPLES" -.PP -\fBAssigning a local address to a socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Assign the pathname "/tmp/feeds/0" -rc = zmq_bind(socket, "ipc:///tmp/feeds/0"); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.PP -\fBConnecting a socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Connect to the pathname "/tmp/feeds/0" -rc = zmq_connect(socket, "ipc:///tmp/feeds/0"); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_bind\fR(3) \fBzmq_connect\fR(3) \fBzmq_inproc\fR(7) \fBzmq_tcp\fR(7) \fBzmq_pgm\fR(7) \fBzmq_vmci\fR(7) \fBzmq_getsockopt\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_null.7 b/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_null.7 deleted file mode 100644 index 42497a1159..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_null.7 +++ /dev/null @@ -1,40 +0,0 @@ -'\" t -.\" Title: zmq_null -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_NULL" "7" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_null \- no security or confidentiality -.SH "SYNOPSIS" -.sp -The NULL mechanism is defined by the ZMTP 3\&.0 specification: \m[blue]\fBhttp://rfc\&.zeromq\&.org/spec:23\fR\m[]\&. This is the default security mechanism for ZeroMQ sockets\&. -.SH "SEE ALSO" -.sp -\fBzmq_plain\fR(7) \fBzmq_curve\fR(7) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_pgm.7 b/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_pgm.7 deleted file mode 100644 index ea8ca3fc15..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_pgm.7 +++ /dev/null @@ -1,200 +0,0 @@ -'\" t -.\" Title: zmq_pgm -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_PGM" "7" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_pgm \- 0MQ reliable multicast transport using PGM -.SH "SYNOPSIS" -.sp -PGM (Pragmatic General Multicast) is a protocol for reliable multicast transport of data over IP networks\&. -.SH "DESCRIPTION" -.sp -0MQ implements two variants of PGM, the standard protocol where PGM datagrams are layered directly on top of IP datagrams as defined by RFC 3208 (the \fIpgm\fR transport) and "Encapsulated PGM" or EPGM where PGM datagrams are encapsulated inside UDP datagrams (the \fIepgm\fR transport)\&. -.sp -The \fIpgm\fR and \fIepgm\fR transports can only be used with the \fIZMQ_PUB\fR and \fIZMQ_SUB\fR socket types\&. -.sp -Further, PGM sockets are rate limited by default\&. For details, refer to the \fIZMQ_RATE\fR, and \fIZMQ_RECOVERY_IVL\fR options documented in \fBzmq_setsockopt\fR(3)\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBCaution\fR -.ps -1 -.br -.sp -The \fIpgm\fR transport implementation requires access to raw IP sockets\&. Additional privileges may be required on some operating systems for this operation\&. Applications not requiring direct interoperability with other PGM implementations are encouraged to use the \fIepgm\fR transport instead which does not require any special privileges\&. -.sp .5v -.RE -.SH "ADDRESSING" -.sp -A 0MQ endpoint is a string consisting of a \fItransport\fR:// followed by an \fIaddress\fR\&. The \fItransport\fR specifies the underlying protocol to use\&. The \fIaddress\fR specifies the transport\-specific address to connect to\&. -.sp -For the PGM transport, the transport is pgm, and for the EPGM protocol the transport is epgm\&. The meaning of the \fIaddress\fR part is defined below\&. -.SS "Connecting a socket" -.sp -When connecting a socket to a peer address using \fIzmq_connect()\fR with the \fIpgm\fR or \fIepgm\fR transport, the \fIendpoint\fR shall be interpreted as an \fIinterface\fR followed by a semicolon, followed by a \fImulticast address\fR, followed by a colon and a port number\&. -.sp -An \fIinterface\fR may be specified by either of the following: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -The interface name as defined by the operating system\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -The primary IPv4 address assigned to the interface, in its numeric representation\&. -.RE -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -Interface names are not standardised in any way and should be assumed to be arbitrary and platform dependent\&. On Win32 platforms no short interface names exist, thus only the primary IPv4 address may be used to specify an \fIinterface\fR\&. The \fIinterface\fR part can be omitted, in that case the default one will be selected\&. -.sp .5v -.RE -.sp -A \fImulticast address\fR is specified by an IPv4 multicast address in its numeric representation\&. -.SH "WIRE FORMAT" -.sp -Consecutive PGM datagrams are interpreted by 0MQ as a single continuous stream of data where 0MQ messages are not necessarily aligned with PGM datagram boundaries and a single 0MQ message may span several PGM datagrams\&. This stream of data consists of 0MQ messages encapsulated in \fIframes\fR as described in \fBzmq_tcp\fR(7)\&. -.SS "PGM datagram payload" -.sp -The following ABNF grammar represents the payload of a single PGM datagram as used by 0MQ: -.sp -.if n \{\ -.RS 4 -.\} -.nf -datagram = (offset data) -offset = 2OCTET -data = *OCTET -.fi -.if n \{\ -.RE -.\} -.sp -In order for late joining consumers to be able to identify message boundaries, each PGM datagram payload starts with a 16\-bit unsigned integer in network byte order specifying either the offset of the first message \fIframe\fR in the datagram or containing the value 0xFFFF if the datagram contains solely an intermediate part of a larger message\&. -.sp -Note that offset specifies where the first message begins rather than the first message part\&. Thus, if there are trailing message parts at the beginning of the packet the offset ignores them and points to first initial message part in the packet\&. -.sp -The following diagram illustrates the layout of a single PGM datagram payload: -.sp -.if n \{\ -.RS 4 -.\} -.nf -+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ -| offset (16 bits) | data | -+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ -.fi -.if n \{\ -.RE -.\} -.sp -The following diagram further illustrates how three example 0MQ frames are laid out in consecutive PGM datagram payloads: -.sp -.if n \{\ -.RS 4 -.\} -.nf -First datagram payload -+\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ -| Frame offset | Frame 1 | Frame 2, part 1 | -| 0x0000 | (Message 1) | (Message 2, part 1) | -+\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ - -Second datagram payload -+\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ -| Frame offset | Frame 2, part 2 | -| 0xFFFF | (Message 2, part 2) | -+\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ - -Third datagram payload -+\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-+ -| Frame offset | Frame 2, final 8 bytes | Frame 3 | -| 0x0008 | (Message 2, final 8 bytes) | (Message 3) | -+\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-+ -.fi -.if n \{\ -.RE -.\} -.SH "EXAMPLE" -.PP -\fBConnecting a socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Connecting to the multicast address 239\&.192\&.1\&.1, port 5555, -// using the first Ethernet network interface on Linux -// and the Encapsulated PGM protocol -rc = zmq_connect(socket, "epgm://eth0;239\&.192\&.1\&.1:5555"); -assert (rc == 0); -// Connecting to the multicast address 239\&.192\&.1\&.1, port 5555, -// using the network interface with the address 192\&.168\&.1\&.1 -// and the standard PGM protocol -rc = zmq_connect(socket, "pgm://192\&.168\&.1\&.1;239\&.192\&.1\&.1:5555"); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_connect\fR(3) \fBzmq_setsockopt\fR(3) \fBzmq_tcp\fR(7) \fBzmq_ipc\fR(7) \fBzmq_inproc\fR(7) \fBzmq_vmci\fR(7) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_plain.7 b/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_plain.7 deleted file mode 100644 index 912c92d5a9..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_plain.7 +++ /dev/null @@ -1,43 +0,0 @@ -'\" t -.\" Title: zmq_plain -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_PLAIN" "7" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_plain \- clear\-text authentication -.SH "SYNOPSIS" -.sp -The PLAIN mechanism defines a simple username/password mechanism that lets a server authenticate a client\&. PLAIN makes no attempt at security or confidentiality\&. It is intended for use on internal networks where security requirements are low\&. The PLAIN mechanism is defined by this document: \m[blue]\fBhttp://rfc\&.zeromq\&.org/spec:24\fR\m[]\&. -.SH "USAGE" -.sp -To use PLAIN, the server shall set the ZMQ_PLAIN_SERVER option, and the client shall set the ZMQ_PLAIN_USERNAME and ZMQ_PLAIN_PASSWORD socket options\&. Which peer binds, and which connects, is not relevant\&. -.SH "SEE ALSO" -.sp -\fBzmq_setsockopt\fR(3) \fBzmq_null\fR(7) \fBzmq_curve\fR(7) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_tcp.7 b/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_tcp.7 deleted file mode 100644 index e0e0e00677..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_tcp.7 +++ /dev/null @@ -1,188 +0,0 @@ -'\" t -.\" Title: zmq_tcp -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_TCP" "7" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_tcp \- 0MQ unicast transport using TCP -.SH "SYNOPSIS" -.sp -TCP is an ubiquitous, reliable, unicast transport\&. When connecting distributed applications over a network with 0MQ, using the TCP transport will likely be your first choice\&. -.SH "ADDRESSING" -.sp -A 0MQ endpoint is a string consisting of a \fItransport\fR:// followed by an \fIaddress\fR\&. The \fItransport\fR specifies the underlying protocol to use\&. The \fIaddress\fR specifies the transport\-specific address to connect to\&. -.sp -For the TCP transport, the transport is tcp, and the meaning of the \fIaddress\fR part is defined below\&. -.SS "Assigning a local address to a socket" -.sp -When assigning a local address to a socket using \fIzmq_bind()\fR with the \fItcp\fR transport, the \fIendpoint\fR shall be interpreted as an \fIinterface\fR followed by a colon and the TCP port number to use\&. -.sp -An \fIinterface\fR may be specified by either of the following: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -The wild\-card -*, meaning all available interfaces\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -The primary IPv4 or IPv6 address assigned to the interface, in its numeric representation\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -The non\-portable interface name as defined by the operating system\&. -.RE -.sp -The TCP port number may be specified by: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -A numeric value, usually above 1024 on POSIX systems\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -The wild\-card -*, meaning a system\-assigned ephemeral port\&. -.RE -.sp -When using ephemeral ports, the caller should retrieve the actual assigned port using the ZMQ_LAST_ENDPOINT socket option\&. See \fBzmq_getsockopt\fR(3) for details\&. -.SS "Unbinding wild\-card address from a socket" -.sp -When wild\-card * \fIendpoint\fR was used in \fIzmq_bind()\fR, the caller should use real \fIendpoint\fR obtained from the ZMQ_LAST_ENDPOINT socket option to unbind this \fIendpoint\fR from a socket using \fIzmq_unbind()\fR\&. -.SS "Connecting a socket" -.sp -When connecting a socket to a peer address using \fIzmq_connect()\fR with the \fItcp\fR transport, the \fIendpoint\fR shall be interpreted as a \fIpeer address\fR followed by a colon and the TCP port number to use\&. You can optionally specify a \fIsource_endpoint\fR which will be used as the source address for your connection; tcp://\fIsource_endpoint\fR;\*(Aqendpoint\*(Aq, see the \fIinterface\fR description above for details\&. -.sp -A \fIpeer address\fR may be specified by either of the following: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -The DNS name of the peer\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -The IPv4 or IPv6 address of the peer, in its numeric representation\&. -.RE -.sp -Note: A description of the ZeroMQ Message Transport Protocol (ZMTP) which is used by the TCP transport can be found at \m[blue]\fBhttp://rfc\&.zeromq\&.org/spec:15\fR\m[] -.SH "EXAMPLES" -.PP -\fBAssigning a local address to a socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// TCP port 5555 on all available interfaces -rc = zmq_bind(socket, "tcp://*:5555"); -assert (rc == 0); -// TCP port 5555 on the local loop\-back interface on all platforms -rc = zmq_bind(socket, "tcp://127\&.0\&.0\&.1:5555"); -assert (rc == 0); -// TCP port 5555 on the first Ethernet network interface on Linux -rc = zmq_bind(socket, "tcp://eth0:5555"); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.PP -\fBConnecting a socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Connecting using an IP address -rc = zmq_connect(socket, "tcp://192\&.168\&.1\&.1:5555"); -assert (rc == 0); -// Connecting using a DNS name -rc = zmq_connect(socket, "tcp://server1:5555"); -assert (rc == 0); -// Connecting using a DNS name and bind to eth1 -rc = zmq_connect(socket, "tcp://eth1:0;server1:5555"); -assert (rc == 0); -// Connecting using a IP address and bind to an IP address -rc = zmq_connect(socket, "tcp://192\&.168\&.1\&.17:5555;192\&.168\&.1\&.1:5555"); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_bind\fR(3) \fBzmq_connect\fR(3) \fBzmq_pgm\fR(7) \fBzmq_ipc\fR(7) \fBzmq_inproc\fR(7) \fBzmq_vmci\fR(7) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_tipc.7 b/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_tipc.7 deleted file mode 100644 index cef1454757..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_tipc.7 +++ /dev/null @@ -1,110 +0,0 @@ -'\" t -.\" Title: zmq_tipc -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_TIPC" "7" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_tipc \- 0MQ unicast transport using TIPC -.SH "SYNOPSIS" -.sp -TIPC is a cluster IPC protocol with a location transparent addressing scheme\&. -.SH "ADDRESSING" -.sp -A 0MQ endpoint is a string consisting of a \fItransport\fR:// followed by an \fIaddress\fR\&. The \fItransport\fR specifies the underlying protocol to use\&. The \fIaddress\fR specifies the transport\-specific address to connect to\&. -.sp -For the TIPC transport, the transport is tipc, and the meaning of the \fIaddress\fR part is defined below\&. -.SS "Assigning a port name to a socket" -.sp -When assigning a port name to a socket using \fIzmq_bind()\fR with the \fItipc\fR transport, the \fIendpoint\fR is defined in the form: {type, lower, upper} -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Type is the numerical (u32) ID of your service\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Lower and Upper specify a range for your service\&. -.RE -.sp -Publishing the same service with overlapping lower/upper ID\(cqs will cause connection requests to be distributed over these in a round\-robin manner\&. -.SS "Connecting a socket" -.sp -When connecting a socket to a peer address using \fIzmq_connect()\fR with the \fItipc\fR transport, the \fIendpoint\fR shall be interpreted as a service ID, followed by a comma and the instance ID\&. -.sp -The instance ID must be within the lower/upper range of a published port name for the endpoint to be valid\&. -.SH "EXAMPLES" -.PP -\fBAssigning a local address to a socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Publish TIPC service ID 5555 -rc = zmq_bind(socket, "tipc://{5555,0,0}"); -assert (rc == 0); -// Publish TIPC service ID 5555 with a service range of 0\-100 -rc = zmq_bind(socket, "tipc://{5555,0,100}"); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.PP -\fBConnecting a socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Connect to service 5555 instance id 50 -rc = zmq_connect(socket, "tipc://{5555,50}"); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_bind\fR(3) \fBzmq_connect\fR(3) \fBzmq_tcp\fR(7) \fBzmq_pgm\fR(7) \fBzmq_ipc\fR(7) \fBzmq_inproc\fR(7) \fBzmq_vmci\fR(7) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_udp.7 b/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_udp.7 deleted file mode 100644 index cda022097f..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_udp.7 +++ /dev/null @@ -1,139 +0,0 @@ -'\" t -.\" Title: zmq_udp -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_UDP" "7" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_udp \- 0MQ UDP multicast and unicast transport -.SH "SYNOPSIS" -.sp -UDP is unreliable protocol transport of data over IP networks\&. UDP support both unicast and multicast communication\&. -.SH "DESCRIPTION" -.sp -UDP transport can only be used with the \fIZMQ_RADIO\fR and \fIZMQ_DISH\fR socket types\&. -.SH "ADDRESSING" -.sp -A 0MQ endpoint is a string consisting of a \fItransport\fR:// followed by an \fIaddress\fR\&. The \fItransport\fR specifies the underlying protocol to use\&. The \fIaddress\fR specifies the transport\-specific address to connect to\&. -.sp -For the UDP transport, the transport is udp\&. The meaning of the \fIaddress\fR part is defined below\&. -.sp -Binding a socket -.sp -.if n \{\ -.RS 4 -.\} -.nf -With \*(Aqudp\*(Aq we can only bind the \*(AqZMQ_DISH\*(Aq socket type\&. -When binding a socket using _zmq_bind()_ with the \*(Aqudp\*(Aq -transport the \*(Aqendpoint\*(Aq shall be interpreted as an \*(Aqinterface\*(Aq followed by a -colon and the UDP port number to use\&. - -An \*(Aqinterface\*(Aq may be specified by either of the following: - -* The wild\-card `*`, meaning all available interfaces\&. -* The primary IPv4 address assigned to the interface, in its numeric - representation\&. -* Multicast address in its numeric representation the socket should join\&. - -The UDP port number may be specified a numeric value, usually above 1024 on POSIX systems\&. - -Connecting a socket -.fi -.if n \{\ -.RE -.\} -.sp -With \fIudp\fR we can only connect the \fIZMQ_RADIO\fR socket type\&. When connecting a socket to a peer address using \fIzmq_connect()\fR with the \fIudp\fR transport, the \fIendpoint\fR shall be interpreted as a \fIpeer address\fR followed by a colon and the UDP port number to use\&. -.sp -A \fIpeer address\fR may be specified by either of the following: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -The IPv4 or IPv6 address of the peer, in its numeric representation\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -Multicast address in its numeric representation\&. -.RE -.SH "EXAMPLES" -.PP -\fBBinding a socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Unicast \- UDP port 5555 on all available interfaces -rc = zmq_bind(dish, "udp://*:5555"); -assert (rc == 0); -// Unicast \- UDP port 5555 on the local loop\-back interface -rc = zmq_bind(dish, "udp://127\&.0\&.0\&.1:5555"); -assert (rc == 0); -// Multicast \- UDP port 5555 on a Multicast address -rc = zmq_bind(dish, "udp://239\&.0\&.0\&.1:5555"); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.PP -\fBConnecting a socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Connecting using an Unicast IP address -rc = zmq_connect(radio, "udp://192\&.168\&.1\&.1:5555"); -assert (rc == 0); -// Connecting using a Multicast address" -rc = zmq_connect(socket, "udp://239\&.0\&.0\&.1:5555); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_connect\fR(3) \fBzmq_setsockopt\fR(3) \fBzmq_tcp\fR(7) \fBzmq_ipc\fR(7) \fBzmq_inproc\fR(7) \fBzmq_vmci\fR(7) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_vmci.7 b/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_vmci.7 deleted file mode 100644 index 5383060905..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/man/man7/zmq_vmci.7 +++ /dev/null @@ -1,162 +0,0 @@ -'\" t -.\" Title: zmq_vmci -.\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.78.1 -.\" Date: 02/18/2017 -.\" Manual: 0MQ Manual -.\" Source: 0MQ 4.2.2 -.\" Language: English -.\" -.TH "ZMQ_VMCI" "7" "02/18/2017" "0MQ 4\&.2\&.2" "0MQ Manual" -.\" ----------------------------------------------------------------- -.\" * Define some portability stuff -.\" ----------------------------------------------------------------- -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.\" http://bugs.debian.org/507673 -.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html -.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.\" ----------------------------------------------------------------- -.\" * set default formatting -.\" ----------------------------------------------------------------- -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.\" ----------------------------------------------------------------- -.\" * MAIN CONTENT STARTS HERE * -.\" ----------------------------------------------------------------- -.SH "NAME" -zmq_vmci \- 0MQ transport over virtual machine communicatios interface (VMCI) sockets -.SH "SYNOPSIS" -.sp -The VMCI transport passes messages between VMware virtual machines running on the same host, between virtual machine and the host and within virtual machines (inter\-process transport like ipc)\&. -.if n \{\ -.sp -.\} -.RS 4 -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -.ps +1 -\fBNote\fR -.ps -1 -.br -.sp -Communication between a virtual machine and the host is not supported on Mac OS X 10\&.9 and above\&. -.sp .5v -.RE -.SH "ADDRESSING" -.sp -A 0MQ endpoint is a string consisting of a \fItransport\fR:// followed by an \fIaddress\fR\&. The \fItransport\fR specifies the underlying protocol to use\&. The \fIaddress\fR specifies the transport\-specific address to connect to\&. -.sp -For the VMCI transport, the transport is vmci, and the meaning of the \fIaddress\fR part is defined below\&. -.SS "Binding a socket" -.sp -When binding a \fIsocket\fR to a local address using \fIzmq_bind()\fR with the \fIvmci\fR transport, the \fIendpoint\fR shall be interpreted as an \fIinterface\fR followed by a colon and the TCP port number to use\&. -.sp -An \fIinterface\fR may be specified by either of the following: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -The wild\-card -*, meaning all available interfaces\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -An integer returned by -VMCISock_GetLocalCID -or -@ -(ZeroMQ will call VMCISock_GetLocalCID internally)\&. -.RE -.sp -The port may be specified by: -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -A numeric value, usually above 1024 on POSIX systems\&. -.RE -.sp -.RS 4 -.ie n \{\ -\h'-04'\(bu\h'+03'\c -.\} -.el \{\ -.sp -1 -.IP \(bu 2.3 -.\} -The wild\-card -*, meaning a system\-assigned ephemeral port\&. -.RE -.SS "Unbinding wild\-card address from a socket" -.sp -When wild\-card * \fIendpoint\fR was used in \fIzmq_bind()\fR, the caller should use real \fIendpoint\fR obtained from the ZMQ_LAST_ENDPOINT socket option to unbind this \fIendpoint\fR from a socket using \fIzmq_unbind()\fR\&. -.SS "Connecting a socket" -.sp -When connecting a socket to a peer address using \fIzmq_connect()\fR with the \fIvmci\fR transport, the \fIendpoint\fR shall be interpreted as a \fIpeer address\fR followed by a colon and the port number to use\&. -.sp -A \fIpeer address\fR must be a CID of the peer\&. -.SH "EXAMPLES" -.PP -\fBAssigning a local address to a socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// VMCI port 5555 on all available interfaces -rc = zmq_bind(socket, "vmci://*:5555"); -assert (rc == 0); -// VMCI port 5555 on the local loop\-back interface on all platforms -cid = VMCISock_GetLocalCID(); -sprintf(endpoint, "vmci://%d:5555", cid); -rc = zmq_bind(socket, endpoint); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.PP -\fBConnecting a socket\fR. -.sp -.if n \{\ -.RS 4 -.\} -.nf -// Connecting using a CID -sprintf(endpoint, "vmci://%d:5555", cid); -rc = zmq_connect(socket, endpoint); -assert (rc == 0); -.fi -.if n \{\ -.RE -.\} -.sp -.SH "SEE ALSO" -.sp -\fBzmq_bind\fR(3) \fBzmq_connect\fR(3) \fBzmq_inproc\fR(7) \fBzmq_tcp\fR(7) \fBzmq_pgm\fR(7) \fBzmq_vmci\fR(7) \fBzmq_getsockopt\fR(3) \fBzmq\fR(7) -.SH "AUTHORS" -.sp -This page was written by the 0MQ community\&. To make a change please read the 0MQ Contribution Policy at \m[blue]\fBhttp://www\&.zeromq\&.org/docs:contributing\fR\m[]\&. diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zactor.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zactor.api deleted file mode 100644 index 2ff128b36e..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zactor.api +++ /dev/null @@ -1,62 +0,0 @@ - - - provides a simple actor framework - - - Actors get a pipe and arguments from caller - - - - - - Create a new actor passing arbitrary arguments reference. - - - - - - Destroy an actor. - - - - Send a zmsg message to the actor, take ownership of the message - and destroy when it has been sent. - - - - - - Receive a zmsg message from the actor. Returns NULL if the actor - was interrupted before the message could be received, or if there - was a timeout on the actor. - - - - - Probe the supplied object, and report if it looks like a zactor_t. - - - - - - Probe the supplied reference. If it looks like a zactor_t instance, - return the underlying libzmq actor handle; else if it looks like - a libzmq actor handle, return the supplied value. - - - - - - Return the actor's zsock handle. Use this when you absolutely need - to work with the zsock instance rather than the actor. - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zarmour.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zarmour.api deleted file mode 100644 index 887ca9ffdb..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zarmour.api +++ /dev/null @@ -1,103 +0,0 @@ - - - armoured text encoding and decoding - - Standard base 64 - URL and filename friendly base 64 - Standard base 32 - Extended hex base 32 - Standard base 16 - Z85 from ZeroMQ RFC 32 - - - Create a new zarmour - - - - Destroy the zarmour - - - - Encode a stream of bytes into an armoured string. Returns the armoured - string, or NULL if there was insufficient memory available to allocate - a new string. - - - - - - - Decode an armoured string into a chunk. The decoded output is - null-terminated, so it may be treated as a string, if that's what - it was prior to encoding. - - - - - - Get the mode property. - - - - - Get printable string for mode. - - - - - Set the mode property. - - - - - Return true if padding is turned on. - - - - - Turn padding on or off. Default is on. - - - - - Get the padding character. - - - - - Set the padding character. - - - - - Return if splitting output into lines is turned on. Default is off. - - - - - Turn splitting output into lines on or off. - - - - - Get the line length used for splitting lines. - - - - - Set the line length used for splitting lines. - - - - - Print properties of object - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zcert.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zcert.api deleted file mode 100644 index d361ba2165..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zcert.api +++ /dev/null @@ -1,122 +0,0 @@ - - - work with CURVE security certificates - - - Create and initialize a new certificate in memory - - - - Accepts public/secret key pair from caller - - - - - - Load certificate from file - - - - - Destroy a certificate in memory - - - - Return public part of key pair as 32-byte binary string - - - - - Return secret part of key pair as 32-byte binary string - - - - - Return public part of key pair as Z85 armored string - - - - - Return secret part of key pair as Z85 armored string - - - - - Set certificate metadata from formatted string. - - - - - - Unset certificate metadata. - - - - - Get metadata value from certificate; if the metadata value doesn't - exist, returns NULL. - - - - - - Get list of metadata fields from certificate. Caller is responsible for - destroying list. Caller should not modify the values of list items. - - - - - Save full certificate (public + secret) to file for persistent storage - This creates one public file and one secret file (filename + "_secret"). - - - - - - Save public certificate only to file for persistent storage - - - - - - Save secret certificate only to file for persistent storage - - - - - - Apply certificate to socket, i.e. use for CURVE security on socket. - If certificate was loaded from public file, the secret key will be - undefined, and this certificate will not work successfully. - - - - - Return copy of certificate; if certificate is NULL or we exhausted - heap memory, returns NULL. - - - - - Return true if two certificates have the same keys - - - - - - Print certificate contents to stdout - - - - Self test of this class - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zcertstore.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zcertstore.api deleted file mode 100644 index b566fefa53..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zcertstore.api +++ /dev/null @@ -1,72 +0,0 @@ - - - work with CURVE security certificate stores - - - Create a new certificate store from a disk directory, loading and - indexing all certificates in that location. The directory itself may be - absent, and created later, or modified at any time. The certificate store - is automatically refreshed on any zcertstore_lookup() call. If the - location is specified as NULL, creates a pure-memory store, which you - can work with by inserting certificates at runtime. - - - - - Destroy a certificate store object in memory. Does not affect anything - stored on disk. - - - - Loaders retrieve certificates from an arbitrary source. - - - - - Destructor for loader state. - - - - - Override the default disk loader with a custom loader fn. - - - - - - - Look up certificate by public key, returns zcert_t object if found, - else returns NULL. The public key is provided in Z85 text format. - - - - - - Insert certificate into certificate store in memory. Note that this - does not save the certificate to disk. To do that, use zcert_save() - directly on the certificate. Takes ownership of zcert_t object. - - - - - Empty certificate hashtable. This wrapper exists to be friendly to bindings, - which don't usually have access to struct internals. - - - - Print list of certificates in store to logging facility - - - - Self test of this class - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zchunk.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zchunk.api deleted file mode 100644 index 25b50e9581..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zchunk.api +++ /dev/null @@ -1,171 +0,0 @@ - - - work with memory chunks - - - Create a new chunk of the specified size. If you specify the data, it - is copied into the chunk. If you do not specify the data, the chunk is - allocated and left empty, and you can then add data using zchunk_append. - - - - - - Destroy a chunk - - - - Resizes chunk max_size as requested; chunk_cur size is set to zero - - - - - Return chunk cur size - - - - - Return chunk max size - - - - - Return chunk data - - - - - Set chunk data from user-supplied data; truncate if too large. Data may - be null. Returns actual size of chunk - - - - - - - Fill chunk data from user-supplied octet - - - - - - - Append user-supplied data to chunk, return resulting chunk size. If the - data would exceeded the available space, it is truncated. If you want to - grow the chunk to accommodate new data, use the zchunk_extend method. - - - - - - - Append user-supplied data to chunk, return resulting chunk size. If the - data would exceeded the available space, the chunk grows in size. - - - - - - - Copy as much data from 'source' into the chunk as possible; returns the - new size of chunk. If all data from 'source' is used, returns exhausted - on the source chunk. Source can be consumed as many times as needed until - it is exhausted. If source was already exhausted, does not change chunk. - - - - - - Returns true if the chunk was exhausted by consume methods, or if the - chunk has a size of zero. - - - - - Read chunk from an open file descriptor - - - - - - - Write chunk to an open file descriptor - - - - - - Try to slurp an entire file into a chunk. Will read up to maxsize of - the file. If maxsize is 0, will attempt to read the entire file and - fail with an assertion if that cannot fit into memory. Returns a new - chunk containing the file data, or NULL if the file could not be read. - - - - - - - Create copy of chunk, as new chunk object. Returns a fresh zchunk_t - object, or null if there was not enough heap memory. If chunk is null, - returns null. - - - - - Return chunk data encoded as printable hex string. Caller must free - string when finished with it. - - - - - Return chunk data copied into freshly allocated string - Caller must free string when finished with it. - - - - - Return TRUE if chunk body is equal to string, excluding terminator - - - - - - Transform zchunk into a zframe that can be sent in a message. - - - - - Transform a zframe into a zchunk. - - - - - - Calculate SHA1 digest for chunk, using zdigest class. - - - - - Dump chunk to FILE stream, for debugging and tracing. - - - - - Dump message to stderr, for debugging and tracing. - See zchunk_fprint for details - - - - Probe the supplied object, and report if it looks like a zchunk_t. - - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zclock.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zclock.api deleted file mode 100644 index a613180f15..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zclock.api +++ /dev/null @@ -1,43 +0,0 @@ - - - millisecond clocks and delays - - - Sleep for a number of milliseconds - - - - - Return current system clock as milliseconds. Note that this clock can - jump backwards (if the system clock is changed) so is unsafe to use for - timers and time offsets. Use zclock_mono for that instead. - - - - - Return current monotonic clock in milliseconds. Use this when you compute - time offsets. The monotonic clock is not affected by system changes and - so will never be reset backwards, unlike a system clock. - - - - - Return current monotonic clock in microseconds. Use this when you compute - time offsets. The monotonic clock is not affected by system changes and - so will never be reset backwards, unlike a system clock. - - - - - Return formatted date/time as fresh string. Free using zstr_free(). - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zconfig.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zconfig.api deleted file mode 100644 index db46751fa8..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zconfig.api +++ /dev/null @@ -1,196 +0,0 @@ - - - work with config files written in rfc.zeromq.org/spec:4/ZPL. - - - - - - - - - - Create new config item - - - - - - Destroy a config item and all its children - - - - Return name of config item - - - - - Return value of config item - - - - - Insert or update configuration key with value - - - - - - Equivalent to zconfig_put, accepting a format specifier and variable - argument list, instead of a single string value. - - - - - - Get value for config item into a string value; leading slash is optional - and ignored. - - - - - - Set config item name, name may be NULL - - - - - Set new value for config item. The new value may be a string, a printf - format, or NULL. Note that if string may possibly contain '%', or if it - comes from an insecure source, you must use '%s' as the format, followed - by the string. - - - - - Find our first child, if any - - - - - Find our first sibling, if any - - - - - Find a config item along a path; leading slash is optional and ignored. - - - - - - Locate the last config item at a specified depth - - - - - - Execute a callback for each config item in the tree; returns zero if - successful, else -1. - - - - - - - Add comment to config item before saving to disk. You can add as many - comment lines as you like. If you use a null format, all comments are - deleted. - - - - - Return comments of config item, as zlist. - - - - - Load a config tree from a specified ZPL text file; returns a zconfig_t - reference for the root, if the file exists and is readable. Returns NULL - if the file does not exist. - - - - - Save a config tree to a specified ZPL text file, where a filename - "-" means dump to standard output. - - - - - - Equivalent to zconfig_load, taking a format string instead of a fixed - filename. - - - - - Equivalent to zconfig_save, taking a format string instead of a fixed - filename. - - - - - - Report filename used during zconfig_load, or NULL if none - - - - - Reload config tree from same file that it was previously loaded from. - Returns 0 if OK, -1 if there was an error (and then does not change - existing data). - - - - - - Load a config tree from a memory chunk - - - - - - Save a config tree to a new memory chunk - - - - - Load a config tree from a null-terminated string - - - - - - Save a config tree to a new null terminated string - - - - - Return true if a configuration tree was loaded from a file and that - file has changed in since the tree was loaded. - - - - - Print the config file to open stream - - - - - Print properties of object - - - - Self test of this class - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zdigest.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zdigest.api deleted file mode 100644 index 83abb9b121..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zdigest.api +++ /dev/null @@ -1,45 +0,0 @@ - - - provides hashing functions (SHA-1 at present) - - - Constructor - creates new digest object, which you use to build up a - digest by repeatedly calling zdigest_update() on chunks of data. - - - - Destroy a digest object - - - - Add buffer into digest calculation - - - - - - Return final digest hash data. If built without crypto support, - returns NULL. - - - - - Return final digest hash size - - - - - Return digest as printable hex string; caller should not modify nor - free this string. After calling this, you may not use zdigest_update() - on the same digest. If built without crypto support, returns NULL. - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zdir.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zdir.api deleted file mode 100644 index cb8283a702..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zdir.api +++ /dev/null @@ -1,124 +0,0 @@ - - - work with file-system directories - - - Create a new directory item that loads in the full tree of the specified - path, optionally located under some parent path. If parent is "-", then - loads only the top-level directory, and does not use parent as a path. - - - - - - Destroy a directory tree and all children it contains. - - - - Return directory path - - - - - Return last modification time for directory. - - - - - Return total hierarchy size, in bytes of data contained in all files - in the directory tree. - - - - - Return directory count - - - - - Returns a sorted list of zfile objects; Each entry in the list is a pointer - to a zfile_t item already allocated in the zdir tree. Do not destroy the - original zdir tree until you are done with this list. - - - - - Remove directory, optionally including all files that it contains, at - all levels. If force is false, will only remove the directory if empty. - If force is true, will remove all files and all subdirectories. - - - - - Calculate differences between two versions of a directory tree. - Returns a list of zdir_patch_t patches. Either older or newer may - be null, indicating the directory is empty/absent. If alias is set, - generates virtual filename (minus path, plus alias). - - - - - - - - Return full contents of directory as a zdir_patch list. - - - - - - Load directory cache; returns a hash table containing the SHA-1 digests - of every file in the tree. The cache is saved between runs in .cache. - - - - - Print contents of directory to open stream - - - - - - Print contents of directory to stdout - - - - - Create a new zdir_watch actor instance: - - zactor_t *watch = zactor_new (zdir_watch, NULL); - - Destroy zdir_watch instance: - - zactor_destroy (&watch); - - Enable verbose logging of commands and activity: - - zstr_send (watch, "VERBOSE"); - - Subscribe to changes to a directory path: - - zsock_send (watch, "ss", "SUBSCRIBE", "directory_path"); - - Unsubscribe from changes to a directory path: - - zsock_send (watch, "ss", "UNSUBSCRIBE", "directory_path"); - - Receive directory changes: - zsock_recv (watch, "sp", &path, &patches); - - // Delete the received data. - free (path); - zlist_destroy (&patches); - - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zdir_patch.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zdir_patch.api deleted file mode 100644 index 8d102b887a..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zdir_patch.api +++ /dev/null @@ -1,62 +0,0 @@ - - - work with directory patches - - Creates a new file - Delete a file - - - Create new patch - - - - - - - - Destroy a patch - - - - Create copy of a patch. If the patch is null, or memory was exhausted, - returns null. - - - - - Return patch file directory path - - - - - Return patch file item - - - - - Return operation - - - - - Return patch virtual file path - - - - - Calculate hash digest for file (create only) - - - - Return hash digest for patch file - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zfile.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zfile.api deleted file mode 100644 index f60391bfee..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zfile.api +++ /dev/null @@ -1,152 +0,0 @@ - - - helper functions for working with files. - - - If file exists, populates properties. CZMQ supports portable symbolic - links, which are files with the extension ".ln". A symbolic link is a - text file containing one line, the filename of a target file. Reading - data from the symbolic link actually reads from the target file. Path - may be NULL, in which case it is not used. - - - - - - Destroy a file item - - - - Duplicate a file item, returns a newly constructed item. If the file - is null, or memory was exhausted, returns null. - - - - - Return file name, remove path if provided - - - - - - Refresh file properties from disk; this is not done automatically - on access methods, otherwise it is not possible to compare directory - snapshots. - - - - Return when the file was last modified. If you want this to reflect the - current situation, call zfile_restat before checking this property. - - - - - Return the last-known size of the file. If you want this to reflect the - current situation, call zfile_restat before checking this property. - - - - - Return true if the file is a directory. If you want this to reflect - any external changes, call zfile_restat before checking this property. - - - - - Return true if the file is a regular file. If you want this to reflect - any external changes, call zfile_restat before checking this property. - - - - - Return true if the file is readable by this process. If you want this to - reflect any external changes, call zfile_restat before checking this - property. - - - - - Return true if the file is writeable by this process. If you want this - to reflect any external changes, call zfile_restat before checking this - property. - - - - - Check if file has stopped changing and can be safely processed. - Updates the file statistics from disk at every call. - - - - - Return true if the file was changed on disk since the zfile_t object - was created, or the last zfile_restat() call made on it. - - - - - Remove the file from disk - - - - Open file for reading - Returns 0 if OK, -1 if not found or not accessible - - - - - Open file for writing, creating directory if needed - File is created if necessary; chunks can be written to file at any - location. Returns 0 if OK, -1 if error. - - - - - Read chunk from file at specified position. If this was the last chunk, - sets the eof property. Returns a null chunk in case of error. - - - - - - - Returns true if zfile_read() just read the last chunk in the file. - - - - - Write chunk to file at specified position - Return 0 if OK, else -1 - - - - - - - Read next line of text from file. Returns a pointer to the text line, - or NULL if there was nothing more to read from the file. - - - - - Close file, if open - - - - Return file handle, if opened - - - - - Calculate SHA1 digest for file, using zdigest class. - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zframe.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zframe.api deleted file mode 100644 index cf3c3219f6..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zframe.api +++ /dev/null @@ -1,156 +0,0 @@ - - - working with single message frames - - - - - - - Create a new frame. If size is not null, allocates the frame data - to the specified size. If additionally, data is not null, copies - size octets from the specified data into the frame body. - - - - - - Destroy a frame - - - - Create an empty (zero-sized) frame - - - - Create a frame with a specified string content. - - - - - Receive frame from socket, returns zframe_t object or NULL if the recv - was interrupted. Does a blocking recv, if you want to not block then use - zpoller or zloop. - - - - - Send a frame to a socket, destroy frame after sending. - Return -1 on error, 0 on success. - - - - - - - - Return number of bytes in frame data - - - - - Return address of frame data - - - - - Return meta data property for frame - Caller must free string when finished with it. - - - - - - Create a new frame that duplicates an existing frame. If frame is null, - or memory was exhausted, returns null. - - - - - Return frame data encoded as printable hex string, useful for 0MQ UUIDs. - Caller must free string when finished with it. - - - - - Return frame data copied into freshly allocated string - Caller must free string when finished with it. - - - - - Return TRUE if frame body is equal to string, excluding terminator - - - - - - Return frame MORE indicator (1 or 0), set when reading frame from socket - or by the zframe_set_more() method - - - - - Set frame MORE indicator (1 or 0). Note this is NOT used when sending - frame to socket, you have to specify flag explicitly. - - - - - Return frame routing ID, if the frame came from a ZMQ_SERVER socket. - Else returns zero. - - - - - Set routing ID on frame. This is used if/when the frame is sent to a - ZMQ_SERVER socket. - - - - - Return frame group of radio-dish pattern. - - - - - Set group on frame. This is used if/when the frame is sent to a - ZMQ_RADIO socket. - Return -1 on error, 0 on success. - - - - - - Return TRUE if two frames have identical size and data - If either frame is NULL, equality is always false. - - - - - - Set new contents for frame - - - - - - Send message to zsys log sink (may be stdout, or system facility as - configured by zsys_set_logstream). Prefix shows before frame, if not null. - - - - - Probe the supplied object, and report if it looks like a zframe_t. - - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zgossip_msg.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zgossip_msg.api deleted file mode 100644 index 0f314fab7c..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zgossip_msg.api +++ /dev/null @@ -1,104 +0,0 @@ - - - - - - - - - - Create a new empty zgossip_msg - - - - Destroy a zgossip_msg instance - - - - Receive a zgossip_msg from the socket. Returns 0 if OK, -1 if - there was an error. Blocks if there is no message waiting. - - - - - - Send the zgossip_msg to the output socket, does not destroy it - - - - - - Print contents of message to stdout - - - - Get the message routing id, as a frame - - - - - Set the message routing id from a frame - - - - - Get the zgossip_msg message id - - - - - Set the zgossip_msg message id - - - - - Get the zgossip_msg message id as printable text - - - - - Get the key field - - - - Set the key field - - - - Get the value field - - - - Set the value field - - - - Get the ttl field - - - - Set the ttl field - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zhash.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zhash.api deleted file mode 100644 index 36d58847af..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zhash.api +++ /dev/null @@ -1,183 +0,0 @@ - - - generic type-free hash container (simple) - - - Callback function for zhash_freefn method - - - - - Create a new, empty hash container - - - - Destroy a hash container and all items in it - - - - Insert item into hash table with specified key and item. - If key is already present returns -1 and leaves existing item unchanged - Returns 0 on success. - - - - - - - Update item into hash table with specified key and item. - If key is already present, destroys old item and inserts new one. - Use free_fn method to ensure deallocator is properly called on item. - - - - - - Remove an item specified by key from the hash table. If there was no such - item, this function does nothing. - - - - - Return the item at the specified key, or null - - - - - - Reindexes an item from an old key to a new key. If there was no such - item, does nothing. Returns 0 if successful, else -1. - - - - - - - Set a free function for the specified hash table item. When the item is - destroyed, the free function, if any, is called on that item. - Use this when hash items are dynamically allocated, to ensure that - you don't have memory leaks. You can pass 'free' or NULL as a free_fn. - Returns the item, or NULL if there is no such item. - - - - - - - Return the number of keys/items in the hash table - - - - - Make copy of hash table; if supplied table is null, returns null. - Does not copy items themselves. Rebuilds new table so may be slow on - very large tables. NOTE: only works with item values that are strings - since there's no other way to know how to duplicate the item value. - - - - - Return keys for items in table - - - - - Simple iterator; returns first item in hash table, in no given order, - or NULL if the table is empty. This method is simpler to use than the - foreach() method, which is deprecated. To access the key for this item - use zhash_cursor(). NOTE: do NOT modify the table while iterating. - - - - - Simple iterator; returns next item in hash table, in no given order, - or NULL if the last item was already returned. Use this together with - zhash_first() to process all items in a hash table. If you need the - items in sorted order, use zhash_keys() and then zlist_sort(). To - access the key for this item use zhash_cursor(). NOTE: do NOT modify - the table while iterating. - - - - - After a successful first/next method, returns the key for the item that - was returned. This is a constant string that you may not modify or - deallocate, and which lasts as long as the item in the hash. After an - unsuccessful first/next, returns NULL. - - - - - Add a comment to hash table before saving to disk. You can add as many - comment lines as you like. These comment lines are discarded when loading - the file. If you use a null format, all comments are deleted. - - - - - Serialize hash table to a binary frame that can be sent in a message. - The packed format is compatible with the 'dictionary' type defined in - http://rfc.zeromq.org/spec:35/FILEMQ, and implemented by zproto: - - ; A list of name/value pairs - dictionary = dict-count *( dict-name dict-value ) - dict-count = number-4 - dict-value = longstr - dict-name = string - - ; Strings are always length + text contents - longstr = number-4 *VCHAR - string = number-1 *VCHAR - - ; Numbers are unsigned integers in network byte order - number-1 = 1OCTET - number-4 = 4OCTET - - Comments are not included in the packed data. Item values MUST be - strings. - - - - - Unpack binary frame into a new hash table. Packed data must follow format - defined by zhash_pack. Hash table is set to autofree. An empty frame - unpacks to an empty hash table. - - - - - Save hash table to a text file in name=value format. Hash values must be - printable strings; keys may not contain '=' character. Returns 0 if OK, - else -1 if a file error occurred. - - - - - - Load hash table from a text file in name=value format; hash table must - already exist. Hash values must printable strings; keys may not contain - '=' character. Returns 0 if OK, else -1 if a file was not readable. - - - - - - When a hash table was loaded from a file by zhash_load, this method will - reload the file if it has been modified since, and is "stable", i.e. not - still changing. Returns 0 if OK, -1 if there was an error reloading the - file. - - - - - Set hash for automatic value destruction - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zhashx.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zhashx.api deleted file mode 100644 index 22087e0fe9..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zhashx.api +++ /dev/null @@ -1,293 +0,0 @@ - - - extended generic type-free hash container - - - Destroy an item - - - - - Duplicate an item - - - - - - Compare two items, for sorting - - - - - - - compare two items, for sorting - - - - - compare two items, for sorting - - - - - - Serializes an item to a longstr. - The caller takes ownership of the newly created object. - - - - - - Deserializes a longstr into an item. - The caller takes ownership of the newly created object. - - - - - - Create a new, empty hash container - - - - Destroy a hash container and all items in it - - - - Insert item into hash table with specified key and item. - If key is already present returns -1 and leaves existing item unchanged - Returns 0 on success. - - - - - - - Update or insert item into hash table with specified key and item. If the - key is already present, destroys old item and inserts new one. If you set - a container item destructor, this is called on the old value. If the key - was not already present, inserts a new item. Sets the hash cursor to the - new item. - - - - - - Remove an item specified by key from the hash table. If there was no such - item, this function does nothing. - - - - - Delete all items from the hash table. If the key destructor is - set, calls it on every key. If the item destructor is set, calls - it on every item. - - - - Return the item at the specified key, or null - - - - - - Reindexes an item from an old key to a new key. If there was no such - item, does nothing. Returns 0 if successful, else -1. - - - - - - - Set a free function for the specified hash table item. When the item is - destroyed, the free function, if any, is called on that item. - Use this when hash items are dynamically allocated, to ensure that - you don't have memory leaks. You can pass 'free' or NULL as a free_fn. - Returns the item, or NULL if there is no such item. - - - - - - - Return the number of keys/items in the hash table - - - - - Return a zlistx_t containing the keys for the items in the - table. Uses the key_duplicator to duplicate all keys and sets the - key_destructor as destructor for the list. - - - - - Return a zlistx_t containing the values for the items in the - table. Uses the duplicator to duplicate all items and sets the - destructor as destructor for the list. - - - - - Simple iterator; returns first item in hash table, in no given order, - or NULL if the table is empty. This method is simpler to use than the - foreach() method, which is deprecated. To access the key for this item - use zhashx_cursor(). NOTE: do NOT modify the table while iterating. - - - - - Simple iterator; returns next item in hash table, in no given order, - or NULL if the last item was already returned. Use this together with - zhashx_first() to process all items in a hash table. If you need the - items in sorted order, use zhashx_keys() and then zlistx_sort(). To - access the key for this item use zhashx_cursor(). NOTE: do NOT modify - the table while iterating. - - - - - After a successful first/next method, returns the key for the item that - was returned. This is a constant string that you may not modify or - deallocate, and which lasts as long as the item in the hash. After an - unsuccessful first/next, returns NULL. - - - - - Add a comment to hash table before saving to disk. You can add as many - comment lines as you like. These comment lines are discarded when loading - the file. If you use a null format, all comments are deleted. - - - - - Save hash table to a text file in name=value format. Hash values must be - printable strings; keys may not contain '=' character. Returns 0 if OK, - else -1 if a file error occurred. - - - - - - Load hash table from a text file in name=value format; hash table must - already exist. Hash values must printable strings; keys may not contain - '=' character. Returns 0 if OK, else -1 if a file was not readable. - - - - - - When a hash table was loaded from a file by zhashx_load, this method will - reload the file if it has been modified since, and is "stable", i.e. not - still changing. Returns 0 if OK, -1 if there was an error reloading the - file. - - - - - Serialize hash table to a binary frame that can be sent in a message. - The packed format is compatible with the 'dictionary' type defined in - http://rfc.zeromq.org/spec:35/FILEMQ, and implemented by zproto: - - ; A list of name/value pairs - dictionary = dict-count *( dict-name dict-value ) - dict-count = number-4 - dict-value = longstr - dict-name = string - - ; Strings are always length + text contents - longstr = number-4 *VCHAR - string = number-1 *VCHAR - - ; Numbers are unsigned integers in network byte order - number-1 = 1OCTET - number-4 = 4OCTET - - Comments are not included in the packed data. Item values MUST be - strings. - - - - - Same as pack but uses a user-defined serializer function to convert items - into longstr. - - - - - - Unpack binary frame into a new hash table. Packed data must follow format - defined by zhashx_pack. Hash table is set to autofree. An empty frame - unpacks to an empty hash table. - - - - - Same as unpack but uses a user-defined deserializer function to convert - a longstr back into item format. - - - - - - Make a copy of the list; items are duplicated if you set a duplicator - for the list, otherwise not. Copying a null reference returns a null - reference. Note that this method's behavior changed slightly for CZMQ - v3.x, as it does not set nor respect autofree. It does however let you - duplicate any hash table safely. The old behavior is in zhashx_dup_v2. - - - - - Set a user-defined deallocator for hash items; by default items are not - freed when the hash is destroyed. - - - - - Set a user-defined duplicator for hash items; by default items are not - copied when the hash is duplicated. - - - - - Set a user-defined deallocator for keys; by default keys are freed - when the hash is destroyed using free(). - - - - - Set a user-defined duplicator for keys; by default keys are duplicated - using strdup. - - - - - Set a user-defined comparator for keys; by default keys are - compared using strcmp. - - - - - Set a user-defined comparator for keys; by default keys are - compared using strcmp. - - - - - Make copy of hash table; if supplied table is null, returns null. - Does not copy items themselves. Rebuilds new table so may be slow on - very large tables. NOTE: only works with item values that are strings - since there's no other way to know how to duplicate the item value. - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/ziflist.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/ziflist.api deleted file mode 100644 index 5dc362463c..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/ziflist.api +++ /dev/null @@ -1,58 +0,0 @@ - - - List of network interfaces available on system - - - Get a list of network interfaces currently defined on the system - - - - Destroy a ziflist instance - - - - Reload network interfaces from system - - - - Return the number of network interfaces on system - - - - - Get first network interface, return NULL if there are none - - - - - Get next network interface, return NULL if we hit the last one - - - - - Return the current interface IP address as a printable string - - - - - Return the current interface broadcast address as a printable string - - - - - Return the current interface network mask as a printable string - - - - - Return the list of interfaces. - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zlist.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zlist.api deleted file mode 100644 index 67b4f01c57..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zlist.api +++ /dev/null @@ -1,158 +0,0 @@ - - - simple generic list container - - - Comparison function e.g. for sorting and removing. - - - - - - - Callback function for zlist_freefn method - - - - - Create a new list container - - - - Destroy a list container - - - - Return the item at the head of list. If the list is empty, returns NULL. - Leaves cursor pointing at the head item, or NULL if the list is empty. - - - - - Return the next item. If the list is empty, returns NULL. To move to - the start of the list call zlist_first (). Advances the cursor. - - - - - Return the item at the tail of list. If the list is empty, returns NULL. - Leaves cursor pointing at the tail item, or NULL if the list is empty. - - - - - Return first item in the list, or null, leaves the cursor - - - - - Return last item in the list, or null, leaves the cursor - - - - - Return the current item of list. If the list is empty, returns NULL. - Leaves cursor pointing at the current item, or NULL if the list is empty. - - - - - Append an item to the end of the list, return 0 if OK or -1 if this - failed for some reason (out of memory). Note that if a duplicator has - been set, this method will also duplicate the item. - - - - - - Push an item to the start of the list, return 0 if OK or -1 if this - failed for some reason (out of memory). Note that if a duplicator has - been set, this method will also duplicate the item. - - - - - - Pop the item off the start of the list, if any - - - - - Checks if an item already is present. Uses compare method to determine if - items are equal. If the compare method is NULL the check will only compare - pointers. Returns true if item is present else false. - - - - - - Remove the specified item from the list if present - - - - - Make a copy of list. If the list has autofree set, the copied list will - duplicate all items, which must be strings. Otherwise, the list will hold - pointers back to the items in the original list. If list is null, returns - NULL. - - - - - Purge all items from list - - - - Return number of items in the list - - - - - Sort the list. If the compare function is null, sorts the list by - ascending key value using a straight ASCII comparison. If you specify - a compare function, this decides how items are sorted. The sort is not - stable, so may reorder items with the same keys. The algorithm used is - combsort, a compromise between performance and simplicity. - - - - - Set list for automatic item destruction; item values MUST be strings. - By default a list item refers to a value held elsewhere. When you set - this, each time you append or push a list item, zlist will take a copy - of the string value. Then, when you destroy the list, it will free all - item values automatically. If you use any other technique to allocate - list values, you must free them explicitly before destroying the list. - The usual technique is to pop list items and destroy them, until the - list is empty. - - - - Sets a compare function for this list. The function compares two items. - It returns an integer less than, equal to, or greater than zero if the - first item is found, respectively, to be less than, to match, or be - greater than the second item. - This function is used for sorting, removal and exists checking. - - - - - Set a free function for the specified list item. When the item is - destroyed, the free function, if any, is called on that item. - Use this when list items are dynamically allocated, to ensure that - you don't have memory leaks. You can pass 'free' or NULL as a free_fn. - Returns the item, or NULL if there is no such item. - - - - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zlistx.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zlistx.api deleted file mode 100644 index 1dc95ea637..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zlistx.api +++ /dev/null @@ -1,220 +0,0 @@ - - - extended generic list container - - - Destroy an item - - - - - Duplicate an item - - - - - - Compare two items, for sorting - - - - - - - Create a new, empty list. - - - - Destroy a list. If an item destructor was specified, all items in the - list are automatically destroyed as well. - - - - Add an item to the head of the list. Calls the item duplicator, if any, - on the item. Resets cursor to list head. Returns an item handle on - success, NULL if memory was exhausted. - - - - - - Add an item to the tail of the list. Calls the item duplicator, if any, - on the item. Resets cursor to list head. Returns an item handle on - success, NULL if memory was exhausted. - - - - - - Return the number of items in the list - - - - - Return first item in the list, or null, leaves the cursor - - - - - Return last item in the list, or null, leaves the cursor - - - - - Return the item at the head of list. If the list is empty, returns NULL. - Leaves cursor pointing at the head item, or NULL if the list is empty. - - - - - Return the next item. At the end of the list (or in an empty list), - returns NULL. Use repeated zlistx_next () calls to work through the list - from zlistx_first (). First time, acts as zlistx_first(). - - - - - Return the previous item. At the start of the list (or in an empty list), - returns NULL. Use repeated zlistx_prev () calls to work through the list - backwards from zlistx_last (). First time, acts as zlistx_last(). - - - - - Return the item at the tail of list. If the list is empty, returns NULL. - Leaves cursor pointing at the tail item, or NULL if the list is empty. - - - - - Returns the value of the item at the cursor, or NULL if the cursor is - not pointing to an item. - - - - - Returns the handle of the item at the cursor, or NULL if the cursor is - not pointing to an item. - - - - - Returns the item associated with the given list handle, or NULL if passed - in handle is NULL. Asserts that the passed in handle points to a list element. - - - - - - Find an item in the list, searching from the start. Uses the item - comparator, if any, else compares item values directly. Returns the - item handle found, or NULL. Sets the cursor to the found item, if any. - - - - - - Detach an item from the list, using its handle. The item is not modified, - and the caller is responsible for destroying it if necessary. If handle is - null, detaches the first item on the list. Returns item that was detached, - or null if none was. If cursor was at item, moves cursor to previous item, - so you can detach items while iterating forwards through a list. - - - - - - Detach item at the cursor, if any, from the list. The item is not modified, - and the caller is responsible for destroying it as necessary. Returns item - that was detached, or null if none was. Moves cursor to previous item, so - you can detach items while iterating forwards through a list. - - - - - Delete an item, using its handle. Calls the item destructor is any is - set. If handle is null, deletes the first item on the list. Returns 0 - if an item was deleted, -1 if not. If cursor was at item, moves cursor - to previous item, so you can delete items while iterating forwards - through a list. - - - - - - Move an item to the start of the list, via its handle. - - - - - Move an item to the end of the list, via its handle. - - - - - Remove all items from the list, and destroy them if the item destructor - is set. - - - - Sort the list. If an item comparator was set, calls that to compare - items, otherwise compares on item value. The sort is not stable, so may - reorder equal items. - - - - Create a new node and insert it into a sorted list. Calls the item - duplicator, if any, on the item. If low_value is true, starts searching - from the start of the list, otherwise searches from the end. Use the item - comparator, if any, to find where to place the new node. Returns a handle - to the new node, or NULL if memory was exhausted. Resets the cursor to the - list head. - - - - - - - Move an item, specified by handle, into position in a sorted list. Uses - the item comparator, if any, to determine the new location. If low_value - is true, starts searching from the start of the list, otherwise searches - from the end. - - - - - - Make a copy of the list; items are duplicated if you set a duplicator - for the list, otherwise not. Copying a null reference returns a null - reference. - - - - - Set a user-defined deallocator for list items; by default items are not - freed when the list is destroyed. - - - - - Set a user-defined duplicator for list items; by default items are not - copied when the list is duplicated. - - - - - Set a user-defined comparator for zlistx_find and zlistx_sort; the method - must return -1, 0, or 1 depending on whether item1 is less than, equal to, - or greater than, item2. - - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zloop.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zloop.api deleted file mode 100644 index 429e3b517a..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zloop.api +++ /dev/null @@ -1,176 +0,0 @@ - - - event-driven reactor - - - Callback function for reactor socket activity - - - - - - - - Callback function for reactor events (low-level) - - - - - - - - Callback for reactor timer events - - - - - - - - Create a new zloop reactor - - - - Destroy a reactor - - - - Register socket reader with the reactor. When the reader has messages, - the reactor will call the handler, passing the arg. Returns 0 if OK, -1 - if there was an error. If you register the same socket more than once, - each instance will invoke its corresponding handler. - - - - - - - - Cancel a socket reader from the reactor. If multiple readers exist for - same socket, cancels ALL of them. - - - - - Configure a registered reader to ignore errors. If you do not set this, - then readers that have errors are removed from the reactor silently. - - - - - Register low-level libzmq pollitem with the reactor. When the pollitem - is ready, will call the handler, passing the arg. Returns 0 if OK, -1 - if there was an error. If you register the pollitem more than once, each - instance will invoke its corresponding handler. A pollitem with - socket=NULL and fd=0 means 'poll on FD zero'. - - - - - - - - Cancel a pollitem from the reactor, specified by socket or FD. If both - are specified, uses only socket. If multiple poll items exist for same - socket/FD, cancels ALL of them. - - - - - Configure a registered poller to ignore errors. If you do not set this, - then poller that have errors are removed from the reactor silently. - - - - - Register a timer that expires after some delay and repeats some number of - times. At each expiry, will call the handler, passing the arg. To run a - timer forever, use 0 times. Returns a timer_id that is used to cancel the - timer in the future. Returns -1 if there was an error. - - - - - - - - - Cancel a specific timer identified by a specific timer_id (as returned by - zloop_timer). - - - - - - Register a ticket timer. Ticket timers are very fast in the case where - you use a lot of timers (thousands), and frequently remove and add them. - The main use case is expiry timers for servers that handle many clients, - and which reset the expiry timer for each message received from a client. - Whereas normal timers perform poorly as the number of clients grows, the - cost of ticket timers is constant, no matter the number of clients. You - must set the ticket delay using zloop_set_ticket_delay before creating a - ticket. Returns a handle to the timer that you should use in - zloop_ticket_reset and zloop_ticket_delete. - - - - - - - Reset a ticket timer, which moves it to the end of the ticket list and - resets its execution time. This is a very fast operation. - - - - - Delete a ticket timer. We do not actually delete the ticket here, as - other code may still refer to the ticket. We mark as deleted, and remove - later and safely. - - - - - Set the ticket delay, which applies to all tickets. If you lower the - delay and there are already tickets created, the results are undefined. - - - - - Set hard limit on number of timers allowed. Setting more than a small - number of timers (10-100) can have a dramatic impact on the performance - of the reactor. For high-volume cases, use ticket timers. If the hard - limit is reached, the reactor stops creating new timers and logs an - error. - - - - - Set verbose tracing of reactor on/off. The default verbose setting is - off (false). - - - - - By default the reactor stops if the process receives a SIGINT or SIGTERM - signal. This makes it impossible to shut-down message based architectures - like zactors. This method lets you switch off break handling. The default - nonstop setting is off (false). - - - - - Start the reactor. Takes control of the thread and returns when the 0MQ - context is terminated or the process is interrupted, or any event handler - returns -1. Event handlers may register new sockets and timers, and - cancel sockets. Returns 0 if interrupted, -1 if canceled by a handler. - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zmsg.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zmsg.api deleted file mode 100644 index 6205fd02e3..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zmsg.api +++ /dev/null @@ -1,250 +0,0 @@ - - - working with multipart messages - - - Create a new empty message object - - - - Destroy a message object and all frames it contains - - - - Receive message from socket, returns zmsg_t object or NULL if the recv - was interrupted. Does a blocking recv. If you want to not block then use - the zloop class or zmsg_recv_nowait or zmq_poll to check for socket input - before receiving. - - - - - Send message to destination socket, and destroy the message after sending - it successfully. If the message has no frames, sends nothing but destroys - the message anyhow. Nullifies the caller's reference to the message (as - it is a destructor). - - - - - - - Send message to destination socket as part of a multipart sequence, and - destroy the message after sending it successfully. Note that after a - zmsg_sendm, you must call zmsg_send or another method that sends a final - message part. If the message has no frames, sends nothing but destroys - the message anyhow. Nullifies the caller's reference to the message (as - it is a destructor). - - - - - - - Return size of message, i.e. number of frames (0 or more). - - - - - Return total size of all frames in message. - - - - - Return message routing ID, if the message came from a ZMQ_SERVER socket. - Else returns zero. - - - - - Set routing ID on message. This is used if/when the message is sent to a - ZMQ_SERVER socket. - - - - - Push frame to the front of the message, i.e. before all other frames. - Message takes ownership of frame, will destroy it when message is sent. - Returns 0 on success, -1 on error. Deprecates zmsg_push, which did not - nullify the caller's frame reference. - - - - - - Add frame to the end of the message, i.e. after all other frames. - Message takes ownership of frame, will destroy it when message is sent. - Returns 0 on success. Deprecates zmsg_add, which did not nullify the - caller's frame reference. - - - - - - Remove first frame from message, if any. Returns frame, or NULL. - - - - - Push block of memory to front of message, as a new frame. - Returns 0 on success, -1 on error. - - - - - - - Add block of memory to the end of the message, as a new frame. - Returns 0 on success, -1 on error. - - - - - - - Push string as new frame to front of message. - Returns 0 on success, -1 on error. - - - - - - Push string as new frame to end of message. - Returns 0 on success, -1 on error. - - - - - - Push formatted string as new frame to front of message. - Returns 0 on success, -1 on error. - - - - - - Push formatted string as new frame to end of message. - Returns 0 on success, -1 on error. - - - - - - Pop frame off front of message, return as fresh string. If there were - no more frames in the message, returns NULL. - - - - - Push encoded message as a new frame. Message takes ownership of - submessage, so the original is destroyed in this call. Returns 0 on - success, -1 on error. - - - - - - Remove first submessage from message, if any. Returns zmsg_t, or NULL if - decoding was not successful. - - - - - Remove specified frame from list, if present. Does not destroy frame. - - - - - Set cursor to first frame in message. Returns frame, or NULL, if the - message is empty. Use this to navigate the frames as a list. - - - - - Return the next frame. If there are no more frames, returns NULL. To move - to the first frame call zmsg_first(). Advances the cursor. - - - - - Return the last frame. If there are no frames, returns NULL. - - - - - Save message to an open file, return 0 if OK, else -1. The message is - saved as a series of frames, each with length and data. Note that the - file is NOT guaranteed to be portable between operating systems, not - versions of CZMQ. The file format is at present undocumented and liable - to arbitrary change. - - - - - - Load/append an open file into new message, return the message. - Returns NULL if the message could not be loaded. - - - - - Serialize multipart message to a single message frame. Use this method - to send structured messages across transports that do not support - multipart data. Allocates and returns a new frame containing the - serialized message. To decode a serialized message frame, use - zmsg_decode (). - - - - - Decodes a serialized message frame created by zmsg_encode () and returns - a new zmsg_t object. Returns NULL if the frame was badly formatted or - there was insufficient memory to work. - - - - - Create copy of message, as new message object. Returns a fresh zmsg_t - object. If message is null, or memory was exhausted, returns null. - - - - - Send message to zsys log sink (may be stdout, or system facility as - configured by zsys_set_logstream). - - - - Return true if the two messages have the same number of frames and each - frame in the first message is identical to the corresponding frame in the - other message. As with zframe_eq, return false if either message is NULL. - - - - - - Generate a signal message encoding the given status. A signal is a short - message carrying a 1-byte success/failure code (by convention, 0 means - OK). Signals are encoded to be distinguishable from "normal" messages. - - - - - Return signal value, 0 or greater, if message is a signal, -1 if not. - - - - - Probe the supplied object, and report if it looks like a zmsg_t. - - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zpoller.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zpoller.api deleted file mode 100644 index fc00f6a075..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zpoller.api +++ /dev/null @@ -1,71 +0,0 @@ - - - event-driven reactor - - - Create new poller, specifying zero or more readers. The list of - readers ends in a NULL. Each reader can be a zsock_t instance, a - zactor_t instance, a libzmq socket (void *), or a file handle. - - - - - Destroy a poller - - - - Add a reader to be polled. Returns 0 if OK, -1 on failure. The reader may - be a libzmq void * socket, a zsock_t instance, or a zactor_t instance. - - - - - - Remove a reader from the poller; returns 0 if OK, -1 on failure. The reader - must have been passed during construction, or in an zpoller_add () call. - - - - - - By default the poller stops if the process receives a SIGINT or SIGTERM - signal. This makes it impossible to shut-down message based architectures - like zactors. This method lets you switch off break handling. The default - nonstop setting is off (false). - - - - - Poll the registered readers for I/O, return first reader that has input. - The reader will be a libzmq void * socket, or a zsock_t or zactor_t - instance as specified in zpoller_new/zpoller_add. The timeout should be - zero or greater, or -1 to wait indefinitely. Socket priority is defined - by their order in the poll list. If you need a balanced poll, use the low - level zmq_poll method directly. If the poll call was interrupted (SIGINT), - or the ZMQ context was destroyed, or the timeout expired, returns NULL. - You can test the actual exit condition by calling zpoller_expired () and - zpoller_terminated (). The timeout is in msec. - - - - - - Return true if the last zpoller_wait () call ended because the timeout - expired, without any error. - - - - - Return true if the last zpoller_wait () call ended because the process - was interrupted, or the parent context was destroyed. - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zproc.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zproc.api deleted file mode 100644 index 52c1c9123b..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zproc.api +++ /dev/null @@ -1,139 +0,0 @@ - - - process configuration and status - - - Returns CZMQ version as a single 6-digit integer encoding the major - version (x 10000), the minor version (x 100) and the patch. - - - - - Returns true if the process received a SIGINT or SIGTERM signal. - It is good practice to use this method to exit any infinite loop - processing messages. - - - - - Returns true if the underlying libzmq supports CURVE security. - - - - - Return current host name, for use in public tcp:// endpoints. - If the host name is not resolvable, returns NULL. - - - - - Move the current process into the background. The precise effect - depends on the operating system. On POSIX boxes, moves to a specified - working directory (if specified), closes all file handles, reopens - stdin, stdout, and stderr to the null device, and sets the process to - ignore SIGHUP. On Windows, does nothing. Returns 0 if OK, -1 if there - was an error. - - - - - Drop the process ID into the lockfile, with exclusive lock, and - switch the process to the specified group and/or user. Any of the - arguments may be null, indicating a no-op. Returns 0 on success, - -1 on failure. Note if you combine this with zsys_daemonize, run - after, not before that method, or the lockfile will hold the wrong - process ID. - - - - - - - Configure the number of I/O threads that ZeroMQ will use. A good - rule of thumb is one thread per gigabit of traffic in or out. The - default is 1, sufficient for most applications. If the environment - variable ZSYS_IO_THREADS is defined, that provides the default. - Note that this method is valid only before any socket is created. - - - - - Configure the number of sockets that ZeroMQ will allow. The default - is 1024. The actual limit depends on the system, and you can query it - by using zsys_socket_limit (). A value of zero means "maximum". - Note that this method is valid only before any socket is created. - - - - - Set network interface name to use for broadcasts, particularly zbeacon. - This lets the interface be configured for test environments where required. - For example, on Mac OS X, zbeacon cannot bind to 255.255.255.255 which is - the default when there is no specified interface. If the environment - variable ZSYS_INTERFACE is set, use that as the default interface name. - Setting the interface to "*" means "use all available interfaces". - - - - - Return network interface to use for broadcasts, or "" if none was set. - - - - - Set log identity, which is a string that prefixes all log messages sent - by this process. The log identity defaults to the environment variable - ZSYS_LOGIDENT, if that is set. - - - - - Sends log output to a PUB socket bound to the specified endpoint. To - collect such log output, create a SUB socket, subscribe to the traffic - you care about, and connect to the endpoint. Log traffic is sent as a - single string frame, in the same format as when sent to stdout. The - log system supports a single sender; multiple calls to this method will - bind the same sender to multiple endpoints. To disable the sender, call - this method with a null argument. - - - - - Enable or disable logging to the system facility (syslog on POSIX boxes, - event log on Windows). By default this is disabled. - - - - - Log error condition - highest priority - - - - - Log warning condition - high priority - - - - - Log normal, but significant, condition - normal priority - - - - - Log informational message - low priority - - - - - Log debug-level message - lowest priority - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zsock.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zsock.api deleted file mode 100644 index 26b15cf509..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zsock.api +++ /dev/null @@ -1,406 +0,0 @@ - - - high-level socket API that hides libzmq contexts and sockets - - - Create a new socket. Returns the new socket, or NULL if the new socket - could not be created. Note that the symbol zsock_new (and other - constructors/destructors for zsock) are redirected to the *_checked - variant, enabling intelligent socket leak detection. This can have - performance implications if you use a LOT of sockets. To turn off this - redirection behaviour, define ZSOCK_NOCHECK. - - - - - - - - - - - - - - - - - - - - - - - - - - Destroy the socket. You must use this for any socket created via the - zsock_new method. - - - - Create a PUB socket. Default action is bind. - - - - - Create a SUB socket, and optionally subscribe to some prefix string. Default - action is connect. - - - - - - Create a REQ socket. Default action is connect. - - - - - Create a REP socket. Default action is bind. - - - - - Create a DEALER socket. Default action is connect. - - - - - Create a ROUTER socket. Default action is bind. - - - - - Create a PUSH socket. Default action is connect. - - - - - Create a PULL socket. Default action is bind. - - - - - Create an XPUB socket. Default action is bind. - - - - - Create an XSUB socket. Default action is connect. - - - - - Create a PAIR socket. Default action is connect. - - - - - Create a STREAM socket. Default action is connect. - - - - - Create a SERVER socket. Default action is bind. - - - - - Create a CLIENT socket. Default action is connect. - - - - - Create a RADIO socket. Default action is bind. - - - - - Create a DISH socket. Default action is connect. - - - - - Create a GATHER socket. Default action is bind. - - - - - Create a SCATTER socket. Default action is connect. - - - - - Bind a socket to a formatted endpoint. For tcp:// endpoints, supports - ephemeral ports, if you specify the port number as "*". By default - zsock uses the IANA designated range from C000 (49152) to FFFF (65535). - To override this range, follow the "*" with "[first-last]". Either or - both first and last may be empty. To bind to a random port within the - range, use "!" in place of "*". - - Examples: - tcp://127.0.0.1:* bind to first free port from C000 up - tcp://127.0.0.1:! bind to random port from C000 to FFFF - tcp://127.0.0.1:*[60000-] bind to first free port from 60000 up - tcp://127.0.0.1:![-60000] bind to random port from C000 to 60000 - tcp://127.0.0.1:![55000-55999] - bind to random port from 55000 to 55999 - - On success, returns the actual port number used, for tcp:// endpoints, - and 0 for other transports. On failure, returns -1. Note that when using - ephemeral ports, a port may be reused by different services without - clients being aware. Protocols that run on ephemeral ports should take - this into account. - - - - - - Returns last bound endpoint, if any. - - - - - Unbind a socket from a formatted endpoint. - Returns 0 if OK, -1 if the endpoint was invalid or the function - isn't supported. - - - - - - Connect a socket to a formatted endpoint - Returns 0 if OK, -1 if the endpoint was invalid. - - - - - - Disconnect a socket from a formatted endpoint - Returns 0 if OK, -1 if the endpoint was invalid or the function - isn't supported. - - - - - - Attach a socket to zero or more endpoints. If endpoints is not null, - parses as list of ZeroMQ endpoints, separated by commas, and prefixed by - '@' (to bind the socket) or '>' (to connect the socket). Returns 0 if all - endpoints were valid, or -1 if there was a syntax error. If the endpoint - does not start with '@' or '>', the serverish argument defines whether - it is used to bind (serverish = true) or connect (serverish = false). - - - - - - - Returns socket type as printable constant string. - - - - - Send a 'picture' message to the socket (or actor). The picture is a - string that defines the type of each frame. This makes it easy to send - a complex multiframe message in one call. The picture can contain any - of these characters, each corresponding to one or two arguments: - - i = int (signed) - 1 = uint8_t - 2 = uint16_t - 4 = uint32_t - 8 = uint64_t - s = char * - b = byte *, size_t (2 arguments) - c = zchunk_t * - f = zframe_t * - h = zhashx_t * - U = zuuid_t * - p = void * (sends the pointer value, only meaningful over inproc) - m = zmsg_t * (sends all frames in the zmsg) - z = sends zero-sized frame (0 arguments) - u = uint (deprecated) - - Note that s, b, c, and f are encoded the same way and the choice is - offered as a convenience to the sender, which may or may not already - have data in a zchunk or zframe. Does not change or take ownership of - any arguments. Returns 0 if successful, -1 if sending failed for any - reason. - - - - - - Send a 'picture' message to the socket (or actor). This is a va_list - version of zsock_send (), so please consult its documentation for the - details. - - - - - - - Receive a 'picture' message to the socket (or actor). See zsock_send for - the format and meaning of the picture. Returns the picture elements into - a series of pointers as provided by the caller: - - i = int * (stores signed integer) - 4 = uint32_t * (stores 32-bit unsigned integer) - 8 = uint64_t * (stores 64-bit unsigned integer) - s = char ** (allocates new string) - b = byte **, size_t * (2 arguments) (allocates memory) - c = zchunk_t ** (creates zchunk) - f = zframe_t ** (creates zframe) - U = zuuid_t * (creates a zuuid with the data) - h = zhashx_t ** (creates zhashx) - p = void ** (stores pointer) - m = zmsg_t ** (creates a zmsg with the remaing frames) - z = null, asserts empty frame (0 arguments) - u = uint * (stores unsigned integer, deprecated) - - Note that zsock_recv creates the returned objects, and the caller must - destroy them when finished with them. The supplied pointers do not need - to be initialized. Returns 0 if successful, or -1 if it failed to recv - a message, in which case the pointers are not modified. When message - frames are truncated (a short message), sets return values to zero/null. - If an argument pointer is NULL, does not store any value (skips it). - An 'n' picture matches an empty frame; if the message does not match, - the method will return -1. - - - - - - Receive a 'picture' message from the socket (or actor). This is a - va_list version of zsock_recv (), so please consult its documentation - for the details. - - - - - - - Send a binary encoded 'picture' message to the socket (or actor). This - method is similar to zsock_send, except the arguments are encoded in a - binary format that is compatible with zproto, and is designed to reduce - memory allocations. The pattern argument is a string that defines the - type of each argument. Supports these argument types: - - pattern C type zproto type: - 1 uint8_t type = "number" size = "1" - 2 uint16_t type = "number" size = "2" - 4 uint32_t type = "number" size = "3" - 8 uint64_t type = "number" size = "4" - s char *, 0-255 chars type = "string" - S char *, 0-2^32-1 chars type = "longstr" - c zchunk_t * type = "chunk" - f zframe_t * type = "frame" - u zuuid_t * type = "uuid" - m zmsg_t * type = "msg" - p void *, sends pointer value, only over inproc - - Does not change or take ownership of any arguments. Returns 0 if - successful, -1 if sending failed for any reason. - - - - - - Receive a binary encoded 'picture' message from the socket (or actor). - This method is similar to zsock_recv, except the arguments are encoded - in a binary format that is compatible with zproto, and is designed to - reduce memory allocations. The pattern argument is a string that defines - the type of each argument. See zsock_bsend for the supported argument - types. All arguments must be pointers; this call sets them to point to - values held on a per-socket basis. - Note that zsock_brecv creates the returned objects, and the caller must - destroy them when finished with them. The supplied pointers do not need - to be initialized. Returns 0 if successful, or -1 if it failed to read - a message. - - - - - - Return socket routing ID if any. This returns 0 if the socket is not - of type ZMQ_SERVER or if no request was already received on it. - - - - - Set routing ID on socket. The socket MUST be of type ZMQ_SERVER. - This will be used when sending messages on the socket via the zsock API. - - - - - Set socket to use unbounded pipes (HWM=0); use this in cases when you are - totally certain the message volume can fit in memory. This method works - across all versions of ZeroMQ. Takes a polymorphic socket reference. - - - - Send a signal over a socket. A signal is a short message carrying a - success/failure code (by convention, 0 means OK). Signals are encoded - to be distinguishable from "normal" messages. Accepts a zsock_t or a - zactor_t argument, and returns 0 if successful, -1 if the signal could - not be sent. Takes a polymorphic socket reference. - - - - - - Wait on a signal. Use this to coordinate between threads, over pipe - pairs. Blocks until the signal is received. Returns -1 on error, 0 or - greater on success. Accepts a zsock_t or a zactor_t as argument. - Takes a polymorphic socket reference. - - - - - If there is a partial message still waiting on the socket, remove and - discard it. This is useful when reading partial messages, to get specific - message types. - - - - Join a group for the RADIO-DISH pattern. Call only on ZMQ_DISH. - Returns 0 if OK, -1 if failed. - - - - - - Leave a group for the RADIO-DISH pattern. Call only on ZMQ_DISH. - Returns 0 if OK, -1 if failed. - - - - - - Probe the supplied object, and report if it looks like a zsock_t. - Takes a polymorphic socket reference. - - - - - - Probe the supplied reference. If it looks like a zsock_t instance, return - the underlying libzmq socket handle; else if it looks like a file - descriptor, return NULL; else if it looks like a libzmq socket handle, - return the supplied value. Takes a polymorphic socket reference. - - - - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zsock_option.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zsock_option.api deleted file mode 100644 index c5799b027e..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zsock_option.api +++ /dev/null @@ -1,797 +0,0 @@ - - - - - - Get socket option `heartbeat_ivl`. - Available from libzmq 4.2.0. - - - - - Set socket option `heartbeat_ivl`. - Available from libzmq 4.2.0. - - - - - Get socket option `heartbeat_ttl`. - Available from libzmq 4.2.0. - - - - - Set socket option `heartbeat_ttl`. - Available from libzmq 4.2.0. - - - - - Get socket option `heartbeat_timeout`. - Available from libzmq 4.2.0. - - - - - Set socket option `heartbeat_timeout`. - Available from libzmq 4.2.0. - - - - - Get socket option `use_fd`. - Available from libzmq 4.2.0. - - - - - Set socket option `use_fd`. - Available from libzmq 4.2.0. - - - - - Set socket option `xpub_manual`. - Available from libzmq 4.2.0. - - - - - Set socket option `xpub_welcome_msg`. - Available from libzmq 4.2.0. - - - - - Set socket option `stream_notify`. - Available from libzmq 4.2.0. - - - - - Get socket option `invert_matching`. - Available from libzmq 4.2.0. - - - - - Set socket option `invert_matching`. - Available from libzmq 4.2.0. - - - - - Set socket option `xpub_verboser`. - Available from libzmq 4.2.0. - - - - - Get socket option `connect_timeout`. - Available from libzmq 4.2.0. - - - - - Set socket option `connect_timeout`. - Available from libzmq 4.2.0. - - - - - Get socket option `tcp_maxrt`. - Available from libzmq 4.2.0. - - - - - Set socket option `tcp_maxrt`. - Available from libzmq 4.2.0. - - - - - Get socket option `thread_safe`. - Available from libzmq 4.2.0. - - - - - Get socket option `multicast_maxtpdu`. - Available from libzmq 4.2.0. - - - - - Set socket option `multicast_maxtpdu`. - Available from libzmq 4.2.0. - - - - - Get socket option `vmci_buffer_size`. - Available from libzmq 4.2.0. - - - - - Set socket option `vmci_buffer_size`. - Available from libzmq 4.2.0. - - - - - Get socket option `vmci_buffer_min_size`. - Available from libzmq 4.2.0. - - - - - Set socket option `vmci_buffer_min_size`. - Available from libzmq 4.2.0. - - - - - Get socket option `vmci_buffer_max_size`. - Available from libzmq 4.2.0. - - - - - Set socket option `vmci_buffer_max_size`. - Available from libzmq 4.2.0. - - - - - Get socket option `vmci_connect_timeout`. - Available from libzmq 4.2.0. - - - - - Set socket option `vmci_connect_timeout`. - Available from libzmq 4.2.0. - - - - - - - Get socket option `tos`. - Available from libzmq 4.1.0. - - - - - Set socket option `tos`. - Available from libzmq 4.1.0. - - - - - Set socket option `router_handover`. - Available from libzmq 4.1.0. - - - - - Set socket option `connect_rid`. - Available from libzmq 4.1.0. - - - - - Set socket option `connect_rid` from 32-octet binary - Available from libzmq 4.1.0. - - - - - Get socket option `handshake_ivl`. - Available from libzmq 4.1.0. - - - - - Set socket option `handshake_ivl`. - Available from libzmq 4.1.0. - - - - - Get socket option `socks_proxy`. - Available from libzmq 4.1.0. - - - - - Set socket option `socks_proxy`. - Available from libzmq 4.1.0. - - - - - Set socket option `xpub_nodrop`. - Available from libzmq 4.1.0. - - - - - - - Set socket option `router_mandatory`. - Available from libzmq 4.0.0. - - - - - Set socket option `probe_router`. - Available from libzmq 4.0.0. - - - - - Set socket option `req_relaxed`. - Available from libzmq 4.0.0. - - - - - Set socket option `req_correlate`. - Available from libzmq 4.0.0. - - - - - Set socket option `conflate`. - Available from libzmq 4.0.0. - - - - - Get socket option `zap_domain`. - Available from libzmq 4.0.0. - - - - - Set socket option `zap_domain`. - Available from libzmq 4.0.0. - - - - - Get socket option `mechanism`. - Available from libzmq 4.0.0. - - - - - Get socket option `plain_server`. - Available from libzmq 4.0.0. - - - - - Set socket option `plain_server`. - Available from libzmq 4.0.0. - - - - - Get socket option `plain_username`. - Available from libzmq 4.0.0. - - - - - Set socket option `plain_username`. - Available from libzmq 4.0.0. - - - - - Get socket option `plain_password`. - Available from libzmq 4.0.0. - - - - - Set socket option `plain_password`. - Available from libzmq 4.0.0. - - - - - Get socket option `curve_server`. - Available from libzmq 4.0.0. - - - - - Set socket option `curve_server`. - Available from libzmq 4.0.0. - - - - - Get socket option `curve_publickey`. - Available from libzmq 4.0.0. - - - - - Set socket option `curve_publickey`. - Available from libzmq 4.0.0. - - - - - Set socket option `curve_publickey` from 32-octet binary - Available from libzmq 4.0.0. - - - - - Get socket option `curve_secretkey`. - Available from libzmq 4.0.0. - - - - - Set socket option `curve_secretkey`. - Available from libzmq 4.0.0. - - - - - Set socket option `curve_secretkey` from 32-octet binary - Available from libzmq 4.0.0. - - - - - Get socket option `curve_serverkey`. - Available from libzmq 4.0.0. - - - - - Set socket option `curve_serverkey`. - Available from libzmq 4.0.0. - - - - - Set socket option `curve_serverkey` from 32-octet binary - Available from libzmq 4.0.0. - - - - - Get socket option `gssapi_server`. - Available from libzmq 4.0.0. - - - - - Set socket option `gssapi_server`. - Available from libzmq 4.0.0. - - - - - Get socket option `gssapi_plaintext`. - Available from libzmq 4.0.0. - - - - - Set socket option `gssapi_plaintext`. - Available from libzmq 4.0.0. - - - - - Get socket option `gssapi_principal`. - Available from libzmq 4.0.0. - - - - - Set socket option `gssapi_principal`. - Available from libzmq 4.0.0. - - - - - Get socket option `gssapi_service_principal`. - Available from libzmq 4.0.0. - - - - - Set socket option `gssapi_service_principal`. - Available from libzmq 4.0.0. - - - - - Get socket option `ipv6`. - Available from libzmq 4.0.0. - - - - - Set socket option `ipv6`. - Available from libzmq 4.0.0. - - - - - Get socket option `immediate`. - Available from libzmq 4.0.0. - - - - - Set socket option `immediate`. - Available from libzmq 4.0.0. - - - - - - - Get socket option `type`. - Available from libzmq 3.0.0. - - - - - Get socket option `sndhwm`. - Available from libzmq 3.0.0. - - - - - Set socket option `sndhwm`. - Available from libzmq 3.0.0. - - - - - Get socket option `rcvhwm`. - Available from libzmq 3.0.0. - - - - - Set socket option `rcvhwm`. - Available from libzmq 3.0.0. - - - - - Get socket option `affinity`. - Available from libzmq 3.0.0. - - - - - Set socket option `affinity`. - Available from libzmq 3.0.0. - - - - - Set socket option `subscribe`. - Available from libzmq 3.0.0. - - - - - Set socket option `unsubscribe`. - Available from libzmq 3.0.0. - - - - - Get socket option `identity`. - Available from libzmq 3.0.0. - - - - - Set socket option `identity`. - Available from libzmq 3.0.0. - - - - - Get socket option `rate`. - Available from libzmq 3.0.0. - - - - - Set socket option `rate`. - Available from libzmq 3.0.0. - - - - - Get socket option `recovery_ivl`. - Available from libzmq 3.0.0. - - - - - Set socket option `recovery_ivl`. - Available from libzmq 3.0.0. - - - - - Get socket option `sndbuf`. - Available from libzmq 3.0.0. - - - - - Set socket option `sndbuf`. - Available from libzmq 3.0.0. - - - - - Get socket option `rcvbuf`. - Available from libzmq 3.0.0. - - - - - Set socket option `rcvbuf`. - Available from libzmq 3.0.0. - - - - - Get socket option `linger`. - Available from libzmq 3.0.0. - - - - - Set socket option `linger`. - Available from libzmq 3.0.0. - - - - - Get socket option `reconnect_ivl`. - Available from libzmq 3.0.0. - - - - - Set socket option `reconnect_ivl`. - Available from libzmq 3.0.0. - - - - - Get socket option `reconnect_ivl_max`. - Available from libzmq 3.0.0. - - - - - Set socket option `reconnect_ivl_max`. - Available from libzmq 3.0.0. - - - - - Get socket option `backlog`. - Available from libzmq 3.0.0. - - - - - Set socket option `backlog`. - Available from libzmq 3.0.0. - - - - - Get socket option `maxmsgsize`. - Available from libzmq 3.0.0. - - - - - Set socket option `maxmsgsize`. - Available from libzmq 3.0.0. - - - - - Get socket option `multicast_hops`. - Available from libzmq 3.0.0. - - - - - Set socket option `multicast_hops`. - Available from libzmq 3.0.0. - - - - - Get socket option `rcvtimeo`. - Available from libzmq 3.0.0. - - - - - Set socket option `rcvtimeo`. - Available from libzmq 3.0.0. - - - - - Get socket option `sndtimeo`. - Available from libzmq 3.0.0. - - - - - Set socket option `sndtimeo`. - Available from libzmq 3.0.0. - - - - - Set socket option `xpub_verbose`. - Available from libzmq 3.0.0. - - - - - Get socket option `tcp_keepalive`. - Available from libzmq 3.0.0. - - - - - Set socket option `tcp_keepalive`. - Available from libzmq 3.0.0. - - - - - Get socket option `tcp_keepalive_idle`. - Available from libzmq 3.0.0. - - - - - Set socket option `tcp_keepalive_idle`. - Available from libzmq 3.0.0. - - - - - Get socket option `tcp_keepalive_cnt`. - Available from libzmq 3.0.0. - - - - - Set socket option `tcp_keepalive_cnt`. - Available from libzmq 3.0.0. - - - - - Get socket option `tcp_keepalive_intvl`. - Available from libzmq 3.0.0. - - - - - Set socket option `tcp_keepalive_intvl`. - Available from libzmq 3.0.0. - - - - - Get socket option `tcp_accept_filter`. - Available from libzmq 3.0.0. - - - - - Set socket option `tcp_accept_filter`. - Available from libzmq 3.0.0. - - - - - Get socket option `rcvmore`. - Available from libzmq 3.0.0. - - - - - Get socket option `fd`. - Available from libzmq 3.0.0. - - - - - Get socket option `events`. - Available from libzmq 3.0.0. - - - - - Get socket option `last_endpoint`. - Available from libzmq 3.0.0. - - - - - Set socket option `router_raw`. - Available from libzmq 3.0.0. - - - - - Get socket option `ipv4only`. - Available from libzmq 3.0.0. - - - - - Set socket option `ipv4only`. - Available from libzmq 3.0.0. - - - - - Set socket option `delay_attach_on_connect`. - Available from libzmq 3.0.0. - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zstr.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zstr.api deleted file mode 100644 index b4c951e720..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zstr.api +++ /dev/null @@ -1,90 +0,0 @@ - - - sending and receiving strings - - - Receive C string from socket. Caller must free returned string using - zstr_free(). Returns NULL if the context is being terminated or the - process was interrupted. - - - - - - Receive a series of strings (until NULL) from multipart data. - Each string is allocated and filled with string data; if there - are not enough frames, unallocated strings are set to NULL. - Returns -1 if the message could not be read, else returns the - number of strings filled, zero or more. Free each returned string - using zstr_free(). If not enough strings are provided, remaining - multipart frames in the message are dropped. - - - - - - - Send a C string to a socket, as a frame. The string is sent without - trailing null byte; to read this you can use zstr_recv, or a similar - method that adds a null terminator on the received string. String - may be NULL, which is sent as "". - - - - - - - Send a C string to a socket, as zstr_send(), with a MORE flag, so that - you can send further strings in the same multi-part message. - - - - - - - Send a formatted string to a socket. Note that you should NOT use - user-supplied strings in the format (they may contain '%' which - will create security holes). - - - - - - - Send a formatted string to a socket, as for zstr_sendf(), with a - MORE flag, so that you can send further strings in the same multi-part - message. - - - - - - - Send a series of strings (until NULL) as multipart data - Returns 0 if the strings could be sent OK, or -1 on error. - - - - - - - Accepts a void pointer and returns a fresh character string. If source - is null, returns an empty string. - - - - - - Free a provided string, and nullify the parent pointer. Safe to call on - a null pointer. - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/ztimerset.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/ztimerset.api deleted file mode 100644 index 20d3ca71ad..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/ztimerset.api +++ /dev/null @@ -1,69 +0,0 @@ - - - timer set - - - Create new timer set. - - - - Destroy a timer set - - - - Callback function for timer event. - - - - - - Add a timer to the set. Returns timer id if OK, -1 on failure. - - - - - - - - Cancel a timer. Returns 0 if OK, -1 on failure. - - - - - - Set timer interval. Returns 0 if OK, -1 on failure. - This method is slow, canceling the timer and adding a new one yield better performance. - - - - - - - Reset timer to start interval counting from current time. Returns 0 if OK, -1 on failure. - This method is slow, canceling the timer and adding a new one yield better performance. - - - - - - Return the time until the next interval. - Should be used as timeout parameter for the zpoller wait method. - The timeout is in msec. - - - - - Invoke callback function of all timers which their interval has elapsed. - Should be call after zpoller wait method. - Returns 0 if OK, -1 on failure. - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/ztrie.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/ztrie.api deleted file mode 100644 index 01fc3a4131..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/ztrie.api +++ /dev/null @@ -1,80 +0,0 @@ - - - simple trie for tokenizable strings - - - Callback function for ztrie_node to destroy node data. - - - - - Creates a new ztrie. - - - - - Destroy the ztrie. - - - - Inserts a new route into the tree and attaches the data. Returns -1 - if the route already exists, otherwise 0. This method takes ownership of - the provided data if a destroy_data_fn is provided. - - - - - - - - Removes a route from the trie and destroys its data. Returns -1 if the - route does not exists, otherwise 0. - the start of the list call zlist_first (). Advances the cursor. - - - - - - Returns true if the path matches a route in the tree, otherwise false. - - - - - - Returns the data of a matched route from last ztrie_matches. If the path - did not match, returns NULL. Do not delete the data as it's owned by - ztrie. - - - - - Returns the count of parameters that a matched route has. - - - - - Returns the parameters of a matched route with named regexes from last - ztrie_matches. If the path did not match or the route did not contain any - named regexes, returns NULL. - - - - - Returns the asterisk matched part of a route, if there has been no match - or no asterisk match, returns NULL. - - - - - Print the trie - - - diff --git a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zuuid.api b/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zuuid.api deleted file mode 100644 index 1fdb9c4e06..0000000000 --- a/phonelibs/zmq/aarch64-linux/share/zproject/czmq/zuuid.api +++ /dev/null @@ -1,82 +0,0 @@ - - - UUID support class - - - Create a new UUID object. - - - - Destroy a specified UUID object. - - - - Create UUID object from supplied ZUUID_LEN-octet value. - - - - - Set UUID to new supplied ZUUID_LEN-octet value. - - - - - Set UUID to new supplied string value skipping '-' and '{' '}' - optional delimiters. Return 0 if OK, else returns -1. - - - - - - Return UUID binary data. - - - - - Return UUID binary size - - - - - Returns UUID as string - - - - - Return UUID in the canonical string format: 8-4-4-4-12, in lower - case. Caller does not modify or free returned value. See - http://en.wikipedia.org/wiki/Universally_unique_identifier - - - - - Store UUID blob in target array - - - - - Check if UUID is same as supplied value - - - - - - Check if UUID is different from supplied value - - - - - - Make copy of UUID object; if uuid is null, or memory was exhausted, - returns null. - - - diff --git a/phonelibs/zmq/aarch64/include/czmq.h b/phonelibs/zmq/aarch64/include/czmq.h deleted file mode 100644 index ba21aa3bd1..0000000000 --- a/phonelibs/zmq/aarch64/include/czmq.h +++ /dev/null @@ -1,31 +0,0 @@ -/* ========================================================================= - CZMQ - a high-level binding in C for ZeroMQ - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __CZMQ_H_INCLUDED__ -#define __CZMQ_H_INCLUDED__ - -// These are signatures for handler functions that customize the -// behavior of CZMQ containers. These are shared between all CZMQ -// container types. - -// -- destroy an item -typedef void (czmq_destructor) (void **item); -// -- duplicate an item -typedef void *(czmq_duplicator) (const void *item); -// - compare two items, for sorting -typedef int (czmq_comparator) (const void *item1, const void *item2); - -// Include the project library file -#include "czmq_library.h" - -#endif diff --git a/phonelibs/zmq/aarch64/include/czmq_library.h b/phonelibs/zmq/aarch64/include/czmq_library.h deleted file mode 100644 index be348db3e9..0000000000 --- a/phonelibs/zmq/aarch64/include/czmq_library.h +++ /dev/null @@ -1,199 +0,0 @@ -/* ========================================================================= - czmq - generated layer of public API - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - -################################################################################ -# THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY # -# Read the zproject/README.md for information about making permanent changes. # -################################################################################ - ========================================================================= -*/ - -#ifndef CZMQ_LIBRARY_H_INCLUDED -#define CZMQ_LIBRARY_H_INCLUDED - -// Set up environment for the application -#include "czmq_prelude.h" - -// External dependencies -#include - -// CZMQ version macros for compile-time API detection -#define CZMQ_VERSION_MAJOR 3 -#define CZMQ_VERSION_MINOR 0 -#define CZMQ_VERSION_PATCH 3 - -#define CZMQ_MAKE_VERSION(major, minor, patch) \ - ((major) * 10000 + (minor) * 100 + (patch)) -#define CZMQ_VERSION \ - CZMQ_MAKE_VERSION(CZMQ_VERSION_MAJOR, CZMQ_VERSION_MINOR, CZMQ_VERSION_PATCH) - -#if defined (__WINDOWS__) -# if defined CZMQ_STATIC -# define CZMQ_EXPORT -# elif defined CZMQ_INTERNAL_BUILD -# if defined DLL_EXPORT -# define CZMQ_EXPORT __declspec(dllexport) -# else -# define CZMQ_EXPORT -# endif -# elif defined CZMQ_EXPORTS -# define CZMQ_EXPORT __declspec(dllexport) -# else -# define CZMQ_EXPORT __declspec(dllimport) -# endif -#else -# define CZMQ_EXPORT -#endif - -// Opaque class structures to allow forward references -// These classes are stable or legacy and built in all releases -typedef struct _zactor_t zactor_t; -#define ZACTOR_T_DEFINED -typedef struct _zarmour_t zarmour_t; -#define ZARMOUR_T_DEFINED -typedef struct _zcert_t zcert_t; -#define ZCERT_T_DEFINED -typedef struct _zcertstore_t zcertstore_t; -#define ZCERTSTORE_T_DEFINED -typedef struct _zchunk_t zchunk_t; -#define ZCHUNK_T_DEFINED -typedef struct _zclock_t zclock_t; -#define ZCLOCK_T_DEFINED -typedef struct _zconfig_t zconfig_t; -#define ZCONFIG_T_DEFINED -typedef struct _zdigest_t zdigest_t; -#define ZDIGEST_T_DEFINED -typedef struct _zdir_t zdir_t; -#define ZDIR_T_DEFINED -typedef struct _zdir_patch_t zdir_patch_t; -#define ZDIR_PATCH_T_DEFINED -typedef struct _zfile_t zfile_t; -#define ZFILE_T_DEFINED -typedef struct _zframe_t zframe_t; -#define ZFRAME_T_DEFINED -typedef struct _zhash_t zhash_t; -#define ZHASH_T_DEFINED -typedef struct _zhashx_t zhashx_t; -#define ZHASHX_T_DEFINED -typedef struct _ziflist_t ziflist_t; -#define ZIFLIST_T_DEFINED -typedef struct _zlist_t zlist_t; -#define ZLIST_T_DEFINED -typedef struct _zlistx_t zlistx_t; -#define ZLISTX_T_DEFINED -typedef struct _zloop_t zloop_t; -#define ZLOOP_T_DEFINED -typedef struct _zmsg_t zmsg_t; -#define ZMSG_T_DEFINED -typedef struct _zpoller_t zpoller_t; -#define ZPOLLER_T_DEFINED -typedef struct _zsock_t zsock_t; -#define ZSOCK_T_DEFINED -typedef struct _zstr_t zstr_t; -#define ZSTR_T_DEFINED -typedef struct _zuuid_t zuuid_t; -#define ZUUID_T_DEFINED -typedef struct _zauth_t zauth_t; -#define ZAUTH_T_DEFINED -typedef struct _zbeacon_t zbeacon_t; -#define ZBEACON_T_DEFINED -typedef struct _zgossip_t zgossip_t; -#define ZGOSSIP_T_DEFINED -typedef struct _zmonitor_t zmonitor_t; -#define ZMONITOR_T_DEFINED -typedef struct _zproxy_t zproxy_t; -#define ZPROXY_T_DEFINED -typedef struct _zrex_t zrex_t; -#define ZREX_T_DEFINED -typedef struct _zsys_t zsys_t; -#define ZSYS_T_DEFINED -typedef struct _zauth_v2_t zauth_v2_t; -#define ZAUTH_V2_T_DEFINED -typedef struct _zbeacon_v2_t zbeacon_v2_t; -#define ZBEACON_V2_T_DEFINED -typedef struct _zctx_t zctx_t; -#define ZCTX_T_DEFINED -typedef struct _zmonitor_v2_t zmonitor_v2_t; -#define ZMONITOR_V2_T_DEFINED -typedef struct _zmutex_t zmutex_t; -#define ZMUTEX_T_DEFINED -typedef struct _zproxy_v2_t zproxy_v2_t; -#define ZPROXY_V2_T_DEFINED -typedef struct _zsocket_t zsocket_t; -#define ZSOCKET_T_DEFINED -typedef struct _zsockopt_t zsockopt_t; -#define ZSOCKOPT_T_DEFINED -typedef struct _zthread_t zthread_t; -#define ZTHREAD_T_DEFINED -// Draft classes are by default not built in stable releases -#ifdef CZMQ_BUILD_DRAFT_API -typedef struct _zproc_t zproc_t; -#define ZPROC_T_DEFINED -typedef struct _ztimerset_t ztimerset_t; -#define ZTIMERSET_T_DEFINED -typedef struct _ztrie_t ztrie_t; -#define ZTRIE_T_DEFINED -#endif // CZMQ_BUILD_DRAFT_API - - -// Public classes, each with its own header file -#include "zactor.h" -#include "zarmour.h" -#include "zcert.h" -#include "zcertstore.h" -#include "zchunk.h" -#include "zclock.h" -#include "zconfig.h" -#include "zdigest.h" -#include "zdir.h" -#include "zdir_patch.h" -#include "zfile.h" -#include "zframe.h" -#include "zhash.h" -#include "zhashx.h" -#include "ziflist.h" -#include "zlist.h" -#include "zlistx.h" -#include "zloop.h" -#include "zmsg.h" -#include "zpoller.h" -#include "zsock.h" -#include "zstr.h" -#include "zuuid.h" -#include "zauth.h" -#include "zbeacon.h" -#include "zgossip.h" -#include "zmonitor.h" -#include "zproxy.h" -#include "zrex.h" -#include "zsys.h" -#include "zauth_v2.h" -#include "zbeacon_v2.h" -#include "zctx.h" -#include "zmonitor_v2.h" -#include "zmutex.h" -#include "zproxy_v2.h" -#include "zsocket.h" -#include "zsockopt.h" -#include "zthread.h" -#ifdef CZMQ_BUILD_DRAFT_API -#include "zproc.h" -#include "ztimerset.h" -#include "ztrie.h" -#endif // CZMQ_BUILD_DRAFT_API - -#endif -/* -################################################################################ -# THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY # -# Read the zproject/README.md for information about making permanent changes. # -################################################################################ -*/ diff --git a/phonelibs/zmq/aarch64/include/czmq_prelude.h b/phonelibs/zmq/aarch64/include/czmq_prelude.h deleted file mode 100644 index e9ceb691e8..0000000000 --- a/phonelibs/zmq/aarch64/include/czmq_prelude.h +++ /dev/null @@ -1,641 +0,0 @@ -/* ========================================================================= - czmq_prelude.h - CZMQ environment - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __CZMQ_PRELUDE_H_INCLUDED__ -#define __CZMQ_PRELUDE_H_INCLUDED__ - -//- Establish the compiler and computer system ------------------------------ -/* - * Defines zero or more of these symbols, for use in any non-portable - * code: - * - * __WINDOWS__ Microsoft C/C++ with Windows calls - * __MSDOS__ System is MS-DOS (set if __WINDOWS__ set) - * __VMS__ System is VAX/VMS or Alpha/OpenVMS - * __UNIX__ System is UNIX - * __OS2__ System is OS/2 - * - * __IS_32BIT__ OS/compiler is 32 bits - * __IS_64BIT__ OS/compiler is 64 bits - * - * When __UNIX__ is defined, we also define exactly one of these: - * - * __UTYPE_AUX Apple AUX - * __UTYPE_BEOS BeOS - * __UTYPE_BSDOS BSD/OS - * __UTYPE_DECALPHA Digital UNIX (Alpha) - * __UTYPE_IBMAIX IBM RS/6000 AIX - * __UTYPE_FREEBSD FreeBSD - * __UTYPE_HPUX HP/UX - * __UTYPE_ANDROID Android - * __UTYPE_LINUX Linux - * __UTYPE_GNU GNU/Hurd - * __UTYPE_MIPS MIPS (BSD 4.3/System V mixture) - * __UTYPE_NETBSD NetBSD - * __UTYPE_NEXT NeXT - * __UTYPE_OPENBSD OpenBSD - * __UTYPE_OSX Apple Macintosh OS X - * __UTYPE_IOS Apple iOS - * __UTYPE_QNX QNX - * __UTYPE_IRIX Silicon Graphics IRIX - * __UTYPE_SINIX SINIX-N (Siemens-Nixdorf Unix) - * __UTYPE_SUNOS SunOS - * __UTYPE_SUNSOLARIS Sun Solaris - * __UTYPE_UNIXWARE SCO UnixWare - * ... these are the ones I know about so far. - * __UTYPE_GENERIC Any other UNIX - * - * When __VMS__ is defined, we may define one or more of these: - * - * __VMS_XOPEN Supports XOPEN functions - */ - -#if (defined (__64BIT__) || defined (__x86_64__)) -# define __IS_64BIT__ // May have 64-bit OS/compiler -#else -# define __IS_32BIT__ // Else assume 32-bit OS/compiler -#endif - -#if (defined WIN32 || defined _WIN32) -# undef __WINDOWS__ -# define __WINDOWS__ -# undef __MSDOS__ -# define __MSDOS__ -#endif - -#if (defined WINDOWS || defined _WINDOWS || defined __WINDOWS__) -# undef __WINDOWS__ -# define __WINDOWS__ -# undef __MSDOS__ -# define __MSDOS__ -// Stop cheeky warnings about "deprecated" functions like fopen -# if _MSC_VER >= 1500 -# undef _CRT_SECURE_NO_DEPRECATE -# define _CRT_SECURE_NO_DEPRECATE -# pragma warning(disable: 4996) -# endif -#endif - -// MSDOS Microsoft C -// _MSC_VER Microsoft C -#if (defined (MSDOS) || defined (_MSC_VER)) -# undef __MSDOS__ -# define __MSDOS__ -# if (defined (_DEBUG) && !defined (DEBUG)) -# define DEBUG -# endif -#endif - -#if (defined (__EMX__) && defined (__i386__)) -# undef __OS2__ -# define __OS2__ -#endif - -// VMS VAX C (VAX/VMS) -// __VMS Dec C (Alpha/OpenVMS) -// __vax__ gcc -#if (defined (VMS) || defined (__VMS) || defined (__vax__)) -# undef __VMS__ -# define __VMS__ -# if (__VMS_VER >= 70000000) -# define __VMS_XOPEN -# endif -#endif - -// Try to define a __UTYPE_xxx symbol... -// unix SunOS at least -// __unix__ gcc -// _POSIX_SOURCE is various UNIX systems, maybe also VAX/VMS -#if (defined (unix) || defined (__unix__) || defined (_POSIX_SOURCE)) -# if (!defined (__VMS__)) -# undef __UNIX__ -# define __UNIX__ -# if (defined (__alpha)) // Digital UNIX is 64-bit -# undef __IS_32BIT__ -# define __IS_64BIT__ -# define __UTYPE_DECALPHA -# endif -# endif -#endif - -#if (defined (_AUX)) -# define __UTYPE_AUX -# define __UNIX__ -#elif (defined (__BEOS__)) -# define __UTYPE_BEOS -# define __UNIX__ -#elif (defined (__hpux)) -# define __UTYPE_HPUX -# define __UNIX__ -# define _INCLUDE_HPUX_SOURCE -# define _INCLUDE_XOPEN_SOURCE -# define _INCLUDE_POSIX_SOURCE -#elif (defined (_AIX) || defined (AIX)) -# define __UTYPE_IBMAIX -# define __UNIX__ -#elif (defined (BSD) || defined (bsd)) -# define __UTYPE_BSDOS -# define __UNIX__ -#elif (defined (__ANDROID__)) -# define __UTYPE_ANDROID -# define __UNIX__ -#elif (defined (LINUX) || defined (linux) || defined (__linux__)) -# define __UTYPE_LINUX -# define __UNIX__ -# ifndef __NO_CTYPE -# define __NO_CTYPE // Suppress warnings on tolower() -# endif -# ifndef _DEFAULT_SOURCE -# define _DEFAULT_SOURCE // Include stuff from 4.3 BSD Unix -# endif -#elif (defined (__GNU__)) -# define __UTYPE_GNU -# define __UNIX__ -#elif (defined (Mips)) -# define __UTYPE_MIPS -# define __UNIX__ -#elif (defined (FreeBSD) || defined (__FreeBSD__)) -# define __UTYPE_FREEBSD -# define __UNIX__ -#elif (defined (NetBSD) || defined (__NetBSD__)) -# define __UTYPE_NETBSD -# define __UNIX__ -#elif (defined (OpenBSD) || defined (__OpenBSD__)) -# define __UTYPE_OPENBSD -# define __UNIX__ -#elif (defined (APPLE) || defined (__APPLE__)) -# include -# define __UNIX__ -# if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR -# define __UTYPE_IOS -# else -# define __UTYPE_OSX -# endif -#elif (defined (NeXT)) -# define __UTYPE_NEXT -# define __UNIX__ -#elif (defined (__QNX__)) -# define __UTYPE_QNX -# define __UNIX__ -#elif (defined (sgi)) -# define __UTYPE_IRIX -# define __UNIX__ -#elif (defined (sinix)) -# define __UTYPE_SINIX -# define __UNIX__ -#elif (defined (SOLARIS) || defined (__SRV4)) -# define __UTYPE_SUNSOLARIS -# define __UNIX__ -#elif (defined (SUNOS) || defined (SUN) || defined (sun)) -# define __UTYPE_SUNOS -# define __UNIX__ -#elif (defined (__USLC__) || defined (UnixWare)) -# define __UTYPE_UNIXWARE -# define __UNIX__ -#elif (defined (__CYGWIN__)) -# define __UTYPE_CYGWIN -# define __UNIX__ -#elif (defined (__UNIX__)) -# define __UTYPE_GENERIC -#endif - -//- Always include ZeroMQ headers ------------------------------------------- - -#include "zmq.h" -#if (ZMQ_VERSION < ZMQ_MAKE_VERSION (4, 2, 0)) -# include "zmq_utils.h" -#endif - -//- Standard ANSI include files --------------------------------------------- - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -//- System-specific include files ------------------------------------------- - -#if (defined (__MSDOS__)) -# if (defined (__WINDOWS__)) -# if (_WIN32_WINNT < 0x0501) -# undef _WIN32_WINNT -# define _WIN32_WINNT 0x0501 -# endif -# if (!defined (FD_SETSIZE)) -# define FD_SETSIZE 1024 // Max. filehandles/sockets -# endif -# include -# include -# include -# include -# include // For getnameinfo () -# include // For GetAdaptersAddresses () -# endif -# include -# include -# include -# include -# include -# include -# include -# include -#endif - -#if (defined (__UNIX__)) -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include // Let CZMQ build with libzmq/3.x -# include // Must come before arpa/inet.h -# if (!defined (__UTYPE_ANDROID)) && (!defined (__UTYPE_IBMAIX)) \ - && (!defined (__UTYPE_HPUX)) -# include -# endif -# if defined (__UTYPE_SUNSOLARIS) || defined (__UTYPE_SUNOS) -# include -# endif -# if (!defined (__UTYPE_BEOS)) -# include -# if (!defined (TCP_NODELAY)) -# include -# endif -# endif -# if (defined (__UTYPE_IBMAIX) || defined(__UTYPE_QNX)) -# include -# endif -# if (defined (__UTYPE_BEOS)) -# include -# endif -# if ((defined (_XOPEN_REALTIME) && (_XOPEN_REALTIME >= 1)) \ - || (defined (_POSIX_VERSION) && (_POSIX_VERSION >= 199309L))) -# include -# endif -# if (defined (__UTYPE_OSX) || defined (__UTYPE_IOS)) -# include -# include // For monotonic clocks -# endif -# if (defined (__UTYPE_OSX)) -# include // For _NSGetEnviron() -# endif -# if (defined (__UTYPE_ANDROID)) -# include -# endif -# if (defined (__UTYPE_LINUX) && defined (HAVE_LIBSYSTEMD)) -# include -# endif -#endif - -#if (defined (__VMS__)) -# if (!defined (vaxc)) -# include // Not provided by Vax C -# endif -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -#endif - -#if (defined (__OS2__)) -# include // Required near top -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include // Must come before arpa/inet.h -# include -# include -# if (!defined (TCP_NODELAY)) -# include -# endif -#endif - -// Add missing defines for non-POSIX systems -#ifndef S_IRUSR -# define S_IRUSR S_IREAD -#endif -#ifndef S_IWUSR -# define S_IWUSR S_IWRITE -#endif -#ifndef S_ISDIR -# define S_ISDIR(m) (((m) & S_IFDIR) != 0) -#endif -#ifndef S_ISREG -# define S_ISREG(m) (((m) & S_IFREG) != 0) -#endif - - -//- Check compiler data type sizes ------------------------------------------ - -#if (UCHAR_MAX != 0xFF) -# error "Cannot compile: must change definition of 'byte'." -#endif -#if (USHRT_MAX != 0xFFFFU) -# error "Cannot compile: must change definition of 'dbyte'." -#endif -#if (UINT_MAX != 0xFFFFFFFFU) -# error "Cannot compile: must change definition of 'qbyte'." -#endif - -//- Data types -------------------------------------------------------------- - -typedef unsigned char byte; // Single unsigned byte = 8 bits -typedef unsigned short dbyte; // Double byte = 16 bits -typedef unsigned int qbyte; // Quad byte = 32 bits -typedef struct sockaddr_in inaddr_t; // Internet socket address structure -typedef struct sockaddr_in6 in6addr_t; // Internet 6 socket address structure - -// Common structure to hold inaddr_t and in6addr_t with length -typedef struct { - union { - inaddr_t __addr; // IPv4 address - in6addr_t __addr6; // IPv6 address - } __inaddr_u; -#define ipv4addr __inaddr_u.__addr -#define ipv6addr __inaddr_u.__addr6 - int inaddrlen; -} inaddr_storage_t; - -//- Inevitable macros ------------------------------------------------------- - -#define streq(s1,s2) (!strcmp ((s1), (s2))) -#define strneq(s1,s2) (strcmp ((s1), (s2))) - -// Provide random number from 0..(num-1) -#if (defined (__WINDOWS__)) || (defined (__UTYPE_IBMAIX)) \ - || (defined (__UTYPE_HPUX)) || (defined (__UTYPE_SUNOS)) -# define randof(num) (int) ((float) (num) * rand () / (RAND_MAX + 1.0)) -#else -# define randof(num) (int) ((float) (num) * random () / (RAND_MAX + 1.0)) -#endif - -// Windows MSVS doesn't have stdbool -#if (defined (_MSC_VER)) -# if (!defined (__cplusplus) && (!defined (true))) -# define true 1 -# define false 0 - typedef char bool; -# endif -#else -# include -#endif - -//- A number of POSIX and C99 keywords and data types ----------------------- -// CZMQ uses uint for array indices; equivalent to unsigned int, but more -// convenient in code. We define it in czmq_prelude.h on systems that do -// not define it by default. - -#if (defined (__WINDOWS__)) -# if (!defined (__cplusplus) && (!defined (inline))) -# define inline __inline -# endif -# define strtoull _strtoui64 -# define atoll _atoi64 -# define srandom srand -# define TIMEZONE _timezone -# if (!defined (__MINGW32__)) -# define snprintf _snprintf -# define vsnprintf _vsnprintf -# endif - typedef unsigned long ulong; - typedef unsigned int uint; -# if (!defined (__MINGW32__)) - typedef int mode_t; -# if !defined (_SSIZE_T_DEFINED) -typedef intptr_t ssize_t; -# define _SSIZE_T_DEFINED -# endif -# endif -# if ((!defined (__MINGW32__) \ - || (defined (__MINGW32__) && defined (__IS_64BIT__))) \ - && !defined (ZMQ_DEFINED_STDINT)) - typedef __int8 int8_t; - typedef __int16 int16_t; - typedef __int32 int32_t; - typedef __int64 int64_t; - typedef unsigned __int8 uint8_t; - typedef unsigned __int16 uint16_t; - typedef unsigned __int32 uint32_t; - typedef unsigned __int64 uint64_t; -# endif - typedef uint32_t in_addr_t; -# if (!defined (PRId8)) -# define PRId8 "d" -# endif -# if (!defined (PRId16)) -# define PRId16 "d" -# endif -# if (!defined (PRId32)) -# define PRId32 "d" -# endif -# if (!defined (PRId64)) -# define PRId64 "I64d" -# endif -# if (!defined (PRIu8)) -# define PRIu8 "u" -# endif -# if (!defined (PRIu16)) -# define PRIu16 "u" -# endif -# if (!defined (PRIu32)) -# define PRIu32 "u" -# endif -# if (!defined (PRIu64)) -# define PRIu64 "I64u" -# endif -# if (!defined (va_copy)) - // MSVC does not support C99's va_copy so we use a regular assignment -# define va_copy(dest,src) (dest) = (src) -# endif -#elif (defined (__UTYPE_OSX)) - typedef unsigned long ulong; - typedef unsigned int uint; - // This fixes header-order dependence problem with some Linux versions -#elif (defined (__UTYPE_LINUX)) -# if (__STDC_VERSION__ >= 199901L && !defined (__USE_MISC)) - typedef unsigned int uint; -# endif -#endif - -//- Non-portable declaration specifiers ------------------------------------- - -// For thread-local storage -#if defined (__WINDOWS__) -# define CZMQ_THREADLS __declspec(thread) -#else -# define CZMQ_THREADLS __thread -#endif - -// Replacement for malloc() which asserts if we run out of heap, and -// which zeroes the allocated block. -static inline void * -safe_malloc (size_t size, const char *file, unsigned line) -{ -// printf ("%s:%u %08d\n", file, line, (int) size); - void *mem = calloc (1, size); - if (mem == NULL) { - fprintf (stderr, "FATAL ERROR at %s:%u\n", file, line); - fprintf (stderr, "OUT OF MEMORY (malloc returned NULL)\n"); - fflush (stderr); - abort (); - } - return mem; -} - -// Define _ZMALLOC_DEBUG if you need to trace memory leaks using e.g. mtrace, -// otherwise all allocations will claim to come from czmq_prelude.h. For best -// results, compile all classes so you see dangling object allocations. -// _ZMALLOC_PEDANTIC does the same thing, but its intention is to propagate -// out of memory condition back up the call stack. -#if defined _ZMALLOC_DEBUG || _ZMALLOC_PEDANTIC -# define zmalloc(size) calloc(1,(size)) -#else -# define zmalloc(size) safe_malloc((size), __FILE__, __LINE__) -#endif - -// GCC supports validating format strings for functions that act like printf -#if defined (__GNUC__) && (__GNUC__ >= 2) -# define CHECK_PRINTF(a) __attribute__((format (printf, a, a + 1))) -#else -# define CHECK_PRINTF(a) -#endif - -// Lets us write code that compiles both on Windows and normal platforms -#if !defined (__WINDOWS__) -typedef int SOCKET; -# define closesocket close -# define INVALID_SOCKET -1 -# define SOCKET_ERROR -1 -# define O_BINARY 0 -#endif - -//- Include non-portable header files based on platform.h ------------------- - -#if defined (HAVE_LINUX_WIRELESS_H) -# include -// This would normally come from net/if.h -unsigned int if_nametoindex (const char *ifname); -#else -# if defined (HAVE_NET_IF_H) -# include -# endif -# if defined (HAVE_NET_IF_MEDIA_H) -# include -# endif -#endif - -#if defined (__WINDOWS__) && !defined (HAVE_UUID) -# define HAVE_UUID 1 -#endif -#if defined (__UTYPE_OSX) && !defined (HAVE_UUID) -# define HAVE_UUID 1 -#endif -#if defined (HAVE_UUID) -# if defined (__UTYPE_FREEBSD) || defined (__UTYPE_NETBSD) -# include -# elif defined __UTYPE_HPUX -# include -# elif defined (__UNIX__) -# include -# endif -#endif - -// ZMQ compatibility macros - -#if ZMQ_VERSION_MAJOR == 4 -# define ZMQ_POLL_MSEC 1 // zmq_poll is msec - -#elif ZMQ_VERSION_MAJOR == 3 -# define ZMQ_POLL_MSEC 1 // zmq_poll is msec -# if ZMQ_VERSION_MINOR < 2 -# define zmq_ctx_new zmq_init -# endif -# define zmq_ctx_term zmq_term - -#elif ZMQ_VERSION_MAJOR == 2 -# define ZMQ_POLL_MSEC 1000 // zmq_poll is usec -# define zmq_sendmsg zmq_send // Smooth out 2.x changes -# define zmq_recvmsg zmq_recv -# define zmq_ctx_new zmq_init -# define zmq_ctx_term zmq_term -# define zmq_msg_send(m,s,f) zmq_sendmsg ((s),(m),(f)) -# define zmq_msg_recv(m,s,f) zmq_recvmsg ((s),(m),(f)) - // Older libzmq APIs may be missing some aspects of libzmq v3.0 -# ifndef ZMQ_ROUTER -# define ZMQ_ROUTER ZMQ_XREP -# endif -# ifndef ZMQ_DEALER -# define ZMQ_DEALER ZMQ_XREQ -# endif -# ifndef ZMQ_DONTWAIT -# define ZMQ_DONTWAIT ZMQ_NOBLOCK -# endif -# ifndef ZMQ_XSUB -# error "please upgrade your libzmq from http://zeromq.org" -# endif -# if ZMQ_VERSION_MINOR == 0 \ - || (ZMQ_VERSION_MINOR == 1 && ZMQ_VERSION_PATCH < 7) -# error "CZMQ requires at least libzmq/2.1.7 stable" -# endif -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zactor.h b/phonelibs/zmq/aarch64/include/zactor.h deleted file mode 100644 index c865c65daf..0000000000 --- a/phonelibs/zmq/aarch64/include/zactor.h +++ /dev/null @@ -1,76 +0,0 @@ -/* ========================================================================= - zactor - actor - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZACTOR_H_INCLUDED__ -#define __ZACTOR_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zactor.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Actors get a pipe and arguments from caller -typedef void (zactor_fn) ( - zsock_t *pipe, void *args); - -// Create a new actor passing arbitrary arguments reference. -CZMQ_EXPORT zactor_t * - zactor_new (zactor_fn task, void *args); - -// Destroy an actor. -CZMQ_EXPORT void - zactor_destroy (zactor_t **self_p); - -// Send a zmsg message to the actor, take ownership of the message -// and destroy when it has been sent. -CZMQ_EXPORT int - zactor_send (zactor_t *self, zmsg_t **msg_p); - -// Receive a zmsg message from the actor. Returns NULL if the actor -// was interrupted before the message could be received, or if there -// was a timeout on the actor. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zmsg_t * - zactor_recv (zactor_t *self); - -// Probe the supplied object, and report if it looks like a zactor_t. -CZMQ_EXPORT bool - zactor_is (void *self); - -// Probe the supplied reference. If it looks like a zactor_t instance, -// return the underlying libzmq actor handle; else if it looks like -// a libzmq actor handle, return the supplied value. -CZMQ_EXPORT void * - zactor_resolve (void *self); - -// Return the actor's zsock handle. Use this when you absolutely need -// to work with the zsock instance rather than the actor. -CZMQ_EXPORT zsock_t * - zactor_sock (zactor_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zactor_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zarmour.h b/phonelibs/zmq/aarch64/include/zarmour.h deleted file mode 100644 index c7f299f7af..0000000000 --- a/phonelibs/zmq/aarch64/include/zarmour.h +++ /dev/null @@ -1,114 +0,0 @@ -/* ========================================================================= - zarmour - armoured text encoding and decoding - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZARMOUR_H_INCLUDED__ -#define __ZARMOUR_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zarmour.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -#define ZARMOUR_MODE_BASE64_STD 0 // Standard base 64 -#define ZARMOUR_MODE_BASE64_URL 1 // URL and filename friendly base 64 -#define ZARMOUR_MODE_BASE32_STD 2 // Standard base 32 -#define ZARMOUR_MODE_BASE32_HEX 3 // Extended hex base 32 -#define ZARMOUR_MODE_BASE16 4 // Standard base 16 -#define ZARMOUR_MODE_Z85 5 // Z85 from ZeroMQ RFC 32 - -// Create a new zarmour -CZMQ_EXPORT zarmour_t * - zarmour_new (void); - -// Destroy the zarmour -CZMQ_EXPORT void - zarmour_destroy (zarmour_t **self_p); - -// Encode a stream of bytes into an armoured string. Returns the armoured -// string, or NULL if there was insufficient memory available to allocate -// a new string. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zarmour_encode (zarmour_t *self, const byte *data, size_t size); - -// Decode an armoured string into a chunk. The decoded output is -// null-terminated, so it may be treated as a string, if that's what -// it was prior to encoding. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zchunk_t * - zarmour_decode (zarmour_t *self, const char *data); - -// Get the mode property. -CZMQ_EXPORT int - zarmour_mode (zarmour_t *self); - -// Get printable string for mode. -CZMQ_EXPORT const char * - zarmour_mode_str (zarmour_t *self); - -// Set the mode property. -CZMQ_EXPORT void - zarmour_set_mode (zarmour_t *self, int mode); - -// Return true if padding is turned on. -CZMQ_EXPORT bool - zarmour_pad (zarmour_t *self); - -// Turn padding on or off. Default is on. -CZMQ_EXPORT void - zarmour_set_pad (zarmour_t *self, bool pad); - -// Get the padding character. -CZMQ_EXPORT char - zarmour_pad_char (zarmour_t *self); - -// Set the padding character. -CZMQ_EXPORT void - zarmour_set_pad_char (zarmour_t *self, char pad_char); - -// Return if splitting output into lines is turned on. Default is off. -CZMQ_EXPORT bool - zarmour_line_breaks (zarmour_t *self); - -// Turn splitting output into lines on or off. -CZMQ_EXPORT void - zarmour_set_line_breaks (zarmour_t *self, bool line_breaks); - -// Get the line length used for splitting lines. -CZMQ_EXPORT size_t - zarmour_line_length (zarmour_t *self); - -// Set the line length used for splitting lines. -CZMQ_EXPORT void - zarmour_set_line_length (zarmour_t *self, size_t line_length); - -// Print properties of object -CZMQ_EXPORT void - zarmour_print (zarmour_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zarmour_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zauth.h b/phonelibs/zmq/aarch64/include/zauth.h deleted file mode 100644 index ca6bb913c8..0000000000 --- a/phonelibs/zmq/aarch64/include/zauth.h +++ /dev/null @@ -1,100 +0,0 @@ -/* ========================================================================= - zauth - authentication for ZeroMQ security mechanisms - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZAUTH_H_INCLUDED__ -#define __ZAUTH_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -#define CURVE_ALLOW_ANY "*" - -// CZMQ v3 API (for use with zsock, not zsocket, which is deprecated). -// -// Create new zauth actor instance. This installs authentication on all -// zsock sockets. Until you add policies, all incoming NULL connections are -// allowed (classic ZeroMQ behaviour), and all PLAIN and CURVE connections -// are denied: -// -// zactor_t *auth = zactor_new (zauth, NULL); -// -// Destroy zauth instance. This removes authentication and allows all -// connections to pass, without authentication: -// -// zactor_destroy (&auth); -// -// Note that all zauth commands are synchronous, so your application always -// waits for a signal from the actor after each command. -// -// Enable verbose logging of commands and activity. Verbose logging can help -// debug non-trivial authentication policies: -// -// zstr_send (auth, "VERBOSE"); -// zsock_wait (auth); -// -// Allow (whitelist) a list of IP addresses. For NULL, all clients from -// these addresses will be accepted. For PLAIN and CURVE, they will be -// allowed to continue with authentication. You can call this method -// multiple times to whitelist more IP addresses. If you whitelist one -// or nmore addresses, any non-whitelisted addresses are treated as -// blacklisted: -// -// zstr_sendx (auth, "ALLOW", "127.0.0.1", "127.0.0.2", NULL); -// zsock_wait (auth); -// -// Deny (blacklist) a list of IP addresses. For all security mechanisms, -// this rejects the connection without any further authentication. Use -// either a whitelist, or a blacklist, not not both. If you define both -// a whitelist and a blacklist, only the whitelist takes effect: -// -// zstr_sendx (auth, "DENY", "192.168.0.1", "192.168.0.2", NULL); -// zsock_wait (auth); -// -// Configure PLAIN authentication using a plain-text password file. You can -// modify the password file at any time; zauth will reload it automatically -// if modified externally: -// -// zstr_sendx (auth, "PLAIN", filename, NULL); -// zsock_wait (auth); -// -// Configure CURVE authentication, using a directory that holds all public -// client certificates, i.e. their public keys. The certificates must be in -// zcert_save format. You can add and remove certificates in that directory -// at any time. To allow all client keys without checking, specify -// CURVE_ALLOW_ANY for the directory name: -// -// zstr_sendx (auth, "CURVE", directory, NULL); -// zsock_wait (auth); -// -// Configure GSSAPI authentication, using an underlying mechanism (usually -// Kerberos) to establish a secure context and perform mutual authentication: -// -// zstr_sendx (auth, "GSSAPI", NULL); -// zsock_wait (auth); -// -// This is the zauth constructor as a zactor_fn: -CZMQ_EXPORT void - zauth (zsock_t *pipe, void *certstore); - -// Selftest -CZMQ_EXPORT void - zauth_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zauth_v2.h b/phonelibs/zmq/aarch64/include/zauth_v2.h deleted file mode 100644 index bbbee86b03..0000000000 --- a/phonelibs/zmq/aarch64/include/zauth_v2.h +++ /dev/null @@ -1,88 +0,0 @@ -/* ========================================================================= - zauth_v2 - authentication for ZeroMQ servers (deprecated) - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZAUTH_V2_H_INCLUDED__ -#define __ZAUTH_V2_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -#ifndef CURVE_ALLOW_ANY -# define CURVE_ALLOW_ANY "*" -#endif - -// Constructor -// Install authentication for the specified context. Returns a new zauth -// object that you can use to configure authentication. Note that until you -// add policies, all incoming NULL connections are allowed (classic ZeroMQ -// behaviour), and all PLAIN and CURVE connections are denied. If there was -// an error during initialization, returns NULL. -CZMQ_EXPORT zauth_t * - zauth_new (zctx_t *ctx); - -// Destructor -CZMQ_EXPORT void - zauth_destroy (zauth_t **self_p); - -// Allow (whitelist) a single IP address. For NULL, all clients from this -// address will be accepted. For PLAIN and CURVE, they will be allowed to -// continue with authentication. You can call this method multiple times -// to whitelist multiple IP addresses. If you whitelist a single address, -// any non-whitelisted addresses are treated as blacklisted. -CZMQ_EXPORT void - zauth_allow (zauth_t *self, const char *address); - -// Deny (blacklist) a single IP address. For all security mechanisms, this -// rejects the connection without any further authentication. Use either a -// whitelist, or a blacklist, not not both. If you define both a whitelist -// and a blacklist, only the whitelist takes effect. -CZMQ_EXPORT void - zauth_deny (zauth_t *self, const char *address); - -// Configure PLAIN authentication for a given domain. PLAIN authentication -// uses a plain-text password file. To cover all domains, use "*". You can -// modify the password file at any time; it is reloaded automatically. -CZMQ_EXPORT void - zauth_configure_plain (zauth_t *self, const char *domain, const char *filename); - -// Configure CURVE authentication for a given domain. CURVE authentication -// uses a directory that holds all public client certificates, i.e. their -// public keys. The certificates must be in zcert_save () format. To cover -// all domains, use "*". You can add and remove certificates in that -// directory at any time. To allow all client keys without checking, specify -// CURVE_ALLOW_ANY for the location. -CZMQ_EXPORT void - zauth_configure_curve (zauth_t *self, const char *domain, const char *location); - -// Configure GSSAPI authentication for a given domain. GSSAPI authentication -// uses an underlying mechanism (usually Kerberos) to establish a secure -// context and perform mutual authentication. To cover all domains, use "*". -CZMQ_EXPORT void - zauth_configure_gssapi (zauth_t *self, char *domain); - -// Enable verbose tracing of commands and activity -CZMQ_EXPORT void - zauth_set_verbose (zauth_t *self, bool verbose); - -// Selftest -CZMQ_EXPORT void - zauth_v2_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zbeacon.h b/phonelibs/zmq/aarch64/include/zbeacon.h deleted file mode 100644 index 78917e9577..0000000000 --- a/phonelibs/zmq/aarch64/include/zbeacon.h +++ /dev/null @@ -1,86 +0,0 @@ -/* ========================================================================= - zbeacon - LAN discovery and presence - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZBEACON_H_INCLUDED__ -#define __ZBEACON_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// Create new zbeacon actor instance: -// -// zactor_t *beacon = zactor_new (zbeacon, NULL); -// -// Destroy zbeacon instance: -// -// zactor_destroy (&beacon); -// -// Enable verbose logging of commands and activity: -// -// zstr_send (beacon, "VERBOSE"); -// -// Configure beacon to run on specified UDP port, and return the name of -// the host, which can be used as endpoint for incoming connections. To -// force the beacon to operate on a given interface, set the environment -// variable ZSYS_INTERFACE, or call zsys_set_interface() before creating -// the beacon. If the system does not support UDP broadcasts (lacking a -// workable interface), returns an empty hostname: -// -// // Pictures: 's' = C string, 'i' = int -// zsock_send (beacon, "si", "CONFIGURE", port_number); -// char *hostname = zstr_recv (beacon); -// -// Start broadcasting a beacon at a specified interval in msec. The beacon -// data can be at most UDP_FRAME_MAX bytes; this constant is defined in -// zsys.h to be 255: -// -// // Pictures: 'b' = byte * data + size_t size -// zsock_send (beacon, "sbi", "PUBLISH", data, size, interval); -// -// Stop broadcasting the beacon: -// -// zstr_sendx (beacon, "SILENCE", NULL); -// -// Start listening to beacons from peers. The filter is used to do a prefix -// match on received beacons, to remove junk. Note that any received data -// that is identical to our broadcast beacon_data is discarded in any case. -// If the filter size is zero, we get all peer beacons: -// -// zsock_send (beacon, "sb", "SUBSCRIBE", filter_data, filter_size); -// -// Stop listening to other peers -// -// zstr_sendx (beacon, "UNSUBSCRIBE", NULL); -// -// Receive next beacon from a peer. Received beacons are always a 2-frame -// message containing the ipaddress of the sender, and then the binary -// beacon data as published by the sender: -// -// zmsg_t *msg = zmsg_recv (beacon); -// -// This is the zbeacon constructor as a zactor_fn: -CZMQ_EXPORT void - zbeacon (zsock_t *pipe, void *unused); - -// Self test of this class -CZMQ_EXPORT void - zbeacon_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zbeacon_v2.h b/phonelibs/zmq/aarch64/include/zbeacon_v2.h deleted file mode 100644 index 8e8f3b4cde..0000000000 --- a/phonelibs/zmq/aarch64/include/zbeacon_v2.h +++ /dev/null @@ -1,75 +0,0 @@ -/* ========================================================================= - zbeacon - LAN discovery and presence (deprecated) - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZBEACON_V2_H_INCLUDED__ -#define __ZBEACON_V2_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// Create a new beacon on a certain UDP port. If the system does not -// support UDP broadcasts (lacking a useful interface), returns NULL. -// To force the beacon to operate on a given port, set the environment -// variable ZSYS_INTERFACE, or call zsys_set_interface() beforehand. -// If you are using the new zsock API then pass NULL as the ctx here. -CZMQ_EXPORT zbeacon_t * - zbeacon_new (zctx_t *ctx, int port_nbr); - -// Destroy a beacon -CZMQ_EXPORT void - zbeacon_destroy (zbeacon_t **self_p); - -// Return our own IP address as printable string -CZMQ_EXPORT char * - zbeacon_hostname (zbeacon_t *self); - -// Set broadcast interval in milliseconds (default is 1000 msec) -CZMQ_EXPORT void - zbeacon_set_interval (zbeacon_t *self, int interval); - -// Filter out any beacon that looks exactly like ours -CZMQ_EXPORT void - zbeacon_noecho (zbeacon_t *self); - -// Start broadcasting beacon to peers at the specified interval -CZMQ_EXPORT void - zbeacon_publish (zbeacon_t *self, byte *transmit, size_t size); - -// Stop broadcasting beacons -CZMQ_EXPORT void - zbeacon_silence (zbeacon_t *self); - -// Start listening to other peers; zero-sized filter means get everything -CZMQ_EXPORT void - zbeacon_subscribe (zbeacon_t *self, byte *filter, size_t size); - -// Stop listening to other peers -CZMQ_EXPORT void - zbeacon_unsubscribe (zbeacon_t *self); - -// Get beacon ZeroMQ socket, for polling or receiving messages -CZMQ_EXPORT void * - zbeacon_socket (zbeacon_t *self); - -// Self test of this class -CZMQ_EXPORT void - zbeacon_v2_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zcert.h b/phonelibs/zmq/aarch64/include/zcert.h deleted file mode 100644 index 495b579cda..0000000000 --- a/phonelibs/zmq/aarch64/include/zcert.h +++ /dev/null @@ -1,139 +0,0 @@ -/* ========================================================================= - zcert - work with CURVE security certificates - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZCERT_H_INCLUDED__ -#define __ZCERT_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zcert.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// This class has legacy methods, which will be removed over time. You -// should not use them, and migrate any code that is still using them. -// Create and initialize a new certificate in memory -CZMQ_EXPORT zcert_t * - zcert_new (void); - -// Accepts public/secret key pair from caller -CZMQ_EXPORT zcert_t * - zcert_new_from (const byte *public_key, const byte *secret_key); - -// Load certificate from file -CZMQ_EXPORT zcert_t * - zcert_load (const char *filename); - -// Destroy a certificate in memory -CZMQ_EXPORT void - zcert_destroy (zcert_t **self_p); - -// Return public part of key pair as 32-byte binary string -CZMQ_EXPORT const byte * - zcert_public_key (zcert_t *self); - -// Return secret part of key pair as 32-byte binary string -CZMQ_EXPORT const byte * - zcert_secret_key (zcert_t *self); - -// Return public part of key pair as Z85 armored string -CZMQ_EXPORT const char * - zcert_public_txt (zcert_t *self); - -// Return secret part of key pair as Z85 armored string -CZMQ_EXPORT const char * - zcert_secret_txt (zcert_t *self); - -// Set certificate metadata from formatted string. -CZMQ_EXPORT void - zcert_set_meta (zcert_t *self, const char *name, const char *format, ...); - -// Get metadata value from certificate; if the metadata value doesn't -// exist, returns NULL. -CZMQ_EXPORT const char * - zcert_meta (zcert_t *self, const char *name); - -// Get list of metadata fields from certificate. Caller is responsible for -// destroying list. Caller should not modify the values of list items. -CZMQ_EXPORT zlist_t * - zcert_meta_keys (zcert_t *self); - -// Save full certificate (public + secret) to file for persistent storage -// This creates one public file and one secret file (filename + "_secret"). -CZMQ_EXPORT int - zcert_save (zcert_t *self, const char *filename); - -// Save public certificate only to file for persistent storage -CZMQ_EXPORT int - zcert_save_public (zcert_t *self, const char *filename); - -// Save secret certificate only to file for persistent storage -CZMQ_EXPORT int - zcert_save_secret (zcert_t *self, const char *filename); - -// Apply certificate to socket, i.e. use for CURVE security on socket. -// If certificate was loaded from public file, the secret key will be -// undefined, and this certificate will not work successfully. -CZMQ_EXPORT void - zcert_apply (zcert_t *self, void *socket); - -// Return copy of certificate; if certificate is NULL or we exhausted -// heap memory, returns NULL. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zcert_t * - zcert_dup (zcert_t *self); - -// Return true if two certificates have the same keys -CZMQ_EXPORT bool - zcert_eq (zcert_t *self, zcert_t *compare); - -// Print certificate contents to stdout -CZMQ_EXPORT void - zcert_print (zcert_t *self); - -// *** Deprecated method, slated for removal: avoid using it *** -// Print certificate contents to open stream. This method is deprecated -// and you should use the print method. -CZMQ_EXPORT void - zcert_fprint (zcert_t *self, FILE *file); - -// Self test of this class -CZMQ_EXPORT void - zcert_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Unset certificate metadata. -CZMQ_EXPORT void - zcert_unset_meta (zcert_t *self, const char *name); - -#endif // CZMQ_BUILD_DRAFT_API -// @ignore -CZMQ_EXPORT void - zcert_set_meta (zcert_t *self, const char *name, const char *format, ...) CHECK_PRINTF (3); -// @end - - -#ifdef __cplusplus -} -#endif - -// Deprecated method aliases -#define zcert_dump(s) zcert_print(s) - -#endif diff --git a/phonelibs/zmq/aarch64/include/zcertstore.h b/phonelibs/zmq/aarch64/include/zcertstore.h deleted file mode 100644 index c7f93c5a7d..0000000000 --- a/phonelibs/zmq/aarch64/include/zcertstore.h +++ /dev/null @@ -1,100 +0,0 @@ -/* ========================================================================= - zcertstore - work with CURVE security certificate stores - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZCERTSTORE_H_INCLUDED__ -#define __ZCERTSTORE_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zcertstore.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// This class has legacy methods, which will be removed over time. You -// should not use them, and migrate any code that is still using them. -// Create a new certificate store from a disk directory, loading and -// indexing all certificates in that location. The directory itself may be -// absent, and created later, or modified at any time. The certificate store -// is automatically refreshed on any zcertstore_lookup() call. If the -// location is specified as NULL, creates a pure-memory store, which you -// can work with by inserting certificates at runtime. -CZMQ_EXPORT zcertstore_t * - zcertstore_new (const char *location); - -// Destroy a certificate store object in memory. Does not affect anything -// stored on disk. -CZMQ_EXPORT void - zcertstore_destroy (zcertstore_t **self_p); - -// Look up certificate by public key, returns zcert_t object if found, -// else returns NULL. The public key is provided in Z85 text format. -CZMQ_EXPORT zcert_t * - zcertstore_lookup (zcertstore_t *self, const char *public_key); - -// Insert certificate into certificate store in memory. Note that this -// does not save the certificate to disk. To do that, use zcert_save() -// directly on the certificate. Takes ownership of zcert_t object. -CZMQ_EXPORT void - zcertstore_insert (zcertstore_t *self, zcert_t **cert_p); - -// Print list of certificates in store to logging facility -CZMQ_EXPORT void - zcertstore_print (zcertstore_t *self); - -// *** Deprecated method, slated for removal: avoid using it *** -// Print list of certificates in store to open stream. This method is -// deprecated, and you should use the print method. -CZMQ_EXPORT void - zcertstore_fprint (zcertstore_t *self, FILE *file); - -// Self test of this class -CZMQ_EXPORT void - zcertstore_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// Loaders retrieve certificates from an arbitrary source. -typedef void (zcertstore_loader) ( - zcertstore_t *self); - -// Destructor for loader state. -typedef void (zcertstore_destructor) ( - void **self_p); - -// *** Draft method, for development use, may change without warning *** -// Override the default disk loader with a custom loader fn. -CZMQ_EXPORT void - zcertstore_set_loader (zcertstore_t *self, zcertstore_loader loader, zcertstore_destructor destructor, void *state); - -// *** Draft method, for development use, may change without warning *** -// Empty certificate hashtable. This wrapper exists to be friendly to bindings, -// which don't usually have access to struct internals. -CZMQ_EXPORT void - zcertstore_empty (zcertstore_t *self); - -#endif // CZMQ_BUILD_DRAFT_API -// @end - - -#ifdef __cplusplus -} -#endif - -// Deprecated method aliases -#define zcertstore_dump(s) zcertstore_print(s) - -#endif diff --git a/phonelibs/zmq/aarch64/include/zchunk.h b/phonelibs/zmq/aarch64/include/zchunk.h deleted file mode 100644 index 56f29b161a..0000000000 --- a/phonelibs/zmq/aarch64/include/zchunk.h +++ /dev/null @@ -1,163 +0,0 @@ -/* ========================================================================= - zchunk - work with memory chunks - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZCHUNK_H_INCLUDED__ -#define __ZCHUNK_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zchunk.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Create a new chunk of the specified size. If you specify the data, it -// is copied into the chunk. If you do not specify the data, the chunk is -// allocated and left empty, and you can then add data using zchunk_append. -CZMQ_EXPORT zchunk_t * - zchunk_new (const void *data, size_t size); - -// Destroy a chunk -CZMQ_EXPORT void - zchunk_destroy (zchunk_t **self_p); - -// Resizes chunk max_size as requested; chunk_cur size is set to zero -CZMQ_EXPORT void - zchunk_resize (zchunk_t *self, size_t size); - -// Return chunk cur size -CZMQ_EXPORT size_t - zchunk_size (zchunk_t *self); - -// Return chunk max size -CZMQ_EXPORT size_t - zchunk_max_size (zchunk_t *self); - -// Return chunk data -CZMQ_EXPORT byte * - zchunk_data (zchunk_t *self); - -// Set chunk data from user-supplied data; truncate if too large. Data may -// be null. Returns actual size of chunk -CZMQ_EXPORT size_t - zchunk_set (zchunk_t *self, const void *data, size_t size); - -// Fill chunk data from user-supplied octet -CZMQ_EXPORT size_t - zchunk_fill (zchunk_t *self, byte filler, size_t size); - -// Append user-supplied data to chunk, return resulting chunk size. If the -// data would exceeded the available space, it is truncated. If you want to -// grow the chunk to accommodate new data, use the zchunk_extend method. -CZMQ_EXPORT size_t - zchunk_append (zchunk_t *self, const void *data, size_t size); - -// Append user-supplied data to chunk, return resulting chunk size. If the -// data would exceeded the available space, the chunk grows in size. -CZMQ_EXPORT size_t - zchunk_extend (zchunk_t *self, const void *data, size_t size); - -// Copy as much data from 'source' into the chunk as possible; returns the -// new size of chunk. If all data from 'source' is used, returns exhausted -// on the source chunk. Source can be consumed as many times as needed until -// it is exhausted. If source was already exhausted, does not change chunk. -CZMQ_EXPORT size_t - zchunk_consume (zchunk_t *self, zchunk_t *source); - -// Returns true if the chunk was exhausted by consume methods, or if the -// chunk has a size of zero. -CZMQ_EXPORT bool - zchunk_exhausted (zchunk_t *self); - -// Read chunk from an open file descriptor -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zchunk_t * - zchunk_read (FILE *handle, size_t bytes); - -// Write chunk to an open file descriptor -CZMQ_EXPORT int - zchunk_write (zchunk_t *self, FILE *handle); - -// Try to slurp an entire file into a chunk. Will read up to maxsize of -// the file. If maxsize is 0, will attempt to read the entire file and -// fail with an assertion if that cannot fit into memory. Returns a new -// chunk containing the file data, or NULL if the file could not be read. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zchunk_t * - zchunk_slurp (const char *filename, size_t maxsize); - -// Create copy of chunk, as new chunk object. Returns a fresh zchunk_t -// object, or null if there was not enough heap memory. If chunk is null, -// returns null. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zchunk_t * - zchunk_dup (zchunk_t *self); - -// Return chunk data encoded as printable hex string. Caller must free -// string when finished with it. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zchunk_strhex (zchunk_t *self); - -// Return chunk data copied into freshly allocated string -// Caller must free string when finished with it. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zchunk_strdup (zchunk_t *self); - -// Return TRUE if chunk body is equal to string, excluding terminator -CZMQ_EXPORT bool - zchunk_streq (zchunk_t *self, const char *string); - -// Transform zchunk into a zframe that can be sent in a message. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zchunk_pack (zchunk_t *self); - -// Transform a zframe into a zchunk. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zchunk_t * - zchunk_unpack (zframe_t *frame); - -// Calculate SHA1 digest for chunk, using zdigest class. -CZMQ_EXPORT const char * - zchunk_digest (zchunk_t *self); - -// Dump chunk to FILE stream, for debugging and tracing. -CZMQ_EXPORT void - zchunk_fprint (zchunk_t *self, FILE *file); - -// Dump message to stderr, for debugging and tracing. -// See zchunk_fprint for details -CZMQ_EXPORT void - zchunk_print (zchunk_t *self); - -// Probe the supplied object, and report if it looks like a zchunk_t. -CZMQ_EXPORT bool - zchunk_is (void *self); - -// Self test of this class. -CZMQ_EXPORT void - zchunk_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/phonelibs/zmq/aarch64/include/zclock.h b/phonelibs/zmq/aarch64/include/zclock.h deleted file mode 100644 index eb064162c4..0000000000 --- a/phonelibs/zmq/aarch64/include/zclock.h +++ /dev/null @@ -1,73 +0,0 @@ -/* ========================================================================= - zclock - millisecond clocks and delays - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZCLOCK_H_INCLUDED__ -#define __ZCLOCK_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zclock.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Sleep for a number of milliseconds -CZMQ_EXPORT void - zclock_sleep (int msecs); - -// Return current system clock as milliseconds. Note that this clock can -// jump backwards (if the system clock is changed) so is unsafe to use for -// timers and time offsets. Use zclock_mono for that instead. -CZMQ_EXPORT int64_t - zclock_time (void); - -// Return current monotonic clock in milliseconds. Use this when you compute -// time offsets. The monotonic clock is not affected by system changes and -// so will never be reset backwards, unlike a system clock. -CZMQ_EXPORT int64_t - zclock_mono (void); - -// Return current monotonic clock in microseconds. Use this when you compute -// time offsets. The monotonic clock is not affected by system changes and -// so will never be reset backwards, unlike a system clock. -CZMQ_EXPORT int64_t - zclock_usecs (void); - -// Return formatted date/time as fresh string. Free using zstr_free(). -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zclock_timestr (void); - -// Self test of this class. -CZMQ_EXPORT void - zclock_test (bool verbose); - -// @end - - -// DEPRECATED in favor of zsys logging, see issue #519 -// Print formatted string to stdout, prefixed by date/time and -// terminated with a newline. -CZMQ_EXPORT void - zclock_log (const char *format, ...); - -// Compiler hints -CZMQ_EXPORT void zclock_log (const char *format, ...) CHECK_PRINTF (1); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zconfig.h b/phonelibs/zmq/aarch64/include/zconfig.h deleted file mode 100644 index 4ec4e1c81f..0000000000 --- a/phonelibs/zmq/aarch64/include/zconfig.h +++ /dev/null @@ -1,194 +0,0 @@ -/* ========================================================================= - zconfig - work with config files written in rfc.zeromq.org/spec:4/ZPL. - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZCONFIG_H_INCLUDED__ -#define __ZCONFIG_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zconfig.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// -typedef int (zconfig_fct) ( - zconfig_t *self, void *arg, int level); - -// Create new config item -CZMQ_EXPORT zconfig_t * - zconfig_new (const char *name, zconfig_t *parent); - -// Load a config tree from a specified ZPL text file; returns a zconfig_t -// reference for the root, if the file exists and is readable. Returns NULL -// if the file does not exist. -CZMQ_EXPORT zconfig_t * - zconfig_load (const char *filename); - -// Equivalent to zconfig_load, taking a format string instead of a fixed -// filename. -CZMQ_EXPORT zconfig_t * - zconfig_loadf (const char *format, ...); - -// Destroy a config item and all its children -CZMQ_EXPORT void - zconfig_destroy (zconfig_t **self_p); - -// Return name of config item -CZMQ_EXPORT char * - zconfig_name (zconfig_t *self); - -// Return value of config item -CZMQ_EXPORT char * - zconfig_value (zconfig_t *self); - -// Insert or update configuration key with value -CZMQ_EXPORT void - zconfig_put (zconfig_t *self, const char *path, const char *value); - -// Equivalent to zconfig_put, accepting a format specifier and variable -// argument list, instead of a single string value. -CZMQ_EXPORT void - zconfig_putf (zconfig_t *self, const char *path, const char *format, ...); - -// Get value for config item into a string value; leading slash is optional -// and ignored. -CZMQ_EXPORT char * - zconfig_get (zconfig_t *self, const char *path, const char *default_value); - -// Set config item name, name may be NULL -CZMQ_EXPORT void - zconfig_set_name (zconfig_t *self, const char *name); - -// Set new value for config item. The new value may be a string, a printf -// format, or NULL. Note that if string may possibly contain '%', or if it -// comes from an insecure source, you must use '%s' as the format, followed -// by the string. -CZMQ_EXPORT void - zconfig_set_value (zconfig_t *self, const char *format, ...); - -// Find our first child, if any -CZMQ_EXPORT zconfig_t * - zconfig_child (zconfig_t *self); - -// Find our first sibling, if any -CZMQ_EXPORT zconfig_t * - zconfig_next (zconfig_t *self); - -// Find a config item along a path; leading slash is optional and ignored. -CZMQ_EXPORT zconfig_t * - zconfig_locate (zconfig_t *self, const char *path); - -// Locate the last config item at a specified depth -CZMQ_EXPORT zconfig_t * - zconfig_at_depth (zconfig_t *self, int level); - -// Execute a callback for each config item in the tree; returns zero if -// successful, else -1. -CZMQ_EXPORT int - zconfig_execute (zconfig_t *self, zconfig_fct handler, void *arg); - -// Add comment to config item before saving to disk. You can add as many -// comment lines as you like. If you use a null format, all comments are -// deleted. -CZMQ_EXPORT void - zconfig_set_comment (zconfig_t *self, const char *format, ...); - -// Return comments of config item, as zlist. -CZMQ_EXPORT zlist_t * - zconfig_comments (zconfig_t *self); - -// Save a config tree to a specified ZPL text file, where a filename -// "-" means dump to standard output. -CZMQ_EXPORT int - zconfig_save (zconfig_t *self, const char *filename); - -// Equivalent to zconfig_save, taking a format string instead of a fixed -// filename. -CZMQ_EXPORT int - zconfig_savef (zconfig_t *self, const char *format, ...); - -// Report filename used during zconfig_load, or NULL if none -CZMQ_EXPORT const char * - zconfig_filename (zconfig_t *self); - -// Reload config tree from same file that it was previously loaded from. -// Returns 0 if OK, -1 if there was an error (and then does not change -// existing data). -CZMQ_EXPORT int - zconfig_reload (zconfig_t **self_p); - -// Load a config tree from a memory chunk -CZMQ_EXPORT zconfig_t * - zconfig_chunk_load (zchunk_t *chunk); - -// Save a config tree to a new memory chunk -CZMQ_EXPORT zchunk_t * - zconfig_chunk_save (zconfig_t *self); - -// Load a config tree from a null-terminated string -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zconfig_t * - zconfig_str_load (const char *string); - -// Save a config tree to a new null terminated string -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zconfig_str_save (zconfig_t *self); - -// Return true if a configuration tree was loaded from a file and that -// file has changed in since the tree was loaded. -CZMQ_EXPORT bool - zconfig_has_changed (zconfig_t *self); - -// Print the config file to open stream -CZMQ_EXPORT void - zconfig_fprint (zconfig_t *self, FILE *file); - -// Print properties of object -CZMQ_EXPORT void - zconfig_print (zconfig_t *self); - -// Self test of this class -CZMQ_EXPORT void - zconfig_test (bool verbose); - -// @ignore -CZMQ_EXPORT void - zconfig_putf (zconfig_t *self, const char *path, const char *format, ...) CHECK_PRINTF (3); -CZMQ_EXPORT void - zconfig_set_value (zconfig_t *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT void - zconfig_set_comment (zconfig_t *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int - zconfig_savef (zconfig_t *self, const char *format, ...) CHECK_PRINTF (2); -// @end - -// Self test of this class -CZMQ_EXPORT void - zconfig_test (bool verbose); - -// Compiler hints -CZMQ_EXPORT void zconfig_set_value (zconfig_t *self, const char *format, ...) CHECK_PRINTF (2); - -#ifdef __cplusplus -} -#endif - -// Deprecated method aliases -#define zconfig_dump(s) zconfig_print(s) -#define zconfig_resolve(s,p,d) zconfig_get((s),(p),(d)) - -#endif diff --git a/phonelibs/zmq/aarch64/include/zctx.h b/phonelibs/zmq/aarch64/include/zctx.h deleted file mode 100644 index 88898410dc..0000000000 --- a/phonelibs/zmq/aarch64/include/zctx.h +++ /dev/null @@ -1,107 +0,0 @@ -/* ========================================================================= - zctx - working with 0MQ contexts - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZCTX_H_INCLUDED__ -#define __ZCTX_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - - -// @interface -// Create new context, returns context object, replaces zmq_init -CZMQ_EXPORT zctx_t * - zctx_new (void); - -// Destroy context and all sockets in it, replaces zmq_term -CZMQ_EXPORT void - zctx_destroy (zctx_t **self_p); - -// Create new shadow context, returns context object -CZMQ_EXPORT zctx_t * - zctx_shadow (zctx_t *self); -// @end - -// Create a new context by shadowing a plain zmq context -CZMQ_EXPORT zctx_t * -zctx_shadow_zmq_ctx (void *zmqctx); - -// @interface -// Raise default I/O threads from 1, for crazy heavy applications -// The rule of thumb is one I/O thread per gigabyte of traffic in -// or out. Call this method before creating any sockets on the context, -// or calling zctx_shadow, or the setting will have no effect. -CZMQ_EXPORT void - zctx_set_iothreads (zctx_t *self, int iothreads); - -// Set msecs to flush sockets when closing them, see the ZMQ_LINGER -// man page section for more details. By default, set to zero, so -// any in-transit messages are discarded when you destroy a socket or -// a context. -CZMQ_EXPORT void - zctx_set_linger (zctx_t *self, int linger); - -// Set initial high-water mark for inter-thread pipe sockets. Note that -// this setting is separate from the default for normal sockets. You -// should change the default for pipe sockets *with care*. Too low values -// will cause blocked threads, and an infinite setting can cause memory -// exhaustion. The default, no matter the underlying ZeroMQ version, is -// 1,000. -CZMQ_EXPORT void - zctx_set_pipehwm (zctx_t *self, int pipehwm); - -// Set initial send HWM for all new normal sockets created in context. -// You can set this per-socket after the socket is created. -// The default, no matter the underlying ZeroMQ version, is 1,000. -CZMQ_EXPORT void - zctx_set_sndhwm (zctx_t *self, int sndhwm); - -// Set initial receive HWM for all new normal sockets created in context. -// You can set this per-socket after the socket is created. -// The default, no matter the underlying ZeroMQ version, is 1,000. -CZMQ_EXPORT void - zctx_set_rcvhwm (zctx_t *self, int rcvhwm); - -// Return low-level 0MQ context object, will be NULL before first socket -// is created. Use with care. -CZMQ_EXPORT void * - zctx_underlying (zctx_t *self); - -// Self test of this class -CZMQ_EXPORT void - zctx_test (bool verbose); -// @end - -// Create socket within this context, for CZMQ use only -void * - zctx__socket_new (zctx_t *self, int type); - -// Create pipe socket within this context, for CZMQ use only -void * - zctx__socket_pipe (zctx_t *self); - -// Destroy socket within this context, for CZMQ use only -void - zctx__socket_destroy (zctx_t *self, void *socket); - -// Initialize the low-level 0MQ context object, for CZMQ use only -void - zctx__initialize_underlying(zctx_t *self); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zdigest.h b/phonelibs/zmq/aarch64/include/zdigest.h deleted file mode 100644 index def9e86053..0000000000 --- a/phonelibs/zmq/aarch64/include/zdigest.h +++ /dev/null @@ -1,65 +0,0 @@ -/* ========================================================================= - zdigest - provides hashing functions (SHA-1 at present) - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZDIGEST_H_INCLUDED__ -#define __ZDIGEST_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zdigest.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Constructor - creates new digest object, which you use to build up a -// digest by repeatedly calling zdigest_update() on chunks of data. -CZMQ_EXPORT zdigest_t * - zdigest_new (void); - -// Destroy a digest object -CZMQ_EXPORT void - zdigest_destroy (zdigest_t **self_p); - -// Add buffer into digest calculation -CZMQ_EXPORT void - zdigest_update (zdigest_t *self, const byte *buffer, size_t length); - -// Return final digest hash data. If built without crypto support, -// returns NULL. -CZMQ_EXPORT const byte * - zdigest_data (zdigest_t *self); - -// Return final digest hash size -CZMQ_EXPORT size_t - zdigest_size (zdigest_t *self); - -// Return digest as printable hex string; caller should not modify nor -// free this string. After calling this, you may not use zdigest_update() -// on the same digest. If built without crypto support, returns NULL. -CZMQ_EXPORT char * - zdigest_string (zdigest_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zdigest_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zdir.h b/phonelibs/zmq/aarch64/include/zdir.h deleted file mode 100644 index 6c5551b57e..0000000000 --- a/phonelibs/zmq/aarch64/include/zdir.h +++ /dev/null @@ -1,149 +0,0 @@ -/* ========================================================================= - zdir - work with file-system directories - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZDIR_H_INCLUDED__ -#define __ZDIR_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zdir.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Create a new directory item that loads in the full tree of the specified -// path, optionally located under some parent path. If parent is "-", then -// loads only the top-level directory, and does not use parent as a path. -CZMQ_EXPORT zdir_t * - zdir_new (const char *path, const char *parent); - -// Destroy a directory tree and all children it contains. -CZMQ_EXPORT void - zdir_destroy (zdir_t **self_p); - -// Return directory path -CZMQ_EXPORT const char * - zdir_path (zdir_t *self); - -// Return last modification time for directory. -CZMQ_EXPORT time_t - zdir_modified (zdir_t *self); - -// Return total hierarchy size, in bytes of data contained in all files -// in the directory tree. -CZMQ_EXPORT off_t - zdir_cursize (zdir_t *self); - -// Return directory count -CZMQ_EXPORT size_t - zdir_count (zdir_t *self); - -// Returns a sorted list of zfile objects; Each entry in the list is a pointer -// to a zfile_t item already allocated in the zdir tree. Do not destroy the -// original zdir tree until you are done with this list. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlist_t * - zdir_list (zdir_t *self); - -// Remove directory, optionally including all files that it contains, at -// all levels. If force is false, will only remove the directory if empty. -// If force is true, will remove all files and all subdirectories. -CZMQ_EXPORT void - zdir_remove (zdir_t *self, bool force); - -// Calculate differences between two versions of a directory tree. -// Returns a list of zdir_patch_t patches. Either older or newer may -// be null, indicating the directory is empty/absent. If alias is set, -// generates virtual filename (minus path, plus alias). -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlist_t * - zdir_diff (zdir_t *older, zdir_t *newer, const char *alias); - -// Return full contents of directory as a zdir_patch list. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlist_t * - zdir_resync (zdir_t *self, const char *alias); - -// Load directory cache; returns a hash table containing the SHA-1 digests -// of every file in the tree. The cache is saved between runs in .cache. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zhash_t * - zdir_cache (zdir_t *self); - -// Print contents of directory to open stream -CZMQ_EXPORT void - zdir_fprint (zdir_t *self, FILE *file, int indent); - -// Print contents of directory to stdout -CZMQ_EXPORT void - zdir_print (zdir_t *self, int indent); - -// Create a new zdir_watch actor instance: -// -// zactor_t *watch = zactor_new (zdir_watch, NULL); -// -// Destroy zdir_watch instance: -// -// zactor_destroy (&watch); -// -// Enable verbose logging of commands and activity: -// -// zstr_send (watch, "VERBOSE"); -// -// Subscribe to changes to a directory path: -// -// zsock_send (watch, "ss", "SUBSCRIBE", "directory_path"); -// -// Unsubscribe from changes to a directory path: -// -// zsock_send (watch, "ss", "UNSUBSCRIBE", "directory_path"); -// -// Receive directory changes: -// zsock_recv (watch, "sp", &path, &patches); -// -// // Delete the received data. -// free (path); -// zlist_destroy (&patches); -CZMQ_EXPORT void - zdir_watch (zsock_t *pipe, void *unused); - -// Self test of this class. -CZMQ_EXPORT void - zdir_test (bool verbose); - -// @end - - -// Returns a sorted array of zfile objects; returns a single block of memory, -// that you destroy by calling zstr_free(). Each entry in the array is a pointer -// to a zfile_t item already allocated in the zdir tree. The array ends with -// a null pointer. Do not destroy the original zdir tree until you are done -// with this array. -CZMQ_EXPORT zfile_t ** - zdir_flatten (zdir_t *self); - -// Free a provided string, and nullify the parent pointer. Safe to call on -// a null pointer. -CZMQ_EXPORT void - zdir_flatten_free (zfile_t ***files_p); - -#ifdef __cplusplus -} -#endif - -// Deprecated method aliases -#define zdir_dump(s,i) zdir_print(s,i) - -#endif diff --git a/phonelibs/zmq/aarch64/include/zdir_patch.h b/phonelibs/zmq/aarch64/include/zdir_patch.h deleted file mode 100644 index 8d15b9aeb4..0000000000 --- a/phonelibs/zmq/aarch64/include/zdir_patch.h +++ /dev/null @@ -1,82 +0,0 @@ -/* ========================================================================= - zdir_patch - work with directory patches - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZDIR_PATCH_H_INCLUDED__ -#define __ZDIR_PATCH_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// un-namespaced enumeration values -#define patch_create ZDIR_PATCH_CREATE -#define patch_delete ZDIR_PATCH_DELETE - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zdir_patch.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -#define ZDIR_PATCH_CREATE 1 // Creates a new file -#define ZDIR_PATCH_DELETE 2 // Delete a file - -// Create new patch -CZMQ_EXPORT zdir_patch_t * - zdir_patch_new (const char *path, zfile_t *file, int op, const char *alias); - -// Destroy a patch -CZMQ_EXPORT void - zdir_patch_destroy (zdir_patch_t **self_p); - -// Create copy of a patch. If the patch is null, or memory was exhausted, -// returns null. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zdir_patch_t * - zdir_patch_dup (zdir_patch_t *self); - -// Return patch file directory path -CZMQ_EXPORT const char * - zdir_patch_path (zdir_patch_t *self); - -// Return patch file item -CZMQ_EXPORT zfile_t * - zdir_patch_file (zdir_patch_t *self); - -// Return operation -CZMQ_EXPORT int - zdir_patch_op (zdir_patch_t *self); - -// Return patch virtual file path -CZMQ_EXPORT const char * - zdir_patch_vpath (zdir_patch_t *self); - -// Calculate hash digest for file (create only) -CZMQ_EXPORT void - zdir_patch_digest_set (zdir_patch_t *self); - -// Return hash digest for patch file -CZMQ_EXPORT const char * - zdir_patch_digest (zdir_patch_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zdir_patch_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zfile.h b/phonelibs/zmq/aarch64/include/zfile.h deleted file mode 100644 index 75c35774b9..0000000000 --- a/phonelibs/zmq/aarch64/include/zfile.h +++ /dev/null @@ -1,177 +0,0 @@ -/* ========================================================================= - zfile - helper functions for working with files. - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZFILE_H_INCLUDED__ -#define __ZFILE_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zfile.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// If file exists, populates properties. CZMQ supports portable symbolic -// links, which are files with the extension ".ln". A symbolic link is a -// text file containing one line, the filename of a target file. Reading -// data from the symbolic link actually reads from the target file. Path -// may be NULL, in which case it is not used. -CZMQ_EXPORT zfile_t * - zfile_new (const char *path, const char *name); - -// Destroy a file item -CZMQ_EXPORT void - zfile_destroy (zfile_t **self_p); - -// Duplicate a file item, returns a newly constructed item. If the file -// is null, or memory was exhausted, returns null. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zfile_t * - zfile_dup (zfile_t *self); - -// Return file name, remove path if provided -CZMQ_EXPORT const char * - zfile_filename (zfile_t *self, const char *path); - -// Refresh file properties from disk; this is not done automatically -// on access methods, otherwise it is not possible to compare directory -// snapshots. -CZMQ_EXPORT void - zfile_restat (zfile_t *self); - -// Return when the file was last modified. If you want this to reflect the -// current situation, call zfile_restat before checking this property. -CZMQ_EXPORT time_t - zfile_modified (zfile_t *self); - -// Return the last-known size of the file. If you want this to reflect the -// current situation, call zfile_restat before checking this property. -CZMQ_EXPORT off_t - zfile_cursize (zfile_t *self); - -// Return true if the file is a directory. If you want this to reflect -// any external changes, call zfile_restat before checking this property. -CZMQ_EXPORT bool - zfile_is_directory (zfile_t *self); - -// Return true if the file is a regular file. If you want this to reflect -// any external changes, call zfile_restat before checking this property. -CZMQ_EXPORT bool - zfile_is_regular (zfile_t *self); - -// Return true if the file is readable by this process. If you want this to -// reflect any external changes, call zfile_restat before checking this -// property. -CZMQ_EXPORT bool - zfile_is_readable (zfile_t *self); - -// Return true if the file is writeable by this process. If you want this -// to reflect any external changes, call zfile_restat before checking this -// property. -CZMQ_EXPORT bool - zfile_is_writeable (zfile_t *self); - -// Check if file has stopped changing and can be safely processed. -// Updates the file statistics from disk at every call. -CZMQ_EXPORT bool - zfile_is_stable (zfile_t *self); - -// Return true if the file was changed on disk since the zfile_t object -// was created, or the last zfile_restat() call made on it. -CZMQ_EXPORT bool - zfile_has_changed (zfile_t *self); - -// Remove the file from disk -CZMQ_EXPORT void - zfile_remove (zfile_t *self); - -// Open file for reading -// Returns 0 if OK, -1 if not found or not accessible -CZMQ_EXPORT int - zfile_input (zfile_t *self); - -// Open file for writing, creating directory if needed -// File is created if necessary; chunks can be written to file at any -// location. Returns 0 if OK, -1 if error. -CZMQ_EXPORT int - zfile_output (zfile_t *self); - -// Read chunk from file at specified position. If this was the last chunk, -// sets the eof property. Returns a null chunk in case of error. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zchunk_t * - zfile_read (zfile_t *self, size_t bytes, off_t offset); - -// Returns true if zfile_read() just read the last chunk in the file. -CZMQ_EXPORT bool - zfile_eof (zfile_t *self); - -// Write chunk to file at specified position -// Return 0 if OK, else -1 -CZMQ_EXPORT int - zfile_write (zfile_t *self, zchunk_t *chunk, off_t offset); - -// Read next line of text from file. Returns a pointer to the text line, -// or NULL if there was nothing more to read from the file. -CZMQ_EXPORT const char * - zfile_readln (zfile_t *self); - -// Close file, if open -CZMQ_EXPORT void - zfile_close (zfile_t *self); - -// Return file handle, if opened -CZMQ_EXPORT FILE * - zfile_handle (zfile_t *self); - -// Calculate SHA1 digest for file, using zdigest class. -CZMQ_EXPORT const char * - zfile_digest (zfile_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zfile_test (bool verbose); - -// @end - - -// @interface -// These methods are deprecated, and now moved to zsys class. -CZMQ_EXPORT bool - zfile_exists (const char *filename); -CZMQ_EXPORT ssize_t - zfile_size (const char *filename); -CZMQ_EXPORT mode_t - zfile_mode (const char *filename); -CZMQ_EXPORT int - zfile_delete (const char *filename); -CZMQ_EXPORT bool - zfile_stable (const char *filename); -CZMQ_EXPORT int - zfile_mkdir (const char *pathname); -CZMQ_EXPORT int - zfile_rmdir (const char *pathname); -CZMQ_EXPORT void - zfile_mode_private (void); -CZMQ_EXPORT void - zfile_mode_default (void); -// @end - -#ifdef __cplusplus -} -#endif - - -#endif // __ZFILE_H_INCLUDED__ diff --git a/phonelibs/zmq/aarch64/include/zframe.h b/phonelibs/zmq/aarch64/include/zframe.h deleted file mode 100644 index 728093c36c..0000000000 --- a/phonelibs/zmq/aarch64/include/zframe.h +++ /dev/null @@ -1,176 +0,0 @@ -/* ========================================================================= - zframe - working with single message frames - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZFRAME_H_INCLUDED__ -#define __ZFRAME_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zframe.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -#define ZFRAME_MORE 1 // -#define ZFRAME_REUSE 2 // -#define ZFRAME_DONTWAIT 4 // - -// Create a new frame. If size is not null, allocates the frame data -// to the specified size. If additionally, data is not null, copies -// size octets from the specified data into the frame body. -CZMQ_EXPORT zframe_t * - zframe_new (const void *data, size_t size); - -// Create an empty (zero-sized) frame -CZMQ_EXPORT zframe_t * - zframe_new_empty (void); - -// Create a frame with a specified string content. -CZMQ_EXPORT zframe_t * - zframe_from (const char *string); - -// Receive frame from socket, returns zframe_t object or NULL if the recv -// was interrupted. Does a blocking recv, if you want to not block then use -// zpoller or zloop. -CZMQ_EXPORT zframe_t * - zframe_recv (void *source); - -// Destroy a frame -CZMQ_EXPORT void - zframe_destroy (zframe_t **self_p); - -// Send a frame to a socket, destroy frame after sending. -// Return -1 on error, 0 on success. -CZMQ_EXPORT int - zframe_send (zframe_t **self_p, void *dest, int flags); - -// Return number of bytes in frame data -CZMQ_EXPORT size_t - zframe_size (zframe_t *self); - -// Return address of frame data -CZMQ_EXPORT byte * - zframe_data (zframe_t *self); - -// Return meta data property for frame -// Caller must free string when finished with it. -CZMQ_EXPORT const char * - zframe_meta (zframe_t *self, const char *property); - -// Create a new frame that duplicates an existing frame. If frame is null, -// or memory was exhausted, returns null. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zframe_dup (zframe_t *self); - -// Return frame data encoded as printable hex string, useful for 0MQ UUIDs. -// Caller must free string when finished with it. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zframe_strhex (zframe_t *self); - -// Return frame data copied into freshly allocated string -// Caller must free string when finished with it. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zframe_strdup (zframe_t *self); - -// Return TRUE if frame body is equal to string, excluding terminator -CZMQ_EXPORT bool - zframe_streq (zframe_t *self, const char *string); - -// Return frame MORE indicator (1 or 0), set when reading frame from socket -// or by the zframe_set_more() method -CZMQ_EXPORT int - zframe_more (zframe_t *self); - -// Set frame MORE indicator (1 or 0). Note this is NOT used when sending -// frame to socket, you have to specify flag explicitly. -CZMQ_EXPORT void - zframe_set_more (zframe_t *self, int more); - -// Return TRUE if two frames have identical size and data -// If either frame is NULL, equality is always false. -CZMQ_EXPORT bool - zframe_eq (zframe_t *self, zframe_t *other); - -// Set new contents for frame -CZMQ_EXPORT void - zframe_reset (zframe_t *self, const void *data, size_t size); - -// Send message to zsys log sink (may be stdout, or system facility as -// configured by zsys_set_logstream). Prefix shows before frame, if not null. -CZMQ_EXPORT void - zframe_print (zframe_t *self, const char *prefix); - -// Probe the supplied object, and report if it looks like a zframe_t. -CZMQ_EXPORT bool - zframe_is (void *self); - -// Self test of this class. -CZMQ_EXPORT void - zframe_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Return frame routing ID, if the frame came from a ZMQ_SERVER socket. -// Else returns zero. -CZMQ_EXPORT uint32_t - zframe_routing_id (zframe_t *self); - -// *** Draft method, for development use, may change without warning *** -// Set routing ID on frame. This is used if/when the frame is sent to a -// ZMQ_SERVER socket. -CZMQ_EXPORT void - zframe_set_routing_id (zframe_t *self, uint32_t routing_id); - -// *** Draft method, for development use, may change without warning *** -// Return frame group of radio-dish pattern. -CZMQ_EXPORT const char * - zframe_group (zframe_t *self); - -// *** Draft method, for development use, may change without warning *** -// Set group on frame. This is used if/when the frame is sent to a -// ZMQ_RADIO socket. -// Return -1 on error, 0 on success. -CZMQ_EXPORT int - zframe_set_group (zframe_t *self, const char *group); - -#endif // CZMQ_BUILD_DRAFT_API -// @end - - -// DEPRECATED as poor style -- callers should use zloop or zpoller -// Receive a new frame off the socket. Returns newly allocated frame, or -// NULL if there was no input waiting, or if the read was interrupted. -CZMQ_EXPORT zframe_t * - zframe_recv_nowait (void *source); - -// DEPRECATED as inconsistent; breaks principle that logging should all go -// to a single destination. -// Print contents of the frame to FILE stream. -CZMQ_EXPORT void - zframe_fprint (zframe_t *self, const char *prefix, FILE *file); - -// Deprecated method aliases -#define zframe_print_to_stream(s,p,F) zframe_fprint(s,p,F) - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zgossip.h b/phonelibs/zmq/aarch64/include/zgossip.h deleted file mode 100644 index 647cb28c08..0000000000 --- a/phonelibs/zmq/aarch64/include/zgossip.h +++ /dev/null @@ -1,95 +0,0 @@ -/* ========================================================================= - zgossip - zgossip server - - ** WARNING ************************************************************* - THIS SOURCE FILE IS 100% GENERATED. If you edit this file, you will lose - your changes at the next build cycle. This is great for temporary printf - statements. DO NOT MAKE ANY CHANGES YOU WISH TO KEEP. The correct places - for commits are: - - * The XML model used for this code generation: zgossip.xml, or - * The code generation script that built this file: zproto_server_c - ************************************************************************ - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef ZGOSSIP_H_INCLUDED -#define ZGOSSIP_H_INCLUDED - -#include "czmq.h" - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// To work with zgossip, use the CZMQ zactor API: -// -// Create new zgossip instance, passing logging prefix: -// -// zactor_t *zgossip = zactor_new (zgossip, "myname"); -// -// Destroy zgossip instance -// -// zactor_destroy (&zgossip); -// -// Enable verbose logging of commands and activity: -// -// zstr_send (zgossip, "VERBOSE"); -// -// Bind zgossip to specified endpoint. TCP endpoints may specify -// the port number as "*" to aquire an ephemeral port: -// -// zstr_sendx (zgossip, "BIND", endpoint, NULL); -// -// Return assigned port number, specifically when BIND was done using an -// an ephemeral port: -// -// zstr_sendx (zgossip, "PORT", NULL); -// char *command, *port_str; -// zstr_recvx (zgossip, &command, &port_str, NULL); -// assert (streq (command, "PORT")); -// -// Specify configuration file to load, overwriting any previous loaded -// configuration file or options: -// -// zstr_sendx (zgossip, "LOAD", filename, NULL); -// -// Set configuration path value: -// -// zstr_sendx (zgossip, "SET", path, value, NULL); -// -// Save configuration data to config file on disk: -// -// zstr_sendx (zgossip, "SAVE", filename, NULL); -// -// Send zmsg_t instance to zgossip: -// -// zactor_send (zgossip, &msg); -// -// Receive zmsg_t instance from zgossip: -// -// zmsg_t *msg = zactor_recv (zgossip); -// -// This is the zgossip constructor as a zactor_fn: -// -CZMQ_EXPORT void - zgossip (zsock_t *pipe, void *args); - -// Self test of this class -CZMQ_EXPORT void - zgossip_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zhash.h b/phonelibs/zmq/aarch64/include/zhash.h deleted file mode 100644 index 929bc2683a..0000000000 --- a/phonelibs/zmq/aarch64/include/zhash.h +++ /dev/null @@ -1,198 +0,0 @@ -/* ========================================================================= - zhash - generic type-free hash container (simple) - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZHASH_H_INCLUDED__ -#define __ZHASH_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zhash.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has legacy methods, which will be removed over time. You -// should not use them, and migrate any code that is still using them. -// Callback function for zhash_freefn method -typedef void (zhash_free_fn) ( - void *data); - -// Callback function for zhash_foreach method. Deprecated. -typedef int (zhash_foreach_fn) ( - const char *key, void *item, void *argument); - -// Create a new, empty hash container -CZMQ_EXPORT zhash_t * - zhash_new (void); - -// Unpack binary frame into a new hash table. Packed data must follow format -// defined by zhash_pack. Hash table is set to autofree. An empty frame -// unpacks to an empty hash table. -CZMQ_EXPORT zhash_t * - zhash_unpack (zframe_t *frame); - -// Destroy a hash container and all items in it -CZMQ_EXPORT void - zhash_destroy (zhash_t **self_p); - -// Insert item into hash table with specified key and item. -// If key is already present returns -1 and leaves existing item unchanged -// Returns 0 on success. -CZMQ_EXPORT int - zhash_insert (zhash_t *self, const char *key, void *item); - -// Update item into hash table with specified key and item. -// If key is already present, destroys old item and inserts new one. -// Use free_fn method to ensure deallocator is properly called on item. -CZMQ_EXPORT void - zhash_update (zhash_t *self, const char *key, void *item); - -// Remove an item specified by key from the hash table. If there was no such -// item, this function does nothing. -CZMQ_EXPORT void - zhash_delete (zhash_t *self, const char *key); - -// Return the item at the specified key, or null -CZMQ_EXPORT void * - zhash_lookup (zhash_t *self, const char *key); - -// Reindexes an item from an old key to a new key. If there was no such -// item, does nothing. Returns 0 if successful, else -1. -CZMQ_EXPORT int - zhash_rename (zhash_t *self, const char *old_key, const char *new_key); - -// Set a free function for the specified hash table item. When the item is -// destroyed, the free function, if any, is called on that item. -// Use this when hash items are dynamically allocated, to ensure that -// you don't have memory leaks. You can pass 'free' or NULL as a free_fn. -// Returns the item, or NULL if there is no such item. -CZMQ_EXPORT void * - zhash_freefn (zhash_t *self, const char *key, zhash_free_fn free_fn); - -// Return the number of keys/items in the hash table -CZMQ_EXPORT size_t - zhash_size (zhash_t *self); - -// Make copy of hash table; if supplied table is null, returns null. -// Does not copy items themselves. Rebuilds new table so may be slow on -// very large tables. NOTE: only works with item values that are strings -// since there's no other way to know how to duplicate the item value. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zhash_t * - zhash_dup (zhash_t *self); - -// Return keys for items in table -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlist_t * - zhash_keys (zhash_t *self); - -// Simple iterator; returns first item in hash table, in no given order, -// or NULL if the table is empty. This method is simpler to use than the -// foreach() method, which is deprecated. To access the key for this item -// use zhash_cursor(). NOTE: do NOT modify the table while iterating. -CZMQ_EXPORT void * - zhash_first (zhash_t *self); - -// Simple iterator; returns next item in hash table, in no given order, -// or NULL if the last item was already returned. Use this together with -// zhash_first() to process all items in a hash table. If you need the -// items in sorted order, use zhash_keys() and then zlist_sort(). To -// access the key for this item use zhash_cursor(). NOTE: do NOT modify -// the table while iterating. -CZMQ_EXPORT void * - zhash_next (zhash_t *self); - -// After a successful first/next method, returns the key for the item that -// was returned. This is a constant string that you may not modify or -// deallocate, and which lasts as long as the item in the hash. After an -// unsuccessful first/next, returns NULL. -CZMQ_EXPORT const char * - zhash_cursor (zhash_t *self); - -// Add a comment to hash table before saving to disk. You can add as many -// comment lines as you like. These comment lines are discarded when loading -// the file. If you use a null format, all comments are deleted. -CZMQ_EXPORT void - zhash_comment (zhash_t *self, const char *format, ...); - -// Serialize hash table to a binary frame that can be sent in a message. -// The packed format is compatible with the 'dictionary' type defined in -// http://rfc.zeromq.org/spec:35/FILEMQ, and implemented by zproto: -// -// ; A list of name/value pairs -// dictionary = dict-count *( dict-name dict-value ) -// dict-count = number-4 -// dict-value = longstr -// dict-name = string -// -// ; Strings are always length + text contents -// longstr = number-4 *VCHAR -// string = number-1 *VCHAR -// -// ; Numbers are unsigned integers in network byte order -// number-1 = 1OCTET -// number-4 = 4OCTET -// -// Comments are not included in the packed data. Item values MUST be -// strings. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zhash_pack (zhash_t *self); - -// Save hash table to a text file in name=value format. Hash values must be -// printable strings; keys may not contain '=' character. Returns 0 if OK, -// else -1 if a file error occurred. -CZMQ_EXPORT int - zhash_save (zhash_t *self, const char *filename); - -// Load hash table from a text file in name=value format; hash table must -// already exist. Hash values must printable strings; keys may not contain -// '=' character. Returns 0 if OK, else -1 if a file was not readable. -CZMQ_EXPORT int - zhash_load (zhash_t *self, const char *filename); - -// When a hash table was loaded from a file by zhash_load, this method will -// reload the file if it has been modified since, and is "stable", i.e. not -// still changing. Returns 0 if OK, -1 if there was an error reloading the -// file. -CZMQ_EXPORT int - zhash_refresh (zhash_t *self); - -// Set hash for automatic value destruction -CZMQ_EXPORT void - zhash_autofree (zhash_t *self); - -// *** Deprecated method, slated for removal: avoid using it *** -// Apply function to each item in the hash table. Items are iterated in no -// defined order. Stops if callback function returns non-zero and returns -// final return code from callback function (zero = success). Deprecated. -CZMQ_EXPORT int - zhash_foreach (zhash_t *self, zhash_foreach_fn callback, void *argument); - -// Self test of this class. -CZMQ_EXPORT void - zhash_test (bool verbose); - -// @ignore -CZMQ_EXPORT void - zhash_comment (zhash_t *self, const char *format, ...) CHECK_PRINTF (2); -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zhashx.h b/phonelibs/zmq/aarch64/include/zhashx.h deleted file mode 100644 index 8776073156..0000000000 --- a/phonelibs/zmq/aarch64/include/zhashx.h +++ /dev/null @@ -1,301 +0,0 @@ -/* ========================================================================= - zhashx - extended generic type-free hash container - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZHASHX_H_INCLUDED__ -#define __ZHASHX_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zhashx.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// This class has legacy methods, which will be removed over time. You -// should not use them, and migrate any code that is still using them. -// Destroy an item -typedef void (zhashx_destructor_fn) ( - void **item); - -// Duplicate an item -typedef void * (zhashx_duplicator_fn) ( - const void *item); - -// Compare two items, for sorting -typedef int (zhashx_comparator_fn) ( - const void *item1, const void *item2); - -// compare two items, for sorting -typedef void (zhashx_free_fn) ( - void *data); - -// compare two items, for sorting -typedef size_t (zhashx_hash_fn) ( - const void *key); - -// Serializes an item to a longstr. -// The caller takes ownership of the newly created object. -typedef char * (zhashx_serializer_fn) ( - const void *item); - -// Deserializes a longstr into an item. -// The caller takes ownership of the newly created object. -typedef void * (zhashx_deserializer_fn) ( - const char *item_str); - -// Callback function for zhashx_foreach method. -// This callback is deprecated and you should use zhashx_first/_next instead. -typedef int (zhashx_foreach_fn) ( - const char *key, void *item, void *argument); - -// Create a new, empty hash container -CZMQ_EXPORT zhashx_t * - zhashx_new (void); - -// Unpack binary frame into a new hash table. Packed data must follow format -// defined by zhashx_pack. Hash table is set to autofree. An empty frame -// unpacks to an empty hash table. -CZMQ_EXPORT zhashx_t * - zhashx_unpack (zframe_t *frame); - -// Destroy a hash container and all items in it -CZMQ_EXPORT void - zhashx_destroy (zhashx_t **self_p); - -// Insert item into hash table with specified key and item. -// If key is already present returns -1 and leaves existing item unchanged -// Returns 0 on success. -CZMQ_EXPORT int - zhashx_insert (zhashx_t *self, const void *key, void *item); - -// Update or insert item into hash table with specified key and item. If the -// key is already present, destroys old item and inserts new one. If you set -// a container item destructor, this is called on the old value. If the key -// was not already present, inserts a new item. Sets the hash cursor to the -// new item. -CZMQ_EXPORT void - zhashx_update (zhashx_t *self, const void *key, void *item); - -// Remove an item specified by key from the hash table. If there was no such -// item, this function does nothing. -CZMQ_EXPORT void - zhashx_delete (zhashx_t *self, const void *key); - -// Delete all items from the hash table. If the key destructor is -// set, calls it on every key. If the item destructor is set, calls -// it on every item. -CZMQ_EXPORT void - zhashx_purge (zhashx_t *self); - -// Return the item at the specified key, or null -CZMQ_EXPORT void * - zhashx_lookup (zhashx_t *self, const void *key); - -// Reindexes an item from an old key to a new key. If there was no such -// item, does nothing. Returns 0 if successful, else -1. -CZMQ_EXPORT int - zhashx_rename (zhashx_t *self, const void *old_key, const void *new_key); - -// Set a free function for the specified hash table item. When the item is -// destroyed, the free function, if any, is called on that item. -// Use this when hash items are dynamically allocated, to ensure that -// you don't have memory leaks. You can pass 'free' or NULL as a free_fn. -// Returns the item, or NULL if there is no such item. -CZMQ_EXPORT void * - zhashx_freefn (zhashx_t *self, const void *key, zhashx_free_fn free_fn); - -// Return the number of keys/items in the hash table -CZMQ_EXPORT size_t - zhashx_size (zhashx_t *self); - -// Return a zlistx_t containing the keys for the items in the -// table. Uses the key_duplicator to duplicate all keys and sets the -// key_destructor as destructor for the list. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlistx_t * - zhashx_keys (zhashx_t *self); - -// Return a zlistx_t containing the values for the items in the -// table. Uses the duplicator to duplicate all items and sets the -// destructor as destructor for the list. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlistx_t * - zhashx_values (zhashx_t *self); - -// Simple iterator; returns first item in hash table, in no given order, -// or NULL if the table is empty. This method is simpler to use than the -// foreach() method, which is deprecated. To access the key for this item -// use zhashx_cursor(). NOTE: do NOT modify the table while iterating. -CZMQ_EXPORT void * - zhashx_first (zhashx_t *self); - -// Simple iterator; returns next item in hash table, in no given order, -// or NULL if the last item was already returned. Use this together with -// zhashx_first() to process all items in a hash table. If you need the -// items in sorted order, use zhashx_keys() and then zlistx_sort(). To -// access the key for this item use zhashx_cursor(). NOTE: do NOT modify -// the table while iterating. -CZMQ_EXPORT void * - zhashx_next (zhashx_t *self); - -// After a successful first/next method, returns the key for the item that -// was returned. This is a constant string that you may not modify or -// deallocate, and which lasts as long as the item in the hash. After an -// unsuccessful first/next, returns NULL. -CZMQ_EXPORT const void * - zhashx_cursor (zhashx_t *self); - -// Add a comment to hash table before saving to disk. You can add as many -// comment lines as you like. These comment lines are discarded when loading -// the file. If you use a null format, all comments are deleted. -CZMQ_EXPORT void - zhashx_comment (zhashx_t *self, const char *format, ...); - -// Save hash table to a text file in name=value format. Hash values must be -// printable strings; keys may not contain '=' character. Returns 0 if OK, -// else -1 if a file error occurred. -CZMQ_EXPORT int - zhashx_save (zhashx_t *self, const char *filename); - -// Load hash table from a text file in name=value format; hash table must -// already exist. Hash values must printable strings; keys may not contain -// '=' character. Returns 0 if OK, else -1 if a file was not readable. -CZMQ_EXPORT int - zhashx_load (zhashx_t *self, const char *filename); - -// When a hash table was loaded from a file by zhashx_load, this method will -// reload the file if it has been modified since, and is "stable", i.e. not -// still changing. Returns 0 if OK, -1 if there was an error reloading the -// file. -CZMQ_EXPORT int - zhashx_refresh (zhashx_t *self); - -// Serialize hash table to a binary frame that can be sent in a message. -// The packed format is compatible with the 'dictionary' type defined in -// http://rfc.zeromq.org/spec:35/FILEMQ, and implemented by zproto: -// -// ; A list of name/value pairs -// dictionary = dict-count *( dict-name dict-value ) -// dict-count = number-4 -// dict-value = longstr -// dict-name = string -// -// ; Strings are always length + text contents -// longstr = number-4 *VCHAR -// string = number-1 *VCHAR -// -// ; Numbers are unsigned integers in network byte order -// number-1 = 1OCTET -// number-4 = 4OCTET -// -// Comments are not included in the packed data. Item values MUST be -// strings. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zhashx_pack (zhashx_t *self); - -// Make a copy of the list; items are duplicated if you set a duplicator -// for the list, otherwise not. Copying a null reference returns a null -// reference. Note that this method's behavior changed slightly for CZMQ -// v3.x, as it does not set nor respect autofree. It does however let you -// duplicate any hash table safely. The old behavior is in zhashx_dup_v2. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zhashx_t * - zhashx_dup (zhashx_t *self); - -// Set a user-defined deallocator for hash items; by default items are not -// freed when the hash is destroyed. -CZMQ_EXPORT void - zhashx_set_destructor (zhashx_t *self, zhashx_destructor_fn destructor); - -// Set a user-defined duplicator for hash items; by default items are not -// copied when the hash is duplicated. -CZMQ_EXPORT void - zhashx_set_duplicator (zhashx_t *self, zhashx_duplicator_fn duplicator); - -// Set a user-defined deallocator for keys; by default keys are freed -// when the hash is destroyed using free(). -CZMQ_EXPORT void - zhashx_set_key_destructor (zhashx_t *self, zhashx_destructor_fn destructor); - -// Set a user-defined duplicator for keys; by default keys are duplicated -// using strdup. -CZMQ_EXPORT void - zhashx_set_key_duplicator (zhashx_t *self, zhashx_duplicator_fn duplicator); - -// Set a user-defined comparator for keys; by default keys are -// compared using strcmp. -CZMQ_EXPORT void - zhashx_set_key_comparator (zhashx_t *self, zhashx_comparator_fn comparator); - -// Set a user-defined comparator for keys; by default keys are -// compared using strcmp. -CZMQ_EXPORT void - zhashx_set_key_hasher (zhashx_t *self, zhashx_hash_fn hasher); - -// Make copy of hash table; if supplied table is null, returns null. -// Does not copy items themselves. Rebuilds new table so may be slow on -// very large tables. NOTE: only works with item values that are strings -// since there's no other way to know how to duplicate the item value. -CZMQ_EXPORT zhashx_t * - zhashx_dup_v2 (zhashx_t *self); - -// *** Deprecated method, slated for removal: avoid using it *** -// Set hash for automatic value destruction. This method is deprecated -// and you should use set_destructor instead. -CZMQ_EXPORT void - zhashx_autofree (zhashx_t *self); - -// *** Deprecated method, slated for removal: avoid using it *** -// Apply function to each item in the hash table. Items are iterated in no -// defined order. Stops if callback function returns non-zero and returns -// final return code from callback function (zero = success). This method -// is deprecated and you should use zhashx_first/_next instead. -CZMQ_EXPORT int - zhashx_foreach (zhashx_t *self, zhashx_foreach_fn callback, void *argument); - -// Self test of this class. -CZMQ_EXPORT void - zhashx_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Same as unpack but uses a user-defined deserializer function to convert -// a longstr back into item format. -CZMQ_EXPORT zhashx_t * - zhashx_unpack_own (zframe_t *frame, zhashx_deserializer_fn deserializer); - -// *** Draft method, for development use, may change without warning *** -// Same as pack but uses a user-defined serializer function to convert items -// into longstr. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zhashx_pack_own (zhashx_t *self, zhashx_serializer_fn serializer); - -#endif // CZMQ_BUILD_DRAFT_API -// @ignore -CZMQ_EXPORT void - zhashx_comment (zhashx_t *self, const char *format, ...) CHECK_PRINTF (2); -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/ziflist.h b/phonelibs/zmq/aarch64/include/ziflist.h deleted file mode 100644 index cb2b144802..0000000000 --- a/phonelibs/zmq/aarch64/include/ziflist.h +++ /dev/null @@ -1,77 +0,0 @@ -/* ========================================================================= - ziflist - List of network interfaces available on system - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZIFLIST_H_INCLUDED__ -#define __ZIFLIST_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/ziflist.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Get a list of network interfaces currently defined on the system -CZMQ_EXPORT ziflist_t * - ziflist_new (void); - -// Destroy a ziflist instance -CZMQ_EXPORT void - ziflist_destroy (ziflist_t **self_p); - -// Reload network interfaces from system -CZMQ_EXPORT void - ziflist_reload (ziflist_t *self); - -// Return the number of network interfaces on system -CZMQ_EXPORT size_t - ziflist_size (ziflist_t *self); - -// Get first network interface, return NULL if there are none -CZMQ_EXPORT const char * - ziflist_first (ziflist_t *self); - -// Get next network interface, return NULL if we hit the last one -CZMQ_EXPORT const char * - ziflist_next (ziflist_t *self); - -// Return the current interface IP address as a printable string -CZMQ_EXPORT const char * - ziflist_address (ziflist_t *self); - -// Return the current interface broadcast address as a printable string -CZMQ_EXPORT const char * - ziflist_broadcast (ziflist_t *self); - -// Return the current interface network mask as a printable string -CZMQ_EXPORT const char * - ziflist_netmask (ziflist_t *self); - -// Return the list of interfaces. -CZMQ_EXPORT void - ziflist_print (ziflist_t *self); - -// Self test of this class. -CZMQ_EXPORT void - ziflist_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zlist.h b/phonelibs/zmq/aarch64/include/zlist.h deleted file mode 100644 index 1dcd39b995..0000000000 --- a/phonelibs/zmq/aarch64/include/zlist.h +++ /dev/null @@ -1,158 +0,0 @@ -/* ========================================================================= - zlist - simple generic list container - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZLIST_H_INCLUDED__ -#define __ZLIST_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zlist.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Comparison function e.g. for sorting and removing. -typedef int (zlist_compare_fn) ( - void *item1, void *item2); - -// Callback function for zlist_freefn method -typedef void (zlist_free_fn) ( - void *data); - -// Create a new list container -CZMQ_EXPORT zlist_t * - zlist_new (void); - -// Destroy a list container -CZMQ_EXPORT void - zlist_destroy (zlist_t **self_p); - -// Return the item at the head of list. If the list is empty, returns NULL. -// Leaves cursor pointing at the head item, or NULL if the list is empty. -CZMQ_EXPORT void * - zlist_first (zlist_t *self); - -// Return the next item. If the list is empty, returns NULL. To move to -// the start of the list call zlist_first (). Advances the cursor. -CZMQ_EXPORT void * - zlist_next (zlist_t *self); - -// Return the item at the tail of list. If the list is empty, returns NULL. -// Leaves cursor pointing at the tail item, or NULL if the list is empty. -CZMQ_EXPORT void * - zlist_last (zlist_t *self); - -// Return first item in the list, or null, leaves the cursor -CZMQ_EXPORT void * - zlist_head (zlist_t *self); - -// Return last item in the list, or null, leaves the cursor -CZMQ_EXPORT void * - zlist_tail (zlist_t *self); - -// Return the current item of list. If the list is empty, returns NULL. -// Leaves cursor pointing at the current item, or NULL if the list is empty. -CZMQ_EXPORT void * - zlist_item (zlist_t *self); - -// Append an item to the end of the list, return 0 if OK or -1 if this -// failed for some reason (out of memory). Note that if a duplicator has -// been set, this method will also duplicate the item. -CZMQ_EXPORT int - zlist_append (zlist_t *self, void *item); - -// Push an item to the start of the list, return 0 if OK or -1 if this -// failed for some reason (out of memory). Note that if a duplicator has -// been set, this method will also duplicate the item. -CZMQ_EXPORT int - zlist_push (zlist_t *self, void *item); - -// Pop the item off the start of the list, if any -CZMQ_EXPORT void * - zlist_pop (zlist_t *self); - -// Checks if an item already is present. Uses compare method to determine if -// items are equal. If the compare method is NULL the check will only compare -// pointers. Returns true if item is present else false. -CZMQ_EXPORT bool - zlist_exists (zlist_t *self, void *item); - -// Remove the specified item from the list if present -CZMQ_EXPORT void - zlist_remove (zlist_t *self, void *item); - -// Make a copy of list. If the list has autofree set, the copied list will -// duplicate all items, which must be strings. Otherwise, the list will hold -// pointers back to the items in the original list. If list is null, returns -// NULL. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlist_t * - zlist_dup (zlist_t *self); - -// Purge all items from list -CZMQ_EXPORT void - zlist_purge (zlist_t *self); - -// Return number of items in the list -CZMQ_EXPORT size_t - zlist_size (zlist_t *self); - -// Sort the list. If the compare function is null, sorts the list by -// ascending key value using a straight ASCII comparison. If you specify -// a compare function, this decides how items are sorted. The sort is not -// stable, so may reorder items with the same keys. The algorithm used is -// combsort, a compromise between performance and simplicity. -CZMQ_EXPORT void - zlist_sort (zlist_t *self, zlist_compare_fn compare); - -// Set list for automatic item destruction; item values MUST be strings. -// By default a list item refers to a value held elsewhere. When you set -// this, each time you append or push a list item, zlist will take a copy -// of the string value. Then, when you destroy the list, it will free all -// item values automatically. If you use any other technique to allocate -// list values, you must free them explicitly before destroying the list. -// The usual technique is to pop list items and destroy them, until the -// list is empty. -CZMQ_EXPORT void - zlist_autofree (zlist_t *self); - -// Sets a compare function for this list. The function compares two items. -// It returns an integer less than, equal to, or greater than zero if the -// first item is found, respectively, to be less than, to match, or be -// greater than the second item. -// This function is used for sorting, removal and exists checking. -CZMQ_EXPORT void - zlist_comparefn (zlist_t *self, zlist_compare_fn fn); - -// Set a free function for the specified list item. When the item is -// destroyed, the free function, if any, is called on that item. -// Use this when list items are dynamically allocated, to ensure that -// you don't have memory leaks. You can pass 'free' or NULL as a free_fn. -// Returns the item, or NULL if there is no such item. -CZMQ_EXPORT void * - zlist_freefn (zlist_t *self, void *item, zlist_free_fn fn, bool at_tail); - -// Self test of this class. -CZMQ_EXPORT void - zlist_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zlistx.h b/phonelibs/zmq/aarch64/include/zlistx.h deleted file mode 100644 index 512637cef3..0000000000 --- a/phonelibs/zmq/aarch64/include/zlistx.h +++ /dev/null @@ -1,205 +0,0 @@ -/* ========================================================================= - zlistx - extended generic list container - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZLISTX_H_INCLUDED__ -#define __ZLISTX_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zlistx.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Destroy an item -typedef void (zlistx_destructor_fn) ( - void **item); - -// Duplicate an item -typedef void * (zlistx_duplicator_fn) ( - const void *item); - -// Compare two items, for sorting -typedef int (zlistx_comparator_fn) ( - const void *item1, const void *item2); - -// Create a new, empty list. -CZMQ_EXPORT zlistx_t * - zlistx_new (void); - -// Destroy a list. If an item destructor was specified, all items in the -// list are automatically destroyed as well. -CZMQ_EXPORT void - zlistx_destroy (zlistx_t **self_p); - -// Add an item to the head of the list. Calls the item duplicator, if any, -// on the item. Resets cursor to list head. Returns an item handle on -// success, NULL if memory was exhausted. -CZMQ_EXPORT void * - zlistx_add_start (zlistx_t *self, void *item); - -// Add an item to the tail of the list. Calls the item duplicator, if any, -// on the item. Resets cursor to list head. Returns an item handle on -// success, NULL if memory was exhausted. -CZMQ_EXPORT void * - zlistx_add_end (zlistx_t *self, void *item); - -// Return the number of items in the list -CZMQ_EXPORT size_t - zlistx_size (zlistx_t *self); - -// Return first item in the list, or null, leaves the cursor -CZMQ_EXPORT void * - zlistx_head (zlistx_t *self); - -// Return last item in the list, or null, leaves the cursor -CZMQ_EXPORT void * - zlistx_tail (zlistx_t *self); - -// Return the item at the head of list. If the list is empty, returns NULL. -// Leaves cursor pointing at the head item, or NULL if the list is empty. -CZMQ_EXPORT void * - zlistx_first (zlistx_t *self); - -// Return the next item. At the end of the list (or in an empty list), -// returns NULL. Use repeated zlistx_next () calls to work through the list -// from zlistx_first (). First time, acts as zlistx_first(). -CZMQ_EXPORT void * - zlistx_next (zlistx_t *self); - -// Return the previous item. At the start of the list (or in an empty list), -// returns NULL. Use repeated zlistx_prev () calls to work through the list -// backwards from zlistx_last (). First time, acts as zlistx_last(). -CZMQ_EXPORT void * - zlistx_prev (zlistx_t *self); - -// Return the item at the tail of list. If the list is empty, returns NULL. -// Leaves cursor pointing at the tail item, or NULL if the list is empty. -CZMQ_EXPORT void * - zlistx_last (zlistx_t *self); - -// Returns the value of the item at the cursor, or NULL if the cursor is -// not pointing to an item. -CZMQ_EXPORT void * - zlistx_item (zlistx_t *self); - -// Returns the handle of the item at the cursor, or NULL if the cursor is -// not pointing to an item. -CZMQ_EXPORT void * - zlistx_cursor (zlistx_t *self); - -// Returns the item associated with the given list handle, or NULL if passed -// in handle is NULL. Asserts that the passed in handle points to a list element. -CZMQ_EXPORT void * - zlistx_handle_item (void *handle); - -// Find an item in the list, searching from the start. Uses the item -// comparator, if any, else compares item values directly. Returns the -// item handle found, or NULL. Sets the cursor to the found item, if any. -CZMQ_EXPORT void * - zlistx_find (zlistx_t *self, void *item); - -// Detach an item from the list, using its handle. The item is not modified, -// and the caller is responsible for destroying it if necessary. If handle is -// null, detaches the first item on the list. Returns item that was detached, -// or null if none was. If cursor was at item, moves cursor to previous item, -// so you can detach items while iterating forwards through a list. -CZMQ_EXPORT void * - zlistx_detach (zlistx_t *self, void *handle); - -// Detach item at the cursor, if any, from the list. The item is not modified, -// and the caller is responsible for destroying it as necessary. Returns item -// that was detached, or null if none was. Moves cursor to previous item, so -// you can detach items while iterating forwards through a list. -CZMQ_EXPORT void * - zlistx_detach_cur (zlistx_t *self); - -// Delete an item, using its handle. Calls the item destructor is any is -// set. If handle is null, deletes the first item on the list. Returns 0 -// if an item was deleted, -1 if not. If cursor was at item, moves cursor -// to previous item, so you can delete items while iterating forwards -// through a list. -CZMQ_EXPORT int - zlistx_delete (zlistx_t *self, void *handle); - -// Move an item to the start of the list, via its handle. -CZMQ_EXPORT void - zlistx_move_start (zlistx_t *self, void *handle); - -// Move an item to the end of the list, via its handle. -CZMQ_EXPORT void - zlistx_move_end (zlistx_t *self, void *handle); - -// Remove all items from the list, and destroy them if the item destructor -// is set. -CZMQ_EXPORT void - zlistx_purge (zlistx_t *self); - -// Sort the list. If an item comparator was set, calls that to compare -// items, otherwise compares on item value. The sort is not stable, so may -// reorder equal items. -CZMQ_EXPORT void - zlistx_sort (zlistx_t *self); - -// Create a new node and insert it into a sorted list. Calls the item -// duplicator, if any, on the item. If low_value is true, starts searching -// from the start of the list, otherwise searches from the end. Use the item -// comparator, if any, to find where to place the new node. Returns a handle -// to the new node, or NULL if memory was exhausted. Resets the cursor to the -// list head. -CZMQ_EXPORT void * - zlistx_insert (zlistx_t *self, void *item, bool low_value); - -// Move an item, specified by handle, into position in a sorted list. Uses -// the item comparator, if any, to determine the new location. If low_value -// is true, starts searching from the start of the list, otherwise searches -// from the end. -CZMQ_EXPORT void - zlistx_reorder (zlistx_t *self, void *handle, bool low_value); - -// Make a copy of the list; items are duplicated if you set a duplicator -// for the list, otherwise not. Copying a null reference returns a null -// reference. -CZMQ_EXPORT zlistx_t * - zlistx_dup (zlistx_t *self); - -// Set a user-defined deallocator for list items; by default items are not -// freed when the list is destroyed. -CZMQ_EXPORT void - zlistx_set_destructor (zlistx_t *self, zlistx_destructor_fn destructor); - -// Set a user-defined duplicator for list items; by default items are not -// copied when the list is duplicated. -CZMQ_EXPORT void - zlistx_set_duplicator (zlistx_t *self, zlistx_duplicator_fn duplicator); - -// Set a user-defined comparator for zlistx_find and zlistx_sort; the method -// must return -1, 0, or 1 depending on whether item1 is less than, equal to, -// or greater than, item2. -CZMQ_EXPORT void - zlistx_set_comparator (zlistx_t *self, zlistx_comparator_fn comparator); - -// Self test of this class. -CZMQ_EXPORT void - zlistx_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zloop.h b/phonelibs/zmq/aarch64/include/zloop.h deleted file mode 100644 index bc58ea0530..0000000000 --- a/phonelibs/zmq/aarch64/include/zloop.h +++ /dev/null @@ -1,168 +0,0 @@ -/* ========================================================================= - zloop - event-driven reactor - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZLOOP_H_INCLUDED__ -#define __ZLOOP_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zloop.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// Callback function for reactor socket activity -typedef int (zloop_reader_fn) ( - zloop_t *loop, zsock_t *reader, void *arg); - -// Callback function for reactor events (low-level) -typedef int (zloop_fn) ( - zloop_t *loop, zmq_pollitem_t *item, void *arg); - -// Callback for reactor timer events -typedef int (zloop_timer_fn) ( - zloop_t *loop, int timer_id, void *arg); - -// Create a new zloop reactor -CZMQ_EXPORT zloop_t * - zloop_new (void); - -// Destroy a reactor -CZMQ_EXPORT void - zloop_destroy (zloop_t **self_p); - -// Register socket reader with the reactor. When the reader has messages, -// the reactor will call the handler, passing the arg. Returns 0 if OK, -1 -// if there was an error. If you register the same socket more than once, -// each instance will invoke its corresponding handler. -CZMQ_EXPORT int - zloop_reader (zloop_t *self, zsock_t *sock, zloop_reader_fn handler, void *arg); - -// Cancel a socket reader from the reactor. If multiple readers exist for -// same socket, cancels ALL of them. -CZMQ_EXPORT void - zloop_reader_end (zloop_t *self, zsock_t *sock); - -// Configure a registered reader to ignore errors. If you do not set this, -// then readers that have errors are removed from the reactor silently. -CZMQ_EXPORT void - zloop_reader_set_tolerant (zloop_t *self, zsock_t *sock); - -// Register low-level libzmq pollitem with the reactor. When the pollitem -// is ready, will call the handler, passing the arg. Returns 0 if OK, -1 -// if there was an error. If you register the pollitem more than once, each -// instance will invoke its corresponding handler. A pollitem with -// socket=NULL and fd=0 means 'poll on FD zero'. -CZMQ_EXPORT int - zloop_poller (zloop_t *self, zmq_pollitem_t *item, zloop_fn handler, void *arg); - -// Cancel a pollitem from the reactor, specified by socket or FD. If both -// are specified, uses only socket. If multiple poll items exist for same -// socket/FD, cancels ALL of them. -CZMQ_EXPORT void - zloop_poller_end (zloop_t *self, zmq_pollitem_t *item); - -// Configure a registered poller to ignore errors. If you do not set this, -// then poller that have errors are removed from the reactor silently. -CZMQ_EXPORT void - zloop_poller_set_tolerant (zloop_t *self, zmq_pollitem_t *item); - -// Register a timer that expires after some delay and repeats some number of -// times. At each expiry, will call the handler, passing the arg. To run a -// timer forever, use 0 times. Returns a timer_id that is used to cancel the -// timer in the future. Returns -1 if there was an error. -CZMQ_EXPORT int - zloop_timer (zloop_t *self, size_t delay, size_t times, zloop_timer_fn handler, void *arg); - -// Cancel a specific timer identified by a specific timer_id (as returned by -// zloop_timer). -CZMQ_EXPORT int - zloop_timer_end (zloop_t *self, int timer_id); - -// Register a ticket timer. Ticket timers are very fast in the case where -// you use a lot of timers (thousands), and frequently remove and add them. -// The main use case is expiry timers for servers that handle many clients, -// and which reset the expiry timer for each message received from a client. -// Whereas normal timers perform poorly as the number of clients grows, the -// cost of ticket timers is constant, no matter the number of clients. You -// must set the ticket delay using zloop_set_ticket_delay before creating a -// ticket. Returns a handle to the timer that you should use in -// zloop_ticket_reset and zloop_ticket_delete. -CZMQ_EXPORT void * - zloop_ticket (zloop_t *self, zloop_timer_fn handler, void *arg); - -// Reset a ticket timer, which moves it to the end of the ticket list and -// resets its execution time. This is a very fast operation. -CZMQ_EXPORT void - zloop_ticket_reset (zloop_t *self, void *handle); - -// Delete a ticket timer. We do not actually delete the ticket here, as -// other code may still refer to the ticket. We mark as deleted, and remove -// later and safely. -CZMQ_EXPORT void - zloop_ticket_delete (zloop_t *self, void *handle); - -// Set the ticket delay, which applies to all tickets. If you lower the -// delay and there are already tickets created, the results are undefined. -CZMQ_EXPORT void - zloop_set_ticket_delay (zloop_t *self, size_t ticket_delay); - -// Set hard limit on number of timers allowed. Setting more than a small -// number of timers (10-100) can have a dramatic impact on the performance -// of the reactor. For high-volume cases, use ticket timers. If the hard -// limit is reached, the reactor stops creating new timers and logs an -// error. -CZMQ_EXPORT void - zloop_set_max_timers (zloop_t *self, size_t max_timers); - -// Set verbose tracing of reactor on/off. The default verbose setting is -// off (false). -CZMQ_EXPORT void - zloop_set_verbose (zloop_t *self, bool verbose); - -// Start the reactor. Takes control of the thread and returns when the 0MQ -// context is terminated or the process is interrupted, or any event handler -// returns -1. Event handlers may register new sockets and timers, and -// cancel sockets. Returns 0 if interrupted, -1 if canceled by a handler. -CZMQ_EXPORT int - zloop_start (zloop_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zloop_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// By default the reactor stops if the process receives a SIGINT or SIGTERM -// signal. This makes it impossible to shut-down message based architectures -// like zactors. This method lets you switch off break handling. The default -// nonstop setting is off (false). -CZMQ_EXPORT void - zloop_set_nonstop (zloop_t *self, bool nonstop); - -#endif // CZMQ_BUILD_DRAFT_API -// @end - - -// Deprecated method aliases -#define zloop_set_tolerant(s,i) zloop_poller_set_tolerant(s,i) - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zmonitor.h b/phonelibs/zmq/aarch64/include/zmonitor.h deleted file mode 100644 index b490bcb1a0..0000000000 --- a/phonelibs/zmq/aarch64/include/zmonitor.h +++ /dev/null @@ -1,73 +0,0 @@ -/* ========================================================================= - zmonitor - socket event monitor - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZMONITOR_H_INCLUDED__ -#define __ZMONITOR_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// Create new zmonitor actor instance to monitor a zsock_t socket: -// -// zactor_t *monitor = zactor_new (zmonitor, mysocket); -// -// Destroy zmonitor instance. -// -// zactor_destroy (&monitor); -// -// Enable verbose logging of commands and activity. -// -// zstr_send (monitor, "VERBOSE"); -// -// Listen to monitor event type (zero or types, ending in NULL): -// zstr_sendx (monitor, "LISTEN", type, ..., NULL); -// -// Events: -// CONNECTED -// CONNECT_DELAYED -// CONNECT_RETRIED -// LISTENING -// BIND_FAILED -// ACCEPTED -// ACCEPT_FAILED -// CLOSED -// CLOSE_FAILED -// DISCONNECTED -// MONITOR_STOPPED -// ALL -// -// Start monitor; after this, any further LISTEN commands are ignored. -// -// zstr_send (monitor, "START"); -// zsock_wait (monitor); -// -// Receive next monitor event: -// -// zmsg_t *msg = zmsg_recv (monitor); -// -// This is the zmonitor constructor as a zactor_fn; the argument can be -// a zactor_t, zsock_t, or libzmq void * socket: -CZMQ_EXPORT void - zmonitor (zsock_t *pipe, void *sock); - -// Selftest -CZMQ_EXPORT void - zmonitor_test (bool verbose); -// @end -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zmonitor_v2.h b/phonelibs/zmq/aarch64/include/zmonitor_v2.h deleted file mode 100644 index 5780e0bcb7..0000000000 --- a/phonelibs/zmq/aarch64/include/zmonitor_v2.h +++ /dev/null @@ -1,56 +0,0 @@ -/* ========================================================================= - zmonitor_v2 - socket event monitor (deprecated) - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZMONITOR_V2_H_INCLUDED__ -#define __ZMONITOR_V2_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// This code needs backporting to work with ZMQ v3.2 -#if (ZMQ_VERSION_MAJOR == 4) - -// Create a new socket monitor -CZMQ_EXPORT zmonitor_t * - zmonitor_new (zctx_t *ctx, void *socket, int events); - -// Destroy a socket monitor -CZMQ_EXPORT void - zmonitor_destroy (zmonitor_t **self_p); - -// Receive a status message from the monitor; if no message arrives within -// 500 msec, or the call was interrupted, returns NULL. -CZMQ_EXPORT zmsg_t * - zmonitor_recv (zmonitor_t *self); - -// Get the ZeroMQ socket, for polling -CZMQ_EXPORT void * - zmonitor_socket (zmonitor_t *self); - -// Enable verbose tracing of commands and activity -CZMQ_EXPORT void - zmonitor_set_verbose (zmonitor_t *self, bool verbose); -#endif // ZeroMQ 4.0 or later - -// Self test of this class -CZMQ_EXPORT void - zmonitor_v2_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zmq.h b/phonelibs/zmq/aarch64/include/zmq.h deleted file mode 100644 index 5f35d1915f..0000000000 --- a/phonelibs/zmq/aarch64/include/zmq.h +++ /dev/null @@ -1,617 +0,0 @@ -/* - Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file - - This file is part of libzmq, the ZeroMQ core engine in C++. - - libzmq is free software; you can redistribute it and/or modify it under - the terms of the GNU Lesser General Public License (LGPL) as published - by the Free Software Foundation; either version 3 of the License, or - (at your option) any later version. - - As a special exception, the Contributors give you permission to link - this library with independent modules to produce an executable, - regardless of the license terms of these independent modules, and to - copy and distribute the resulting executable under terms of your choice, - provided that you also meet, for each linked independent module, the - terms and conditions of the license of that module. An independent - module is a module which is not derived from or based on this library. - If you modify this library, you must extend this exception to your - version of the library. - - libzmq is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public - License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . - - ************************************************************************* - NOTE to contributors. This file comprises the principal public contract - for ZeroMQ API users. Any change to this file supplied in a stable - release SHOULD not break existing applications. - In practice this means that the value of constants must not change, and - that old values may not be reused for new constants. - ************************************************************************* -*/ - -#ifndef __ZMQ_H_INCLUDED__ -#define __ZMQ_H_INCLUDED__ - -/* Version macros for compile-time API version detection */ -#define ZMQ_VERSION_MAJOR 4 -#define ZMQ_VERSION_MINOR 2 -#define ZMQ_VERSION_PATCH 0 - -#define ZMQ_MAKE_VERSION(major, minor, patch) \ - ((major) * 10000 + (minor) * 100 + (patch)) -#define ZMQ_VERSION \ - ZMQ_MAKE_VERSION(ZMQ_VERSION_MAJOR, ZMQ_VERSION_MINOR, ZMQ_VERSION_PATCH) - -#ifdef __cplusplus -extern "C" { -#endif - -#if !defined _WIN32_WCE -#include -#endif -#include -#include -#if defined _WIN32 -// Set target version to Windows Server 2008, Windows Vista or higher. -// Windows XP (0x0501) is supported but without client & server socket types. -#ifndef _WIN32_WINNT -#define _WIN32_WINNT 0x0600 -#endif - -#ifdef __MINGW32__ -// Require Windows XP or higher with MinGW for getaddrinfo(). -#if(_WIN32_WINNT >= 0x0600) -#else -#undef _WIN32_WINNT -#define _WIN32_WINNT 0x0600 -#endif -#endif -#include -#endif - -/* Handle DSO symbol visibility */ -#if defined _WIN32 -# if defined ZMQ_STATIC -# define ZMQ_EXPORT -# elif defined DLL_EXPORT -# define ZMQ_EXPORT __declspec(dllexport) -# else -# define ZMQ_EXPORT __declspec(dllimport) -# endif -#else -# if defined __SUNPRO_C || defined __SUNPRO_CC -# define ZMQ_EXPORT __global -# elif (defined __GNUC__ && __GNUC__ >= 4) || defined __INTEL_COMPILER -# define ZMQ_EXPORT __attribute__ ((visibility("default"))) -# else -# define ZMQ_EXPORT -# endif -#endif - -/* Define integer types needed for event interface */ -#define ZMQ_DEFINED_STDINT 1 -#if defined ZMQ_HAVE_SOLARIS || defined ZMQ_HAVE_OPENVMS -# include -#elif defined _MSC_VER && _MSC_VER < 1600 -# ifndef int32_t - typedef __int32 int32_t; -# endif -# ifndef uint16_t - typedef unsigned __int16 uint16_t; -# endif -# ifndef uint8_t - typedef unsigned __int8 uint8_t; -# endif -#else -# include -#endif - - -/******************************************************************************/ -/* 0MQ errors. */ -/******************************************************************************/ - -/* A number random enough not to collide with different errno ranges on */ -/* different OSes. The assumption is that error_t is at least 32-bit type. */ -#define ZMQ_HAUSNUMERO 156384712 - -/* On Windows platform some of the standard POSIX errnos are not defined. */ -#ifndef ENOTSUP -#define ENOTSUP (ZMQ_HAUSNUMERO + 1) -#endif -#ifndef EPROTONOSUPPORT -#define EPROTONOSUPPORT (ZMQ_HAUSNUMERO + 2) -#endif -#ifndef ENOBUFS -#define ENOBUFS (ZMQ_HAUSNUMERO + 3) -#endif -#ifndef ENETDOWN -#define ENETDOWN (ZMQ_HAUSNUMERO + 4) -#endif -#ifndef EADDRINUSE -#define EADDRINUSE (ZMQ_HAUSNUMERO + 5) -#endif -#ifndef EADDRNOTAVAIL -#define EADDRNOTAVAIL (ZMQ_HAUSNUMERO + 6) -#endif -#ifndef ECONNREFUSED -#define ECONNREFUSED (ZMQ_HAUSNUMERO + 7) -#endif -#ifndef EINPROGRESS -#define EINPROGRESS (ZMQ_HAUSNUMERO + 8) -#endif -#ifndef ENOTSOCK -#define ENOTSOCK (ZMQ_HAUSNUMERO + 9) -#endif -#ifndef EMSGSIZE -#define EMSGSIZE (ZMQ_HAUSNUMERO + 10) -#endif -#ifndef EAFNOSUPPORT -#define EAFNOSUPPORT (ZMQ_HAUSNUMERO + 11) -#endif -#ifndef ENETUNREACH -#define ENETUNREACH (ZMQ_HAUSNUMERO + 12) -#endif -#ifndef ECONNABORTED -#define ECONNABORTED (ZMQ_HAUSNUMERO + 13) -#endif -#ifndef ECONNRESET -#define ECONNRESET (ZMQ_HAUSNUMERO + 14) -#endif -#ifndef ENOTCONN -#define ENOTCONN (ZMQ_HAUSNUMERO + 15) -#endif -#ifndef ETIMEDOUT -#define ETIMEDOUT (ZMQ_HAUSNUMERO + 16) -#endif -#ifndef EHOSTUNREACH -#define EHOSTUNREACH (ZMQ_HAUSNUMERO + 17) -#endif -#ifndef ENETRESET -#define ENETRESET (ZMQ_HAUSNUMERO + 18) -#endif - -/* Native 0MQ error codes. */ -#define EFSM (ZMQ_HAUSNUMERO + 51) -#define ENOCOMPATPROTO (ZMQ_HAUSNUMERO + 52) -#define ETERM (ZMQ_HAUSNUMERO + 53) -#define EMTHREAD (ZMQ_HAUSNUMERO + 54) - -/* This function retrieves the errno as it is known to 0MQ library. The goal */ -/* of this function is to make the code 100% portable, including where 0MQ */ -/* compiled with certain CRT library (on Windows) is linked to an */ -/* application that uses different CRT library. */ -ZMQ_EXPORT int zmq_errno (void); - -/* Resolves system errors and 0MQ errors to human-readable string. */ -ZMQ_EXPORT const char *zmq_strerror (int errnum); - -/* Run-time API version detection */ -ZMQ_EXPORT void zmq_version (int *major, int *minor, int *patch); - -/******************************************************************************/ -/* 0MQ infrastructure (a.k.a. context) initialisation & termination. */ -/******************************************************************************/ - -/* Context options */ -#define ZMQ_IO_THREADS 1 -#define ZMQ_MAX_SOCKETS 2 -#define ZMQ_SOCKET_LIMIT 3 -#define ZMQ_THREAD_PRIORITY 3 -#define ZMQ_THREAD_SCHED_POLICY 4 -#define ZMQ_MAX_MSGSZ 5 - -/* Default for new contexts */ -#define ZMQ_IO_THREADS_DFLT 1 -#define ZMQ_MAX_SOCKETS_DFLT 1023 -#define ZMQ_THREAD_PRIORITY_DFLT -1 -#define ZMQ_THREAD_SCHED_POLICY_DFLT -1 - -ZMQ_EXPORT void *zmq_ctx_new (void); -ZMQ_EXPORT int zmq_ctx_term (void *context); -ZMQ_EXPORT int zmq_ctx_shutdown (void *context); -ZMQ_EXPORT int zmq_ctx_set (void *context, int option, int optval); -ZMQ_EXPORT int zmq_ctx_get (void *context, int option); - -/* Old (legacy) API */ -ZMQ_EXPORT void *zmq_init (int io_threads); -ZMQ_EXPORT int zmq_term (void *context); -ZMQ_EXPORT int zmq_ctx_destroy (void *context); - - -/******************************************************************************/ -/* 0MQ message definition. */ -/******************************************************************************/ - -/* union here ensures correct alignment on architectures that require it, e.g. - * SPARC - */ -typedef union zmq_msg_t {unsigned char _ [64]; void *p; } zmq_msg_t; - -typedef void (zmq_free_fn) (void *data, void *hint); - -ZMQ_EXPORT int zmq_msg_init (zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_init_size (zmq_msg_t *msg, size_t size); -ZMQ_EXPORT int zmq_msg_init_data (zmq_msg_t *msg, void *data, - size_t size, zmq_free_fn *ffn, void *hint); -ZMQ_EXPORT int zmq_msg_send (zmq_msg_t *msg, void *s, int flags); -ZMQ_EXPORT int zmq_msg_recv (zmq_msg_t *msg, void *s, int flags); -ZMQ_EXPORT int zmq_msg_close (zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_move (zmq_msg_t *dest, zmq_msg_t *src); -ZMQ_EXPORT int zmq_msg_copy (zmq_msg_t *dest, zmq_msg_t *src); -ZMQ_EXPORT void *zmq_msg_data (zmq_msg_t *msg); -ZMQ_EXPORT size_t zmq_msg_size (zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_more (zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_get (zmq_msg_t *msg, int property); -ZMQ_EXPORT int zmq_msg_set (zmq_msg_t *msg, int property, int optval); -ZMQ_EXPORT const char *zmq_msg_gets (zmq_msg_t *msg, const char *property); - -/******************************************************************************/ -/* 0MQ socket definition. */ -/******************************************************************************/ - -/* Socket types. */ -#define ZMQ_PAIR 0 -#define ZMQ_PUB 1 -#define ZMQ_SUB 2 -#define ZMQ_REQ 3 -#define ZMQ_REP 4 -#define ZMQ_DEALER 5 -#define ZMQ_ROUTER 6 -#define ZMQ_PULL 7 -#define ZMQ_PUSH 8 -#define ZMQ_XPUB 9 -#define ZMQ_XSUB 10 -#define ZMQ_STREAM 11 - -/* Deprecated aliases */ -#define ZMQ_XREQ ZMQ_DEALER -#define ZMQ_XREP ZMQ_ROUTER - -/* Socket options. */ -#define ZMQ_AFFINITY 4 -#define ZMQ_IDENTITY 5 -#define ZMQ_SUBSCRIBE 6 -#define ZMQ_UNSUBSCRIBE 7 -#define ZMQ_RATE 8 -#define ZMQ_RECOVERY_IVL 9 -#define ZMQ_SNDBUF 11 -#define ZMQ_RCVBUF 12 -#define ZMQ_RCVMORE 13 -#define ZMQ_FD 14 -#define ZMQ_EVENTS 15 -#define ZMQ_TYPE 16 -#define ZMQ_LINGER 17 -#define ZMQ_RECONNECT_IVL 18 -#define ZMQ_BACKLOG 19 -#define ZMQ_RECONNECT_IVL_MAX 21 -#define ZMQ_MAXMSGSIZE 22 -#define ZMQ_SNDHWM 23 -#define ZMQ_RCVHWM 24 -#define ZMQ_MULTICAST_HOPS 25 -#define ZMQ_RCVTIMEO 27 -#define ZMQ_SNDTIMEO 28 -#define ZMQ_LAST_ENDPOINT 32 -#define ZMQ_ROUTER_MANDATORY 33 -#define ZMQ_TCP_KEEPALIVE 34 -#define ZMQ_TCP_KEEPALIVE_CNT 35 -#define ZMQ_TCP_KEEPALIVE_IDLE 36 -#define ZMQ_TCP_KEEPALIVE_INTVL 37 -#define ZMQ_IMMEDIATE 39 -#define ZMQ_XPUB_VERBOSE 40 -#define ZMQ_ROUTER_RAW 41 -#define ZMQ_IPV6 42 -#define ZMQ_MECHANISM 43 -#define ZMQ_PLAIN_SERVER 44 -#define ZMQ_PLAIN_USERNAME 45 -#define ZMQ_PLAIN_PASSWORD 46 -#define ZMQ_CURVE_SERVER 47 -#define ZMQ_CURVE_PUBLICKEY 48 -#define ZMQ_CURVE_SECRETKEY 49 -#define ZMQ_CURVE_SERVERKEY 50 -#define ZMQ_PROBE_ROUTER 51 -#define ZMQ_REQ_CORRELATE 52 -#define ZMQ_REQ_RELAXED 53 -#define ZMQ_CONFLATE 54 -#define ZMQ_ZAP_DOMAIN 55 -#define ZMQ_ROUTER_HANDOVER 56 -#define ZMQ_TOS 57 -#define ZMQ_CONNECT_RID 61 -#define ZMQ_GSSAPI_SERVER 62 -#define ZMQ_GSSAPI_PRINCIPAL 63 -#define ZMQ_GSSAPI_SERVICE_PRINCIPAL 64 -#define ZMQ_GSSAPI_PLAINTEXT 65 -#define ZMQ_HANDSHAKE_IVL 66 -#define ZMQ_SOCKS_PROXY 68 -#define ZMQ_XPUB_NODROP 69 -// All options after this is for version 4.2 and still *draft* -// Subject to arbitrary change without notice -#define ZMQ_BLOCKY 70 -#define ZMQ_XPUB_MANUAL 71 -#define ZMQ_XPUB_WELCOME_MSG 72 -#define ZMQ_STREAM_NOTIFY 73 -#define ZMQ_INVERT_MATCHING 74 -#define ZMQ_HEARTBEAT_IVL 75 -#define ZMQ_HEARTBEAT_TTL 76 -#define ZMQ_HEARTBEAT_TIMEOUT 77 -#define ZMQ_XPUB_VERBOSER 78 -#define ZMQ_CONNECT_TIMEOUT 79 -#define ZMQ_TCP_MAXRT 80 -#define ZMQ_THREAD_SAFE 81 -#define ZMQ_MULTICAST_MAXTPDU 84 -#define ZMQ_VMCI_BUFFER_SIZE 85 -#define ZMQ_VMCI_BUFFER_MIN_SIZE 86 -#define ZMQ_VMCI_BUFFER_MAX_SIZE 87 -#define ZMQ_VMCI_CONNECT_TIMEOUT 88 -#define ZMQ_USE_FD 89 - -/* Message options */ -#define ZMQ_MORE 1 -#define ZMQ_SHARED 3 - -/* Send/recv options. */ -#define ZMQ_DONTWAIT 1 -#define ZMQ_SNDMORE 2 - -/* Security mechanisms */ -#define ZMQ_NULL 0 -#define ZMQ_PLAIN 1 -#define ZMQ_CURVE 2 -#define ZMQ_GSSAPI 3 - -/* RADIO-DISH protocol */ -#define ZMQ_GROUP_MAX_LENGTH 15 - -/* Deprecated options and aliases */ -#define ZMQ_TCP_ACCEPT_FILTER 38 -#define ZMQ_IPC_FILTER_PID 58 -#define ZMQ_IPC_FILTER_UID 59 -#define ZMQ_IPC_FILTER_GID 60 -#define ZMQ_IPV4ONLY 31 -#define ZMQ_DELAY_ATTACH_ON_CONNECT ZMQ_IMMEDIATE -#define ZMQ_NOBLOCK ZMQ_DONTWAIT -#define ZMQ_FAIL_UNROUTABLE ZMQ_ROUTER_MANDATORY -#define ZMQ_ROUTER_BEHAVIOR ZMQ_ROUTER_MANDATORY - -/* Deprecated Message options */ -#define ZMQ_SRCFD 2 - -/******************************************************************************/ -/* 0MQ socket events and monitoring */ -/******************************************************************************/ - -/* Socket transport events (TCP, IPC and TIPC only) */ - -#define ZMQ_EVENT_CONNECTED 0x0001 -#define ZMQ_EVENT_CONNECT_DELAYED 0x0002 -#define ZMQ_EVENT_CONNECT_RETRIED 0x0004 -#define ZMQ_EVENT_LISTENING 0x0008 -#define ZMQ_EVENT_BIND_FAILED 0x0010 -#define ZMQ_EVENT_ACCEPTED 0x0020 -#define ZMQ_EVENT_ACCEPT_FAILED 0x0040 -#define ZMQ_EVENT_CLOSED 0x0080 -#define ZMQ_EVENT_CLOSE_FAILED 0x0100 -#define ZMQ_EVENT_DISCONNECTED 0x0200 -#define ZMQ_EVENT_MONITOR_STOPPED 0x0400 -#define ZMQ_EVENT_ALL 0xFFFF - -ZMQ_EXPORT void *zmq_socket (void *, int type); -ZMQ_EXPORT int zmq_close (void *s); -ZMQ_EXPORT int zmq_setsockopt (void *s, int option, const void *optval, - size_t optvallen); -ZMQ_EXPORT int zmq_getsockopt (void *s, int option, void *optval, - size_t *optvallen); -ZMQ_EXPORT int zmq_bind (void *s, const char *addr); -ZMQ_EXPORT int zmq_connect (void *s, const char *addr); -ZMQ_EXPORT int zmq_unbind (void *s, const char *addr); -ZMQ_EXPORT int zmq_disconnect (void *s, const char *addr); -ZMQ_EXPORT int zmq_send (void *s, const void *buf, size_t len, int flags); -ZMQ_EXPORT int zmq_send_const (void *s, const void *buf, size_t len, int flags); -ZMQ_EXPORT int zmq_recv (void *s, void *buf, size_t len, int flags); -ZMQ_EXPORT int zmq_socket_monitor (void *s, const char *addr, int events); - - -/******************************************************************************/ -/* I/O multiplexing. */ -/******************************************************************************/ - -#define ZMQ_POLLIN 1 -#define ZMQ_POLLOUT 2 -#define ZMQ_POLLERR 4 -#define ZMQ_POLLPRI 8 - -typedef struct zmq_pollitem_t -{ - void *socket; -#if defined _WIN32 - SOCKET fd; -#else - int fd; -#endif - short events; - short revents; -} zmq_pollitem_t; - -#define ZMQ_POLLITEMS_DFLT 16 - -ZMQ_EXPORT int zmq_poll (zmq_pollitem_t *items, int nitems, long timeout); - -/******************************************************************************/ -/* Message proxying */ -/******************************************************************************/ - -ZMQ_EXPORT int zmq_proxy (void *frontend, void *backend, void *capture); -ZMQ_EXPORT int zmq_proxy_steerable (void *frontend, void *backend, void *capture, void *control); - -/******************************************************************************/ -/* Probe library capabilities */ -/******************************************************************************/ - -#define ZMQ_HAS_CAPABILITIES 1 -ZMQ_EXPORT int zmq_has (const char *capability); - -/* Deprecated aliases */ -#define ZMQ_STREAMER 1 -#define ZMQ_FORWARDER 2 -#define ZMQ_QUEUE 3 - -/* Deprecated methods */ -ZMQ_EXPORT int zmq_device (int type, void *frontend, void *backend); -ZMQ_EXPORT int zmq_sendmsg (void *s, zmq_msg_t *msg, int flags); -ZMQ_EXPORT int zmq_recvmsg (void *s, zmq_msg_t *msg, int flags); -struct iovec; -ZMQ_EXPORT int zmq_sendiov (void *s, struct iovec *iov, size_t count, int flags); -ZMQ_EXPORT int zmq_recviov (void *s, struct iovec *iov, size_t *count, int flags); - -/******************************************************************************/ -/* Encryption functions */ -/******************************************************************************/ - -/* Encode data with Z85 encoding. Returns encoded data */ -ZMQ_EXPORT char *zmq_z85_encode (char *dest, const uint8_t *data, size_t size); - -/* Decode data with Z85 encoding. Returns decoded data */ -ZMQ_EXPORT uint8_t *zmq_z85_decode (uint8_t *dest, const char *string); - -/* Generate z85-encoded public and private keypair with tweetnacl/libsodium. */ -/* Returns 0 on success. */ -ZMQ_EXPORT int zmq_curve_keypair (char *z85_public_key, char *z85_secret_key); - -/* Derive the z85-encoded public key from the z85-encoded secret key. */ -/* Returns 0 on success. */ -ZMQ_EXPORT int zmq_curve_public (char *z85_public_key, const char *z85_secret_key); - -/******************************************************************************/ -/* Atomic utility methods */ -/******************************************************************************/ - -ZMQ_EXPORT void *zmq_atomic_counter_new (void); -ZMQ_EXPORT void zmq_atomic_counter_set (void *counter, int value); -ZMQ_EXPORT int zmq_atomic_counter_inc (void *counter); -ZMQ_EXPORT int zmq_atomic_counter_dec (void *counter); -ZMQ_EXPORT int zmq_atomic_counter_value (void *counter); -ZMQ_EXPORT void zmq_atomic_counter_destroy (void **counter_p); - - -/******************************************************************************/ -/* These functions are not documented by man pages -- use at your own risk. */ -/* If you need these to be part of the formal ZMQ API, then (a) write a man */ -/* page, and (b) write a test case in tests. */ -/******************************************************************************/ - -/* Helper functions are used by perf tests so that they don't have to care */ -/* about minutiae of time-related functions on different OS platforms. */ - -/* Starts the stopwatch. Returns the handle to the watch. */ -ZMQ_EXPORT void *zmq_stopwatch_start (void); - -/* Stops the stopwatch. Returns the number of microseconds elapsed since */ -/* the stopwatch was started. */ -ZMQ_EXPORT unsigned long zmq_stopwatch_stop (void *watch_); - -/* Sleeps for specified number of seconds. */ -ZMQ_EXPORT void zmq_sleep (int seconds_); - -typedef void (zmq_thread_fn) (void*); - -/* Start a thread. Returns a handle to the thread. */ -ZMQ_EXPORT void *zmq_threadstart (zmq_thread_fn* func, void* arg); - -/* Wait for thread to complete then free up resources. */ -ZMQ_EXPORT void zmq_threadclose (void* thread); - - -/******************************************************************************/ -/* These functions are DRAFT and disabled in stable releases, and subject to */ -/* change at ANY time until declared stable. */ -/******************************************************************************/ - -#ifdef ZMQ_BUILD_DRAFT_API - -/* DRAFT Socket types. */ -#define ZMQ_SERVER 12 -#define ZMQ_CLIENT 13 -#define ZMQ_RADIO 14 -#define ZMQ_DISH 15 -#define ZMQ_GATHER 16 -#define ZMQ_SCATTER 17 -#define ZMQ_DGRAM 18 - -/* DRAFT Socket methods. */ -ZMQ_EXPORT int zmq_join (void *s, const char *group); -ZMQ_EXPORT int zmq_leave (void *s, const char *group); - -/* DRAFT Msg methods. */ -ZMQ_EXPORT int zmq_msg_set_routing_id(zmq_msg_t *msg, uint32_t routing_id); -ZMQ_EXPORT uint32_t zmq_msg_routing_id(zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_set_group(zmq_msg_t *msg, const char *group); -ZMQ_EXPORT const char *zmq_msg_group(zmq_msg_t *msg); - -/******************************************************************************/ -/* Poller polling on sockets,fd and thread-safe sockets */ -/******************************************************************************/ - -#define ZMQ_HAVE_POLLER - -typedef struct zmq_poller_event_t -{ - void *socket; -#if defined _WIN32 - SOCKET fd; -#else - int fd; -#endif - void *user_data; - short events; -} zmq_poller_event_t; - -ZMQ_EXPORT void *zmq_poller_new (void); -ZMQ_EXPORT int zmq_poller_destroy (void **poller_p); -ZMQ_EXPORT int zmq_poller_add (void *poller, void *socket, void *user_data, short events); -ZMQ_EXPORT int zmq_poller_modify (void *poller, void *socket, short events); -ZMQ_EXPORT int zmq_poller_remove (void *poller, void *socket); -ZMQ_EXPORT int zmq_poller_wait (void *poller, zmq_poller_event_t *event, long timeout); - -#if defined _WIN32 -ZMQ_EXPORT int zmq_poller_add_fd (void *poller, SOCKET fd, void *user_data, short events); -ZMQ_EXPORT int zmq_poller_modify_fd (void *poller, SOCKET fd, short events); -ZMQ_EXPORT int zmq_poller_remove_fd (void *poller, SOCKET fd); -#else -ZMQ_EXPORT int zmq_poller_add_fd (void *poller, int fd, void *user_data, short events); -ZMQ_EXPORT int zmq_poller_modify_fd (void *poller, int fd, short events); -ZMQ_EXPORT int zmq_poller_remove_fd (void *poller, int fd); -#endif - -/******************************************************************************/ -/* Scheduling timers */ -/******************************************************************************/ - -#define ZMQ_HAVE_TIMERS - -typedef void (zmq_timer_fn)(int timer_id, void *arg); - -ZMQ_EXPORT void *zmq_timers_new (void); -ZMQ_EXPORT int zmq_timers_destroy (void **timers_p); -ZMQ_EXPORT int zmq_timers_add (void *timers, size_t interval, zmq_timer_fn handler, void *arg); -ZMQ_EXPORT int zmq_timers_cancel (void *timers, int timer_id); -ZMQ_EXPORT int zmq_timers_set_interval (void *timers, int timer_id, size_t interval); -ZMQ_EXPORT int zmq_timers_reset (void *timers, int timer_id); -ZMQ_EXPORT long zmq_timers_timeout (void *timers); -ZMQ_EXPORT int zmq_timers_execute (void *timers); - -#endif // ZMQ_BUILD_DRAFT_API - - -#undef ZMQ_EXPORT - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zmq_utils.h b/phonelibs/zmq/aarch64/include/zmq_utils.h deleted file mode 100644 index f29638d553..0000000000 --- a/phonelibs/zmq/aarch64/include/zmq_utils.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file - - This file is part of libzmq, the ZeroMQ core engine in C++. - - libzmq is free software; you can redistribute it and/or modify it under - the terms of the GNU Lesser General Public License (LGPL) as published - by the Free Software Foundation; either version 3 of the License, or - (at your option) any later version. - - As a special exception, the Contributors give you permission to link - this library with independent modules to produce an executable, - regardless of the license terms of these independent modules, and to - copy and distribute the resulting executable under terms of your choice, - provided that you also meet, for each linked independent module, the - terms and conditions of the license of that module. An independent - module is a module which is not derived from or based on this library. - If you modify this library, you must extend this exception to your - version of the library. - - libzmq is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public - License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . -*/ - -/* This file is deprecated, and all its functionality provided by zmq.h */ -/* Note that -Wpedantic compilation requires GCC to avoid using its custom - extensions such as #warning, hence the trick below. Also, pragmas for - warnings or other messages are not standard, not portable, and not all - compilers even have an equivalent concept. - So in the worst case, this include file is treated as silently empty. */ - -#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) || defined(_MSC_VER) -#if defined(__GNUC__) || defined(__GNUG__) -#pragma GCC diagnostic push -#pragma GCC diagnostic warning "-Wcpp" -#pragma GCC diagnostic ignored "-Werror" -#pragma GCC diagnostic ignored "-Wall" -#endif -#pragma message("Warning: zmq_utils.h is deprecated. All its functionality is provided by zmq.h.") -#if defined(__GNUC__) || defined(__GNUG__) -#pragma GCC diagnostic pop -#endif -#endif diff --git a/phonelibs/zmq/aarch64/include/zmsg.h b/phonelibs/zmq/aarch64/include/zmsg.h deleted file mode 100644 index c6ab16c66e..0000000000 --- a/phonelibs/zmq/aarch64/include/zmsg.h +++ /dev/null @@ -1,285 +0,0 @@ -/* ========================================================================= - zmsg - working with multipart messages - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZMSG_H_INCLUDED__ -#define __ZMSG_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zmsg.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// Create a new empty message object -CZMQ_EXPORT zmsg_t * - zmsg_new (void); - -// Receive message from socket, returns zmsg_t object or NULL if the recv -// was interrupted. Does a blocking recv. If you want to not block then use -// the zloop class or zmsg_recv_nowait or zmq_poll to check for socket input -// before receiving. -CZMQ_EXPORT zmsg_t * - zmsg_recv (void *source); - -// Load/append an open file into new message, return the message. -// Returns NULL if the message could not be loaded. -CZMQ_EXPORT zmsg_t * - zmsg_load (FILE *file); - -// Decodes a serialized message frame created by zmsg_encode () and returns -// a new zmsg_t object. Returns NULL if the frame was badly formatted or -// there was insufficient memory to work. -CZMQ_EXPORT zmsg_t * - zmsg_decode (zframe_t *frame); - -// Generate a signal message encoding the given status. A signal is a short -// message carrying a 1-byte success/failure code (by convention, 0 means -// OK). Signals are encoded to be distinguishable from "normal" messages. -CZMQ_EXPORT zmsg_t * - zmsg_new_signal (byte status); - -// Destroy a message object and all frames it contains -CZMQ_EXPORT void - zmsg_destroy (zmsg_t **self_p); - -// Send message to destination socket, and destroy the message after sending -// it successfully. If the message has no frames, sends nothing but destroys -// the message anyhow. Nullifies the caller's reference to the message (as -// it is a destructor). -CZMQ_EXPORT int - zmsg_send (zmsg_t **self_p, void *dest); - -// Send message to destination socket as part of a multipart sequence, and -// destroy the message after sending it successfully. Note that after a -// zmsg_sendm, you must call zmsg_send or another method that sends a final -// message part. If the message has no frames, sends nothing but destroys -// the message anyhow. Nullifies the caller's reference to the message (as -// it is a destructor). -CZMQ_EXPORT int - zmsg_sendm (zmsg_t **self_p, void *dest); - -// Return size of message, i.e. number of frames (0 or more). -CZMQ_EXPORT size_t - zmsg_size (zmsg_t *self); - -// Return total size of all frames in message. -CZMQ_EXPORT size_t - zmsg_content_size (zmsg_t *self); - -// Push frame to the front of the message, i.e. before all other frames. -// Message takes ownership of frame, will destroy it when message is sent. -// Returns 0 on success, -1 on error. Deprecates zmsg_push, which did not -// nullify the caller's frame reference. -CZMQ_EXPORT int - zmsg_prepend (zmsg_t *self, zframe_t **frame_p); - -// Add frame to the end of the message, i.e. after all other frames. -// Message takes ownership of frame, will destroy it when message is sent. -// Returns 0 on success. Deprecates zmsg_add, which did not nullify the -// caller's frame reference. -CZMQ_EXPORT int - zmsg_append (zmsg_t *self, zframe_t **frame_p); - -// Remove first frame from message, if any. Returns frame, or NULL. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zmsg_pop (zmsg_t *self); - -// Push block of memory to front of message, as a new frame. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_pushmem (zmsg_t *self, const void *data, size_t size); - -// Add block of memory to the end of the message, as a new frame. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_addmem (zmsg_t *self, const void *data, size_t size); - -// Push string as new frame to front of message. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_pushstr (zmsg_t *self, const char *string); - -// Push string as new frame to end of message. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_addstr (zmsg_t *self, const char *string); - -// Push formatted string as new frame to front of message. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_pushstrf (zmsg_t *self, const char *format, ...); - -// Push formatted string as new frame to end of message. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_addstrf (zmsg_t *self, const char *format, ...); - -// Pop frame off front of message, return as fresh string. If there were -// no more frames in the message, returns NULL. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zmsg_popstr (zmsg_t *self); - -// Push encoded message as a new frame. Message takes ownership of -// submessage, so the original is destroyed in this call. Returns 0 on -// success, -1 on error. -CZMQ_EXPORT int - zmsg_addmsg (zmsg_t *self, zmsg_t **msg_p); - -// Remove first submessage from message, if any. Returns zmsg_t, or NULL if -// decoding was not successful. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zmsg_t * - zmsg_popmsg (zmsg_t *self); - -// Remove specified frame from list, if present. Does not destroy frame. -CZMQ_EXPORT void - zmsg_remove (zmsg_t *self, zframe_t *frame); - -// Set cursor to first frame in message. Returns frame, or NULL, if the -// message is empty. Use this to navigate the frames as a list. -CZMQ_EXPORT zframe_t * - zmsg_first (zmsg_t *self); - -// Return the next frame. If there are no more frames, returns NULL. To move -// to the first frame call zmsg_first(). Advances the cursor. -CZMQ_EXPORT zframe_t * - zmsg_next (zmsg_t *self); - -// Return the last frame. If there are no frames, returns NULL. -CZMQ_EXPORT zframe_t * - zmsg_last (zmsg_t *self); - -// Save message to an open file, return 0 if OK, else -1. The message is -// saved as a series of frames, each with length and data. Note that the -// file is NOT guaranteed to be portable between operating systems, not -// versions of CZMQ. The file format is at present undocumented and liable -// to arbitrary change. -CZMQ_EXPORT int - zmsg_save (zmsg_t *self, FILE *file); - -// Serialize multipart message to a single message frame. Use this method -// to send structured messages across transports that do not support -// multipart data. Allocates and returns a new frame containing the -// serialized message. To decode a serialized message frame, use -// zmsg_decode (). -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zmsg_encode (zmsg_t *self); - -// Create copy of message, as new message object. Returns a fresh zmsg_t -// object. If message is null, or memory was exhausted, returns null. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zmsg_t * - zmsg_dup (zmsg_t *self); - -// Send message to zsys log sink (may be stdout, or system facility as -// configured by zsys_set_logstream). -CZMQ_EXPORT void - zmsg_print (zmsg_t *self); - -// Return true if the two messages have the same number of frames and each -// frame in the first message is identical to the corresponding frame in the -// other message. As with zframe_eq, return false if either message is NULL. -CZMQ_EXPORT bool - zmsg_eq (zmsg_t *self, zmsg_t *other); - -// Return signal value, 0 or greater, if message is a signal, -1 if not. -CZMQ_EXPORT int - zmsg_signal (zmsg_t *self); - -// Probe the supplied object, and report if it looks like a zmsg_t. -CZMQ_EXPORT bool - zmsg_is (void *self); - -// Self test of this class. -CZMQ_EXPORT void - zmsg_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Return message routing ID, if the message came from a ZMQ_SERVER socket. -// Else returns zero. -CZMQ_EXPORT uint32_t - zmsg_routing_id (zmsg_t *self); - -// *** Draft method, for development use, may change without warning *** -// Set routing ID on message. This is used if/when the message is sent to a -// ZMQ_SERVER socket. -CZMQ_EXPORT void - zmsg_set_routing_id (zmsg_t *self, uint32_t routing_id); - -#endif // CZMQ_BUILD_DRAFT_API -// @ignore -CZMQ_EXPORT int - zmsg_pushstrf (zmsg_t *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int - zmsg_addstrf (zmsg_t *self, const char *format, ...) CHECK_PRINTF (2); -// @end - - -// DEPRECATED as over-engineered, poor style -// Pop frame off front of message, caller now owns frame -// If next frame is empty, pops and destroys that empty frame. -CZMQ_EXPORT zframe_t * - zmsg_unwrap (zmsg_t *self); - -// DEPRECATED as poor style -- callers should use zloop or zpoller -// Receive message from socket, returns zmsg_t object, or NULL either if -// there was no input waiting, or the recv was interrupted. -CZMQ_EXPORT zmsg_t * - zmsg_recv_nowait (void *source); - -// DEPRECATED as unsafe -- does not nullify frame reference. -// Push frame plus empty frame to front of message, before first frame. -// Message takes ownership of frame, will destroy it when message is sent. -CZMQ_EXPORT void - zmsg_wrap (zmsg_t *self, zframe_t *frame); - -// DEPRECATED - will be removed for next + 1 stable release -// Add frame to the front of the message, i.e. before all other frames. -// Message takes ownership of frame, will destroy it when message is sent. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_push (zmsg_t *self, zframe_t *frame); - -// DEPRECATED - will be removed for next stable release -CZMQ_EXPORT int - zmsg_add (zmsg_t *self, zframe_t *frame); - -// DEPRECATED as inconsistent; breaks principle that logging should all go -// to a single destination. -// Print message to open stream -// Truncates to first 10 frames, for readability. -CZMQ_EXPORT void - zmsg_fprint (zmsg_t *self, FILE *file); - -// Compiler hints -CZMQ_EXPORT int zmsg_addstrf (zmsg_t *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int zmsg_pushstrf (zmsg_t *self, const char *format, ...) CHECK_PRINTF (2); - -#ifdef __cplusplus -} -#endif - -// Deprecated method aliases -#define zmsg_dump(s) zmsg_print(s) -#define zmsg_dump_to_stream(s,F) zmsg_fprint(s,F) - -#endif diff --git a/phonelibs/zmq/aarch64/include/zmutex.h b/phonelibs/zmq/aarch64/include/zmutex.h deleted file mode 100644 index cba315999b..0000000000 --- a/phonelibs/zmq/aarch64/include/zmutex.h +++ /dev/null @@ -1,55 +0,0 @@ -/* ========================================================================= - zmutex - working with mutexes - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZMUTEX_H_INCLUDED__ -#define __ZMUTEX_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// This is a deprecated class, and will be removed over time. It is -// provided in stable builds to support old applications. You should -// stop using this class, and migrate any code that is still using it. - -// Create a new mutex container -CZMQ_EXPORT zmutex_t * - zmutex_new (void); - -// Destroy a mutex container -CZMQ_EXPORT void - zmutex_destroy (zmutex_t **self_p); - -// Lock mutex -CZMQ_EXPORT void - zmutex_lock (zmutex_t *self); - -// Unlock mutex -CZMQ_EXPORT void - zmutex_unlock (zmutex_t *self); - -// Try to lock mutex -CZMQ_EXPORT int - zmutex_try_lock (zmutex_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zmutex_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zpoller.h b/phonelibs/zmq/aarch64/include/zpoller.h deleted file mode 100644 index 3756a935a6..0000000000 --- a/phonelibs/zmq/aarch64/include/zpoller.h +++ /dev/null @@ -1,92 +0,0 @@ -/* ========================================================================= - zpoller - trivial socket poller class - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __zpoller_H_INCLUDED__ -#define __zpoller_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zpoller.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// Create new poller, specifying zero or more readers. The list of -// readers ends in a NULL. Each reader can be a zsock_t instance, a -// zactor_t instance, a libzmq socket (void *), or a file handle. -CZMQ_EXPORT zpoller_t * - zpoller_new (void *reader, ...); - -// Destroy a poller -CZMQ_EXPORT void - zpoller_destroy (zpoller_t **self_p); - -// Add a reader to be polled. Returns 0 if OK, -1 on failure. The reader may -// be a libzmq void * socket, a zsock_t instance, or a zactor_t instance. -CZMQ_EXPORT int - zpoller_add (zpoller_t *self, void *reader); - -// Remove a reader from the poller; returns 0 if OK, -1 on failure. The reader -// must have been passed during construction, or in an zpoller_add () call. -CZMQ_EXPORT int - zpoller_remove (zpoller_t *self, void *reader); - -// Poll the registered readers for I/O, return first reader that has input. -// The reader will be a libzmq void * socket, or a zsock_t or zactor_t -// instance as specified in zpoller_new/zpoller_add. The timeout should be -// zero or greater, or -1 to wait indefinitely. Socket priority is defined -// by their order in the poll list. If you need a balanced poll, use the low -// level zmq_poll method directly. If the poll call was interrupted (SIGINT), -// or the ZMQ context was destroyed, or the timeout expired, returns NULL. -// You can test the actual exit condition by calling zpoller_expired () and -// zpoller_terminated (). The timeout is in msec. -CZMQ_EXPORT void * - zpoller_wait (zpoller_t *self, int timeout); - -// Return true if the last zpoller_wait () call ended because the timeout -// expired, without any error. -CZMQ_EXPORT bool - zpoller_expired (zpoller_t *self); - -// Return true if the last zpoller_wait () call ended because the process -// was interrupted, or the parent context was destroyed. -CZMQ_EXPORT bool - zpoller_terminated (zpoller_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zpoller_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// By default the poller stops if the process receives a SIGINT or SIGTERM -// signal. This makes it impossible to shut-down message based architectures -// like zactors. This method lets you switch off break handling. The default -// nonstop setting is off (false). -CZMQ_EXPORT void - zpoller_set_nonstop (zpoller_t *self, bool nonstop); - -#endif // CZMQ_BUILD_DRAFT_API -// @end - - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/phonelibs/zmq/aarch64/include/zproc.h b/phonelibs/zmq/aarch64/include/zproc.h deleted file mode 100644 index a2e1b3dd99..0000000000 --- a/phonelibs/zmq/aarch64/include/zproc.h +++ /dev/null @@ -1,179 +0,0 @@ -/* ========================================================================= - zproc - process configuration and status - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef ZPROC_H_INCLUDED -#define ZPROC_H_INCLUDED - -#ifdef __cplusplus -extern "C" { -#endif - - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zproc.api" to make changes. -// @interface -// This is a draft class, and may change without notice. It is disabled in -// stable builds by default. If you use this in applications, please ask -// for it to be pushed to stable state. Use --enable-drafts to enable. -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Returns CZMQ version as a single 6-digit integer encoding the major -// version (x 10000), the minor version (x 100) and the patch. -CZMQ_EXPORT int - zproc_czmq_version (void); - -// *** Draft method, for development use, may change without warning *** -// Returns true if the process received a SIGINT or SIGTERM signal. -// It is good practice to use this method to exit any infinite loop -// processing messages. -CZMQ_EXPORT bool - zproc_interrupted (void); - -// *** Draft method, for development use, may change without warning *** -// Returns true if the underlying libzmq supports CURVE security. -CZMQ_EXPORT bool - zproc_has_curve (void); - -// *** Draft method, for development use, may change without warning *** -// Return current host name, for use in public tcp:// endpoints. -// If the host name is not resolvable, returns NULL. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zproc_hostname (void); - -// *** Draft method, for development use, may change without warning *** -// Move the current process into the background. The precise effect -// depends on the operating system. On POSIX boxes, moves to a specified -// working directory (if specified), closes all file handles, reopens -// stdin, stdout, and stderr to the null device, and sets the process to -// ignore SIGHUP. On Windows, does nothing. Returns 0 if OK, -1 if there -// was an error. -CZMQ_EXPORT void - zproc_daemonize (const char *workdir); - -// *** Draft method, for development use, may change without warning *** -// Drop the process ID into the lockfile, with exclusive lock, and -// switch the process to the specified group and/or user. Any of the -// arguments may be null, indicating a no-op. Returns 0 on success, -// -1 on failure. Note if you combine this with zsys_daemonize, run -// after, not before that method, or the lockfile will hold the wrong -// process ID. -CZMQ_EXPORT void - zproc_run_as (const char *lockfile, const char *group, const char *user); - -// *** Draft method, for development use, may change without warning *** -// Configure the number of I/O threads that ZeroMQ will use. A good -// rule of thumb is one thread per gigabit of traffic in or out. The -// default is 1, sufficient for most applications. If the environment -// variable ZSYS_IO_THREADS is defined, that provides the default. -// Note that this method is valid only before any socket is created. -CZMQ_EXPORT void - zproc_set_io_threads (size_t io_threads); - -// *** Draft method, for development use, may change without warning *** -// Configure the number of sockets that ZeroMQ will allow. The default -// is 1024. The actual limit depends on the system, and you can query it -// by using zsys_socket_limit (). A value of zero means "maximum". -// Note that this method is valid only before any socket is created. -CZMQ_EXPORT void - zproc_set_max_sockets (size_t max_sockets); - -// *** Draft method, for development use, may change without warning *** -// Set network interface name to use for broadcasts, particularly zbeacon. -// This lets the interface be configured for test environments where required. -// For example, on Mac OS X, zbeacon cannot bind to 255.255.255.255 which is -// the default when there is no specified interface. If the environment -// variable ZSYS_INTERFACE is set, use that as the default interface name. -// Setting the interface to "*" means "use all available interfaces". -CZMQ_EXPORT void - zproc_set_biface (const char *value); - -// *** Draft method, for development use, may change without warning *** -// Return network interface to use for broadcasts, or "" if none was set. -CZMQ_EXPORT const char * - zproc_biface (void); - -// *** Draft method, for development use, may change without warning *** -// Set log identity, which is a string that prefixes all log messages sent -// by this process. The log identity defaults to the environment variable -// ZSYS_LOGIDENT, if that is set. -CZMQ_EXPORT void - zproc_set_log_ident (const char *value); - -// *** Draft method, for development use, may change without warning *** -// Sends log output to a PUB socket bound to the specified endpoint. To -// collect such log output, create a SUB socket, subscribe to the traffic -// you care about, and connect to the endpoint. Log traffic is sent as a -// single string frame, in the same format as when sent to stdout. The -// log system supports a single sender; multiple calls to this method will -// bind the same sender to multiple endpoints. To disable the sender, call -// this method with a null argument. -CZMQ_EXPORT void - zproc_set_log_sender (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Enable or disable logging to the system facility (syslog on POSIX boxes, -// event log on Windows). By default this is disabled. -CZMQ_EXPORT void - zproc_set_log_system (bool logsystem); - -// *** Draft method, for development use, may change without warning *** -// Log error condition - highest priority -CZMQ_EXPORT void - zproc_log_error (const char *format, ...); - -// *** Draft method, for development use, may change without warning *** -// Log warning condition - high priority -CZMQ_EXPORT void - zproc_log_warning (const char *format, ...); - -// *** Draft method, for development use, may change without warning *** -// Log normal, but significant, condition - normal priority -CZMQ_EXPORT void - zproc_log_notice (const char *format, ...); - -// *** Draft method, for development use, may change without warning *** -// Log informational message - low priority -CZMQ_EXPORT void - zproc_log_info (const char *format, ...); - -// *** Draft method, for development use, may change without warning *** -// Log debug-level message - lowest priority -CZMQ_EXPORT void - zproc_log_debug (const char *format, ...); - -// *** Draft method, for development use, may change without warning *** -// Self test of this class. -CZMQ_EXPORT void - zproc_test (bool verbose); - -#endif // CZMQ_BUILD_DRAFT_API -// @ignore -CZMQ_EXPORT void - zproc_log_error (const char *format, ...) CHECK_PRINTF (1); -CZMQ_EXPORT void - zproc_log_warning (const char *format, ...) CHECK_PRINTF (1); -CZMQ_EXPORT void - zproc_log_notice (const char *format, ...) CHECK_PRINTF (1); -CZMQ_EXPORT void - zproc_log_info (const char *format, ...) CHECK_PRINTF (1); -CZMQ_EXPORT void - zproc_log_debug (const char *format, ...) CHECK_PRINTF (1); -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zproxy.h b/phonelibs/zmq/aarch64/include/zproxy.h deleted file mode 100644 index f672c5e724..0000000000 --- a/phonelibs/zmq/aarch64/include/zproxy.h +++ /dev/null @@ -1,111 +0,0 @@ -/* ========================================================================= - zproxy - run a steerable proxy in the background - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZPROXY_H_INCLUDED__ -#define __ZPROXY_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// Create new zproxy actor instance. The proxy switches messages between -// a frontend socket and a backend socket; use the FRONTEND and BACKEND -// commands to configure these: -// -// zactor_t *proxy = zactor_new (zproxy, NULL); -// -// Destroy zproxy instance. This destroys the two sockets and stops any -// message flow between them: -// -// zactor_destroy (&proxy); -// -// Note that all zproxy commands are synchronous, so your application always -// waits for a signal from the actor after each command. -// -// Enable verbose logging of commands and activity: -// -// zstr_send (proxy, "VERBOSE"); -// zsock_wait (proxy); -// -// Specify frontend socket type -- see zsock_type_str () -- and attach to -// endpoints, see zsock_attach (). Note that a proxy socket is always -// serverish: -// -// zstr_sendx (proxy, "FRONTEND", "XSUB", endpoints, NULL); -// zsock_wait (proxy); -// -// Specify backend socket type -- see zsock_type_str () -- and attach to -// endpoints, see zsock_attach (). Note that a proxy socket is always -// serverish: -// -// zstr_sendx (proxy, "BACKEND", "XPUB", endpoints, NULL); -// zsock_wait (proxy); -// -// Capture all proxied messages; these are delivered to the application -// via an inproc PULL socket that you have already bound to the specified -// endpoint: -// -// zstr_sendx (proxy, "CAPTURE", endpoint, NULL); -// zsock_wait (proxy); -// -// Pause the proxy. A paused proxy will cease processing messages, causing -// them to be queued up and potentially hit the high-water mark on the -// frontend or backend socket, causing messages to be dropped, or writing -// applications to block: -// -// zstr_sendx (proxy, "PAUSE", NULL); -// zsock_wait (proxy); -// -// Resume the proxy. Note that the proxy starts automatically as soon as it -// has a properly attached frontend and backend socket: -// -// zstr_sendx (proxy, "RESUME", NULL); -// zsock_wait (proxy); -// -// Configure an authentication domain for the "FRONTEND" or "BACKEND" proxy -// socket -- see zsock_set_zap_domain (). Call before binding socket: -// -// zstr_sendx (proxy, "DOMAIN", "FRONTEND", "global", NULL); -// zsock_wait (proxy); -// -// Configure PLAIN authentication for the "FRONTEND" or "BACKEND" proxy -// socket -- see zsock_set_plain_server (). Call before binding socket: -// -// zstr_sendx (proxy, "PLAIN", "BACKEND", NULL); -// zsock_wait (proxy); -// -// Configure CURVE authentication for the "FRONTEND" or "BACKEND" proxy -// socket -- see zsock_set_curve_server () -- specifying both the public and -// secret keys of a certificate as Z85 armored strings -- see -// zcert_public_txt () and zcert_secret_txt (). Call before binding socket: -// -// zstr_sendx (proxy, "CURVE", "FRONTEND", public_txt, secret_txt, NULL); -// zsock_wait (proxy); -// -// This is the zproxy constructor as a zactor_fn; the argument is a -// character string specifying frontend and backend socket types as two -// uppercase strings separated by a hyphen: -CZMQ_EXPORT void - zproxy (zsock_t *pipe, void *unused); - -// Selftest -CZMQ_EXPORT void - zproxy_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zproxy_v2.h b/phonelibs/zmq/aarch64/include/zproxy_v2.h deleted file mode 100644 index 4bde951591..0000000000 --- a/phonelibs/zmq/aarch64/include/zproxy_v2.h +++ /dev/null @@ -1,62 +0,0 @@ -/* ========================================================================= - zproxy_v2 - run a steerable proxy in the background (deprecated) - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZPROXY_V2_H_INCLUDED__ -#define __ZPROXY_V2_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface - -// Constructor -// Create a new zproxy object. You must create the frontend and backend -// sockets, configure them, and connect or bind them, before you pass them -// to the constructor. Do NOT use the sockets again, after passing them to -// this method. -CZMQ_EXPORT zproxy_t * - zproxy_new (zctx_t *ctx, void *frontend, void *backend); - -// Destructor -// Destroy a zproxy object; note this first stops the proxy. -CZMQ_EXPORT void - zproxy_destroy (zproxy_t **self_p); - -// Copy all proxied messages to specified endpoint; if this is NULL, any -// in-progress capturing will be stopped. You must already have bound the -// endpoint to a PULL socket. -CZMQ_EXPORT void - zproxy_capture (zproxy_t *self, const char *endpoint); - -// Pauses a zproxy object; a paused proxy will cease processing messages, -// causing them to be queued up and potentially hit the high-water mark on -// the frontend socket, causing messages to be dropped, or writing -// applications to block. -CZMQ_EXPORT void - zproxy_pause (zproxy_t *self); - -// Resume a zproxy object -CZMQ_EXPORT void - zproxy_resume (zproxy_t *self); - -// Self test of this class -CZMQ_EXPORT void - zproxy_v2_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zrex.h b/phonelibs/zmq/aarch64/include/zrex.h deleted file mode 100644 index 8b50618a34..0000000000 --- a/phonelibs/zmq/aarch64/include/zrex.h +++ /dev/null @@ -1,82 +0,0 @@ -/* ========================================================================= - zrex - work with regular expressions - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZREX_H_INCLUDED__ -#define __ZREX_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// Constructor. Optionally, sets an expression against which we can match -// text and capture hits. If there is an error in the expression, reports -// zrex_valid() as false and provides the error in zrex_strerror(). If you -// set a pattern, you can call zrex_matches() to test it against text. -CZMQ_EXPORT zrex_t * - zrex_new (const char *expression); - -// Destructor -CZMQ_EXPORT void - zrex_destroy (zrex_t **self_p); - -// Return true if the expression was valid and compiled without errors. -CZMQ_EXPORT bool - zrex_valid (zrex_t *self); - -// Return the error message generated during compilation of the expression. -CZMQ_EXPORT const char * - zrex_strerror (zrex_t *self); - -// Returns true if the text matches the previously compiled expression. -// Use this method to compare one expression against many strings. -CZMQ_EXPORT bool - zrex_matches (zrex_t *self, const char *text); - -// Returns true if the text matches the supplied expression. Use this -// method to compare one string against several expressions. -CZMQ_EXPORT bool - zrex_eq (zrex_t *self, const char *text, const char *expression); - -// Returns number of hits from last zrex_matches or zrex_eq. If the text -// matched, returns 1 plus the number of capture groups. If the text did -// not match, returns zero. To retrieve individual capture groups, call -// zrex_hit (). -CZMQ_EXPORT int - zrex_hits (zrex_t *self); - -// Returns the Nth capture group from the last expression match, where -// N is 0 to the value returned by zrex_hits(). Capture group 0 is the -// whole matching string. Sequence 1 is the first capture group, if any, -// and so on. -CZMQ_EXPORT const char * - zrex_hit (zrex_t *self, uint index); - -// Fetches hits into string variables provided by caller; this makes for -// nicer code than accessing hits by index. Caller should not modify nor -// free the returned values. Returns number of strings returned. This -// method starts at hit 1, i.e. first capture group, as hit 0 is always -// the original matched string. -CZMQ_EXPORT int - zrex_fetch (zrex_t *self, const char **string_p, ...); - -// Self test of this class -CZMQ_EXPORT void - zrex_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zsock.h b/phonelibs/zmq/aarch64/include/zsock.h deleted file mode 100644 index fc5c46e45e..0000000000 --- a/phonelibs/zmq/aarch64/include/zsock.h +++ /dev/null @@ -1,921 +0,0 @@ -/* ========================================================================= - zsock - high-level socket API that hides libzmq contexts and sockets - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZSOCK_H_INCLUDED__ -#define __ZSOCK_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// This interface includes some smart constructors, which create sockets with -// additional set-up. In all of these, the endpoint is NULL, or starts with -// '@' (bind) or '>' (connect). Multiple endpoints are allowed, separated by -// commas. If endpoint does not start with '@' or '>', default action depends -// on socket type. - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zsock.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// Create a new socket. Returns the new socket, or NULL if the new socket -// could not be created. Note that the symbol zsock_new (and other -// constructors/destructors for zsock) are redirected to the *_checked -// variant, enabling intelligent socket leak detection. This can have -// performance implications if you use a LOT of sockets. To turn off this -// redirection behaviour, define ZSOCK_NOCHECK. -CZMQ_EXPORT zsock_t * - zsock_new (int type); - -// Create a PUB socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_pub (const char *endpoint); - -// Create a SUB socket, and optionally subscribe to some prefix string. Default -// action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_sub (const char *endpoint, const char *subscribe); - -// Create a REQ socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_req (const char *endpoint); - -// Create a REP socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_rep (const char *endpoint); - -// Create a DEALER socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_dealer (const char *endpoint); - -// Create a ROUTER socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_router (const char *endpoint); - -// Create a PUSH socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_push (const char *endpoint); - -// Create a PULL socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_pull (const char *endpoint); - -// Create an XPUB socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_xpub (const char *endpoint); - -// Create an XSUB socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_xsub (const char *endpoint); - -// Create a PAIR socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_pair (const char *endpoint); - -// Create a STREAM socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_stream (const char *endpoint); - -// Destroy the socket. You must use this for any socket created via the -// zsock_new method. -CZMQ_EXPORT void - zsock_destroy (zsock_t **self_p); - -// Bind a socket to a formatted endpoint. For tcp:// endpoints, supports -// ephemeral ports, if you specify the port number as "*". By default -// zsock uses the IANA designated range from C000 (49152) to FFFF (65535). -// To override this range, follow the "*" with "[first-last]". Either or -// both first and last may be empty. To bind to a random port within the -// range, use "!" in place of "*". -// -// Examples: -// tcp://127.0.0.1:* bind to first free port from C000 up -// tcp://127.0.0.1:! bind to random port from C000 to FFFF -// tcp://127.0.0.1:*[60000-] bind to first free port from 60000 up -// tcp://127.0.0.1:![-60000] bind to random port from C000 to 60000 -// tcp://127.0.0.1:![55000-55999] -// bind to random port from 55000 to 55999 -// -// On success, returns the actual port number used, for tcp:// endpoints, -// and 0 for other transports. On failure, returns -1. Note that when using -// ephemeral ports, a port may be reused by different services without -// clients being aware. Protocols that run on ephemeral ports should take -// this into account. -CZMQ_EXPORT int - zsock_bind (zsock_t *self, const char *format, ...); - -// Returns last bound endpoint, if any. -CZMQ_EXPORT const char * - zsock_endpoint (zsock_t *self); - -// Unbind a socket from a formatted endpoint. -// Returns 0 if OK, -1 if the endpoint was invalid or the function -// isn't supported. -CZMQ_EXPORT int - zsock_unbind (zsock_t *self, const char *format, ...); - -// Connect a socket to a formatted endpoint -// Returns 0 if OK, -1 if the endpoint was invalid. -CZMQ_EXPORT int - zsock_connect (zsock_t *self, const char *format, ...); - -// Disconnect a socket from a formatted endpoint -// Returns 0 if OK, -1 if the endpoint was invalid or the function -// isn't supported. -CZMQ_EXPORT int - zsock_disconnect (zsock_t *self, const char *format, ...); - -// Attach a socket to zero or more endpoints. If endpoints is not null, -// parses as list of ZeroMQ endpoints, separated by commas, and prefixed by -// '@' (to bind the socket) or '>' (to connect the socket). Returns 0 if all -// endpoints were valid, or -1 if there was a syntax error. If the endpoint -// does not start with '@' or '>', the serverish argument defines whether -// it is used to bind (serverish = true) or connect (serverish = false). -CZMQ_EXPORT int - zsock_attach (zsock_t *self, const char *endpoints, bool serverish); - -// Returns socket type as printable constant string. -CZMQ_EXPORT const char * - zsock_type_str (zsock_t *self); - -// Send a 'picture' message to the socket (or actor). The picture is a -// string that defines the type of each frame. This makes it easy to send -// a complex multiframe message in one call. The picture can contain any -// of these characters, each corresponding to one or two arguments: -// -// i = int (signed) -// 1 = uint8_t -// 2 = uint16_t -// 4 = uint32_t -// 8 = uint64_t -// s = char * -// b = byte *, size_t (2 arguments) -// c = zchunk_t * -// f = zframe_t * -// h = zhashx_t * -// U = zuuid_t * -// p = void * (sends the pointer value, only meaningful over inproc) -// m = zmsg_t * (sends all frames in the zmsg) -// z = sends zero-sized frame (0 arguments) -// u = uint (deprecated) -// -// Note that s, b, c, and f are encoded the same way and the choice is -// offered as a convenience to the sender, which may or may not already -// have data in a zchunk or zframe. Does not change or take ownership of -// any arguments. Returns 0 if successful, -1 if sending failed for any -// reason. -CZMQ_EXPORT int - zsock_send (void *self, const char *picture, ...); - -// Send a 'picture' message to the socket (or actor). This is a va_list -// version of zsock_send (), so please consult its documentation for the -// details. -CZMQ_EXPORT int - zsock_vsend (void *self, const char *picture, va_list argptr); - -// Receive a 'picture' message to the socket (or actor). See zsock_send for -// the format and meaning of the picture. Returns the picture elements into -// a series of pointers as provided by the caller: -// -// i = int * (stores signed integer) -// 4 = uint32_t * (stores 32-bit unsigned integer) -// 8 = uint64_t * (stores 64-bit unsigned integer) -// s = char ** (allocates new string) -// b = byte **, size_t * (2 arguments) (allocates memory) -// c = zchunk_t ** (creates zchunk) -// f = zframe_t ** (creates zframe) -// U = zuuid_t * (creates a zuuid with the data) -// h = zhashx_t ** (creates zhashx) -// p = void ** (stores pointer) -// m = zmsg_t ** (creates a zmsg with the remaing frames) -// z = null, asserts empty frame (0 arguments) -// u = uint * (stores unsigned integer, deprecated) -// -// Note that zsock_recv creates the returned objects, and the caller must -// destroy them when finished with them. The supplied pointers do not need -// to be initialized. Returns 0 if successful, or -1 if it failed to recv -// a message, in which case the pointers are not modified. When message -// frames are truncated (a short message), sets return values to zero/null. -// If an argument pointer is NULL, does not store any value (skips it). -// An 'n' picture matches an empty frame; if the message does not match, -// the method will return -1. -CZMQ_EXPORT int - zsock_recv (void *self, const char *picture, ...); - -// Receive a 'picture' message from the socket (or actor). This is a -// va_list version of zsock_recv (), so please consult its documentation -// for the details. -CZMQ_EXPORT int - zsock_vrecv (void *self, const char *picture, va_list argptr); - -// Send a binary encoded 'picture' message to the socket (or actor). This -// method is similar to zsock_send, except the arguments are encoded in a -// binary format that is compatible with zproto, and is designed to reduce -// memory allocations. The pattern argument is a string that defines the -// type of each argument. Supports these argument types: -// -// pattern C type zproto type: -// 1 uint8_t type = "number" size = "1" -// 2 uint16_t type = "number" size = "2" -// 4 uint32_t type = "number" size = "3" -// 8 uint64_t type = "number" size = "4" -// s char *, 0-255 chars type = "string" -// S char *, 0-2^32-1 chars type = "longstr" -// c zchunk_t * type = "chunk" -// f zframe_t * type = "frame" -// u zuuid_t * type = "uuid" -// m zmsg_t * type = "msg" -// p void *, sends pointer value, only over inproc -// -// Does not change or take ownership of any arguments. Returns 0 if -// successful, -1 if sending failed for any reason. -CZMQ_EXPORT int - zsock_bsend (void *self, const char *picture, ...); - -// Receive a binary encoded 'picture' message from the socket (or actor). -// This method is similar to zsock_recv, except the arguments are encoded -// in a binary format that is compatible with zproto, and is designed to -// reduce memory allocations. The pattern argument is a string that defines -// the type of each argument. See zsock_bsend for the supported argument -// types. All arguments must be pointers; this call sets them to point to -// values held on a per-socket basis. -// Note that zsock_brecv creates the returned objects, and the caller must -// destroy them when finished with them. The supplied pointers do not need -// to be initialized. Returns 0 if successful, or -1 if it failed to read -// a message. -CZMQ_EXPORT int - zsock_brecv (void *self, const char *picture, ...); - -// Set socket to use unbounded pipes (HWM=0); use this in cases when you are -// totally certain the message volume can fit in memory. This method works -// across all versions of ZeroMQ. Takes a polymorphic socket reference. -CZMQ_EXPORT void - zsock_set_unbounded (void *self); - -// Send a signal over a socket. A signal is a short message carrying a -// success/failure code (by convention, 0 means OK). Signals are encoded -// to be distinguishable from "normal" messages. Accepts a zsock_t or a -// zactor_t argument, and returns 0 if successful, -1 if the signal could -// not be sent. Takes a polymorphic socket reference. -CZMQ_EXPORT int - zsock_signal (void *self, byte status); - -// Wait on a signal. Use this to coordinate between threads, over pipe -// pairs. Blocks until the signal is received. Returns -1 on error, 0 or -// greater on success. Accepts a zsock_t or a zactor_t as argument. -// Takes a polymorphic socket reference. -CZMQ_EXPORT int - zsock_wait (void *self); - -// If there is a partial message still waiting on the socket, remove and -// discard it. This is useful when reading partial messages, to get specific -// message types. -CZMQ_EXPORT void - zsock_flush (void *self); - -// Probe the supplied object, and report if it looks like a zsock_t. -// Takes a polymorphic socket reference. -CZMQ_EXPORT bool - zsock_is (void *self); - -// Probe the supplied reference. If it looks like a zsock_t instance, return -// the underlying libzmq socket handle; else if it looks like a file -// descriptor, return NULL; else if it looks like a libzmq socket handle, -// return the supplied value. Takes a polymorphic socket reference. -CZMQ_EXPORT void * - zsock_resolve (void *self); - -// Get socket option `tos`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_tos (void *self); - -// Set socket option `tos`. -CZMQ_EXPORT void - zsock_set_tos (void *self, int tos); - -// Set socket option `router_handover`. -CZMQ_EXPORT void - zsock_set_router_handover (void *self, int router_handover); - -// Set socket option `router_mandatory`. -CZMQ_EXPORT void - zsock_set_router_mandatory (void *self, int router_mandatory); - -// Set socket option `probe_router`. -CZMQ_EXPORT void - zsock_set_probe_router (void *self, int probe_router); - -// Set socket option `req_relaxed`. -CZMQ_EXPORT void - zsock_set_req_relaxed (void *self, int req_relaxed); - -// Set socket option `req_correlate`. -CZMQ_EXPORT void - zsock_set_req_correlate (void *self, int req_correlate); - -// Set socket option `conflate`. -CZMQ_EXPORT void - zsock_set_conflate (void *self, int conflate); - -// Get socket option `zap_domain`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_zap_domain (void *self); - -// Set socket option `zap_domain`. -CZMQ_EXPORT void - zsock_set_zap_domain (void *self, const char *zap_domain); - -// Get socket option `mechanism`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_mechanism (void *self); - -// Get socket option `plain_server`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_plain_server (void *self); - -// Set socket option `plain_server`. -CZMQ_EXPORT void - zsock_set_plain_server (void *self, int plain_server); - -// Get socket option `plain_username`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_plain_username (void *self); - -// Set socket option `plain_username`. -CZMQ_EXPORT void - zsock_set_plain_username (void *self, const char *plain_username); - -// Get socket option `plain_password`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_plain_password (void *self); - -// Set socket option `plain_password`. -CZMQ_EXPORT void - zsock_set_plain_password (void *self, const char *plain_password); - -// Get socket option `curve_server`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_curve_server (void *self); - -// Set socket option `curve_server`. -CZMQ_EXPORT void - zsock_set_curve_server (void *self, int curve_server); - -// Get socket option `curve_publickey`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_curve_publickey (void *self); - -// Set socket option `curve_publickey`. -CZMQ_EXPORT void - zsock_set_curve_publickey (void *self, const char *curve_publickey); - -// Set socket option `curve_publickey` from 32-octet binary -CZMQ_EXPORT void - zsock_set_curve_publickey_bin (void *self, const byte *curve_publickey); - -// Get socket option `curve_secretkey`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_curve_secretkey (void *self); - -// Set socket option `curve_secretkey`. -CZMQ_EXPORT void - zsock_set_curve_secretkey (void *self, const char *curve_secretkey); - -// Set socket option `curve_secretkey` from 32-octet binary -CZMQ_EXPORT void - zsock_set_curve_secretkey_bin (void *self, const byte *curve_secretkey); - -// Get socket option `curve_serverkey`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_curve_serverkey (void *self); - -// Set socket option `curve_serverkey`. -CZMQ_EXPORT void - zsock_set_curve_serverkey (void *self, const char *curve_serverkey); - -// Set socket option `curve_serverkey` from 32-octet binary -CZMQ_EXPORT void - zsock_set_curve_serverkey_bin (void *self, const byte *curve_serverkey); - -// Get socket option `gssapi_server`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_gssapi_server (void *self); - -// Set socket option `gssapi_server`. -CZMQ_EXPORT void - zsock_set_gssapi_server (void *self, int gssapi_server); - -// Get socket option `gssapi_plaintext`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_gssapi_plaintext (void *self); - -// Set socket option `gssapi_plaintext`. -CZMQ_EXPORT void - zsock_set_gssapi_plaintext (void *self, int gssapi_plaintext); - -// Get socket option `gssapi_principal`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_gssapi_principal (void *self); - -// Set socket option `gssapi_principal`. -CZMQ_EXPORT void - zsock_set_gssapi_principal (void *self, const char *gssapi_principal); - -// Get socket option `gssapi_service_principal`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_gssapi_service_principal (void *self); - -// Set socket option `gssapi_service_principal`. -CZMQ_EXPORT void - zsock_set_gssapi_service_principal (void *self, const char *gssapi_service_principal); - -// Get socket option `ipv6`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_ipv6 (void *self); - -// Set socket option `ipv6`. -CZMQ_EXPORT void - zsock_set_ipv6 (void *self, int ipv6); - -// Get socket option `immediate`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_immediate (void *self); - -// Set socket option `immediate`. -CZMQ_EXPORT void - zsock_set_immediate (void *self, int immediate); - -// Set socket option `router_raw`. -CZMQ_EXPORT void - zsock_set_router_raw (void *self, int router_raw); - -// Get socket option `ipv4only`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_ipv4only (void *self); - -// Set socket option `ipv4only`. -CZMQ_EXPORT void - zsock_set_ipv4only (void *self, int ipv4only); - -// Set socket option `delay_attach_on_connect`. -CZMQ_EXPORT void - zsock_set_delay_attach_on_connect (void *self, int delay_attach_on_connect); - -// Get socket option `type`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_type (void *self); - -// Get socket option `sndhwm`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_sndhwm (void *self); - -// Set socket option `sndhwm`. -CZMQ_EXPORT void - zsock_set_sndhwm (void *self, int sndhwm); - -// Get socket option `rcvhwm`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_rcvhwm (void *self); - -// Set socket option `rcvhwm`. -CZMQ_EXPORT void - zsock_set_rcvhwm (void *self, int rcvhwm); - -// Get socket option `affinity`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_affinity (void *self); - -// Set socket option `affinity`. -CZMQ_EXPORT void - zsock_set_affinity (void *self, int affinity); - -// Set socket option `subscribe`. -CZMQ_EXPORT void - zsock_set_subscribe (void *self, const char *subscribe); - -// Set socket option `unsubscribe`. -CZMQ_EXPORT void - zsock_set_unsubscribe (void *self, const char *unsubscribe); - -// Get socket option `identity`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_identity (void *self); - -// Set socket option `identity`. -CZMQ_EXPORT void - zsock_set_identity (void *self, const char *identity); - -// Get socket option `rate`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_rate (void *self); - -// Set socket option `rate`. -CZMQ_EXPORT void - zsock_set_rate (void *self, int rate); - -// Get socket option `recovery_ivl`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_recovery_ivl (void *self); - -// Set socket option `recovery_ivl`. -CZMQ_EXPORT void - zsock_set_recovery_ivl (void *self, int recovery_ivl); - -// Get socket option `sndbuf`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_sndbuf (void *self); - -// Set socket option `sndbuf`. -CZMQ_EXPORT void - zsock_set_sndbuf (void *self, int sndbuf); - -// Get socket option `rcvbuf`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_rcvbuf (void *self); - -// Set socket option `rcvbuf`. -CZMQ_EXPORT void - zsock_set_rcvbuf (void *self, int rcvbuf); - -// Get socket option `linger`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_linger (void *self); - -// Set socket option `linger`. -CZMQ_EXPORT void - zsock_set_linger (void *self, int linger); - -// Get socket option `reconnect_ivl`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_reconnect_ivl (void *self); - -// Set socket option `reconnect_ivl`. -CZMQ_EXPORT void - zsock_set_reconnect_ivl (void *self, int reconnect_ivl); - -// Get socket option `reconnect_ivl_max`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_reconnect_ivl_max (void *self); - -// Set socket option `reconnect_ivl_max`. -CZMQ_EXPORT void - zsock_set_reconnect_ivl_max (void *self, int reconnect_ivl_max); - -// Get socket option `backlog`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_backlog (void *self); - -// Set socket option `backlog`. -CZMQ_EXPORT void - zsock_set_backlog (void *self, int backlog); - -// Get socket option `maxmsgsize`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_maxmsgsize (void *self); - -// Set socket option `maxmsgsize`. -CZMQ_EXPORT void - zsock_set_maxmsgsize (void *self, int maxmsgsize); - -// Get socket option `multicast_hops`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_multicast_hops (void *self); - -// Set socket option `multicast_hops`. -CZMQ_EXPORT void - zsock_set_multicast_hops (void *self, int multicast_hops); - -// Get socket option `rcvtimeo`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_rcvtimeo (void *self); - -// Set socket option `rcvtimeo`. -CZMQ_EXPORT void - zsock_set_rcvtimeo (void *self, int rcvtimeo); - -// Get socket option `sndtimeo`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_sndtimeo (void *self); - -// Set socket option `sndtimeo`. -CZMQ_EXPORT void - zsock_set_sndtimeo (void *self, int sndtimeo); - -// Set socket option `xpub_verbose`. -CZMQ_EXPORT void - zsock_set_xpub_verbose (void *self, int xpub_verbose); - -// Get socket option `tcp_keepalive`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_tcp_keepalive (void *self); - -// Set socket option `tcp_keepalive`. -CZMQ_EXPORT void - zsock_set_tcp_keepalive (void *self, int tcp_keepalive); - -// Get socket option `tcp_keepalive_idle`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_tcp_keepalive_idle (void *self); - -// Set socket option `tcp_keepalive_idle`. -CZMQ_EXPORT void - zsock_set_tcp_keepalive_idle (void *self, int tcp_keepalive_idle); - -// Get socket option `tcp_keepalive_cnt`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_tcp_keepalive_cnt (void *self); - -// Set socket option `tcp_keepalive_cnt`. -CZMQ_EXPORT void - zsock_set_tcp_keepalive_cnt (void *self, int tcp_keepalive_cnt); - -// Get socket option `tcp_keepalive_intvl`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_tcp_keepalive_intvl (void *self); - -// Set socket option `tcp_keepalive_intvl`. -CZMQ_EXPORT void - zsock_set_tcp_keepalive_intvl (void *self, int tcp_keepalive_intvl); - -// Get socket option `tcp_accept_filter`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_tcp_accept_filter (void *self); - -// Set socket option `tcp_accept_filter`. -CZMQ_EXPORT void - zsock_set_tcp_accept_filter (void *self, const char *tcp_accept_filter); - -// Get socket option `rcvmore`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_rcvmore (void *self); - -// Get socket option `fd`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT SOCKET - zsock_fd (void *self); - -// Get socket option `events`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_events (void *self); - -// Get socket option `last_endpoint`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_last_endpoint (void *self); - -// Self test of this class. -CZMQ_EXPORT void - zsock_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Create a SERVER socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_server (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a CLIENT socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_client (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a RADIO socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_radio (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a DISH socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_dish (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a GATHER socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_gather (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a SCATTER socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_scatter (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Return socket routing ID if any. This returns 0 if the socket is not -// of type ZMQ_SERVER or if no request was already received on it. -CZMQ_EXPORT uint32_t - zsock_routing_id (zsock_t *self); - -// *** Draft method, for development use, may change without warning *** -// Set routing ID on socket. The socket MUST be of type ZMQ_SERVER. -// This will be used when sending messages on the socket via the zsock API. -CZMQ_EXPORT void - zsock_set_routing_id (zsock_t *self, uint32_t routing_id); - -// *** Draft method, for development use, may change without warning *** -// Join a group for the RADIO-DISH pattern. Call only on ZMQ_DISH. -// Returns 0 if OK, -1 if failed. -CZMQ_EXPORT int - zsock_join (void *self, const char *group); - -// *** Draft method, for development use, may change without warning *** -// Leave a group for the RADIO-DISH pattern. Call only on ZMQ_DISH. -// Returns 0 if OK, -1 if failed. -CZMQ_EXPORT int - zsock_leave (void *self, const char *group); - -// *** Draft method, for development use, may change without warning *** -// Get socket option `heartbeat_ivl`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_heartbeat_ivl (void *self); - -// *** Draft method, for development use, may change without warning *** -// Set socket option `heartbeat_ivl`. -CZMQ_EXPORT void - zsock_set_heartbeat_ivl (void *self, int heartbeat_ivl); - -// *** Draft method, for development use, may change without warning *** -// Get socket option `heartbeat_ttl`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_heartbeat_ttl (void *self); - -// *** Draft method, for development use, may change without warning *** -// Set socket option `heartbeat_ttl`. -CZMQ_EXPORT void - zsock_set_heartbeat_ttl (void *self, int heartbeat_ttl); - -// *** Draft method, for development use, may change without warning *** -// Get socket option `heartbeat_timeout`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_heartbeat_timeout (void *self); - -// *** Draft method, for development use, may change without warning *** -// Set socket option `heartbeat_timeout`. -CZMQ_EXPORT void - zsock_set_heartbeat_timeout (void *self, int heartbeat_timeout); - -// *** Draft method, for development use, may change without warning *** -// Get socket option `use_fd`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_use_fd (void *self); - -// *** Draft method, for development use, may change without warning *** -// Set socket option `use_fd`. -CZMQ_EXPORT void - zsock_set_use_fd (void *self, int use_fd); - -#endif // CZMQ_BUILD_DRAFT_API -// @ignore -CZMQ_EXPORT int - zsock_bind (zsock_t *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int - zsock_unbind (zsock_t *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int - zsock_connect (zsock_t *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int - zsock_disconnect (zsock_t *self, const char *format, ...) CHECK_PRINTF (2); -// @end - - -// zsock leak detection - not a part of the official interface to zsock. This -// enables CZMQ to report socket leaks intelligently. -#if defined ZSOCK_NOCHECK - // no checking active - use the above interface methods directly. -#else -# define zsock_new(t) zsock_new_checked((t), __FILE__, __LINE__) -# define zsock_new_pub(e) zsock_new_pub_checked((e), __FILE__, __LINE__) -# define zsock_new_sub(e,s) zsock_new_sub_checked((e), (s), __FILE__, __LINE__) -# define zsock_new_req(e) zsock_new_req_checked((e), __FILE__, __LINE__) -# define zsock_new_rep(e) zsock_new_rep_checked((e), __FILE__, __LINE__) -# define zsock_new_dealer(e) zsock_new_dealer_checked((e), __FILE__, __LINE__) -# define zsock_new_router(e) zsock_new_router_checked((e), __FILE__, __LINE__) -# define zsock_new_pull(e) zsock_new_pull_checked((e), __FILE__, __LINE__) -# define zsock_new_push(e) zsock_new_push_checked((e), __FILE__, __LINE__) -# define zsock_new_xpub(e) zsock_new_xpub_checked((e), __FILE__, __LINE__) -# define zsock_new_xsub(e) zsock_new_xsub_checked((e), __FILE__, __LINE__) -# define zsock_new_pair(e) zsock_new_pair_checked((e), __FILE__, __LINE__) -# define zsock_new_stream(e) zsock_new_stream_checked((e), __FILE__, __LINE__) -# define zsock_destroy(t) zsock_destroy_checked((t), __FILE__, __LINE__) -#endif - -CZMQ_EXPORT zsock_t * - zsock_new_checked (int type, const char *filename, size_t line_nbr); - -CZMQ_EXPORT void - zsock_destroy_checked (zsock_t **self_p, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_pub_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_sub_checked (const char *endpoint, const char *subscribe, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_req_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_rep_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_dealer_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_router_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_push_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_pull_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_xpub_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_xsub_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_pair_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_stream_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_server_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_client_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_radio_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_dish_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_gather_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_scatter_checked (const char *endpoint, const char *filename, size_t line_nbr); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zsocket.h b/phonelibs/zmq/aarch64/include/zsocket.h deleted file mode 100644 index a60a0d9db3..0000000000 --- a/phonelibs/zmq/aarch64/include/zsocket.h +++ /dev/null @@ -1,110 +0,0 @@ -/* ========================================================================= - zsocket - working with 0MQ sockets - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZSOCKET_H_INCLUDED__ -#define __ZSOCKET_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// This port range is defined by IANA for dynamic or private ports -// We use this when choosing a port for dynamic binding. -#define ZSOCKET_DYNFROM 0xc000 -#define ZSOCKET_DYNTO 0xffff - -// Callback function for zero-copy methods -typedef void (zsocket_free_fn) (void *data, void *arg); - -// Create a new socket within our CZMQ context, replaces zmq_socket. -// Use this to get automatic management of the socket at shutdown. -// Note: SUB sockets do not automatically subscribe to everything; you -// must set filters explicitly. -CZMQ_EXPORT void * - zsocket_new (zctx_t *self, int type); - -// Destroy a socket within our CZMQ context, replaces zmq_close. -CZMQ_EXPORT void - zsocket_destroy (zctx_t *ctx, void *self); - -// Bind a socket to a formatted endpoint. If the port is specified as -// '*', binds to any free port from ZSOCKET_DYNFROM to ZSOCKET_DYNTO -// and returns the actual port number used. Otherwise asserts that the -// bind succeeded with the specified port number. Always returns the -// port number if successful. -CZMQ_EXPORT int - zsocket_bind (void *self, const char *format, ...); - -// Unbind a socket from a formatted endpoint. -// Returns 0 if OK, -1 if the endpoint was invalid or the function -// isn't supported. -CZMQ_EXPORT int - zsocket_unbind (void *self, const char *format, ...); - -// Connect a socket to a formatted endpoint -// Returns 0 if OK, -1 if the endpoint was invalid. -CZMQ_EXPORT int - zsocket_connect (void *self, const char *format, ...); - -// Disconnect a socket from a formatted endpoint -// Returns 0 if OK, -1 if the endpoint was invalid or the function -// isn't supported. -CZMQ_EXPORT int - zsocket_disconnect (void *self, const char *format, ...); - -// Poll for input events on the socket. Returns TRUE if there is input -// ready on the socket, else FALSE. -CZMQ_EXPORT bool - zsocket_poll (void *self, int msecs); - -// Returns socket type as printable constant string -CZMQ_EXPORT const char * - zsocket_type_str (void *self); - -// Send data over a socket as a single message frame. -// Accepts these flags: ZFRAME_MORE and ZFRAME_DONTWAIT. -// Returns -1 on error, 0 on success -CZMQ_EXPORT int - zsocket_sendmem (void *self, const void *data, size_t size, int flags); - -// Send a signal over a socket. A signal is a zero-byte message. -// Signals are used primarily between threads, over pipe sockets. -// Returns -1 if there was an error sending the signal. -CZMQ_EXPORT int - zsocket_signal (void *self); - -// Wait on a signal. Use this to coordinate between threads, over -// pipe pairs. Returns -1 on error, 0 on success. -CZMQ_EXPORT int - zsocket_wait (void *self); - -// Self test of this class -CZMQ_EXPORT void - zsocket_test (bool verbose); -// @end - -// Compiler hints -CZMQ_EXPORT int zsocket_bind (void *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int zsocket_unbind (void *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int zsocket_connect (void *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int zsocket_disconnect (void *self, const char *format, ...) CHECK_PRINTF (2); - -// Emulation of widely-used 2.x socket options -CZMQ_EXPORT void zsocket_set_hwm (void *self, int hwm); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zsockopt.h b/phonelibs/zmq/aarch64/include/zsockopt.h deleted file mode 100644 index 5246986dd0..0000000000 --- a/phonelibs/zmq/aarch64/include/zsockopt.h +++ /dev/null @@ -1,256 +0,0 @@ -/* ========================================================================= - zsockopt - get/set 0MQ socket options (deprecated) - - **************************************************** - * GENERATED SOURCE CODE, DO NOT EDIT!! * - * TO CHANGE THIS, EDIT src/zsockopt.gsl * - * AND RUN `gsl sockopts` in src/. * - **************************************************** - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZSOCKOPT_H_INCLUDED__ -#define __ZSOCKOPT_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -#if (ZMQ_VERSION_MAJOR == 4) -// Get socket options -CZMQ_EXPORT int zsocket_heartbeat_ivl (void *zocket); -CZMQ_EXPORT int zsocket_heartbeat_ttl (void *zocket); -CZMQ_EXPORT int zsocket_heartbeat_timeout (void *zocket); -CZMQ_EXPORT int zsocket_use_fd (void *zocket); -CZMQ_EXPORT int zsocket_tos (void *zocket); -CZMQ_EXPORT char * zsocket_zap_domain (void *zocket); -CZMQ_EXPORT int zsocket_mechanism (void *zocket); -CZMQ_EXPORT int zsocket_plain_server (void *zocket); -CZMQ_EXPORT char * zsocket_plain_username (void *zocket); -CZMQ_EXPORT char * zsocket_plain_password (void *zocket); -CZMQ_EXPORT int zsocket_curve_server (void *zocket); -CZMQ_EXPORT char * zsocket_curve_publickey (void *zocket); -CZMQ_EXPORT char * zsocket_curve_secretkey (void *zocket); -CZMQ_EXPORT char * zsocket_curve_serverkey (void *zocket); -CZMQ_EXPORT int zsocket_gssapi_server (void *zocket); -CZMQ_EXPORT int zsocket_gssapi_plaintext (void *zocket); -CZMQ_EXPORT char * zsocket_gssapi_principal (void *zocket); -CZMQ_EXPORT char * zsocket_gssapi_service_principal (void *zocket); -CZMQ_EXPORT int zsocket_ipv6 (void *zocket); -CZMQ_EXPORT int zsocket_immediate (void *zocket); -CZMQ_EXPORT int zsocket_ipv4only (void *zocket); -CZMQ_EXPORT int zsocket_type (void *zocket); -CZMQ_EXPORT int zsocket_sndhwm (void *zocket); -CZMQ_EXPORT int zsocket_rcvhwm (void *zocket); -CZMQ_EXPORT int zsocket_affinity (void *zocket); -CZMQ_EXPORT char * zsocket_identity (void *zocket); -CZMQ_EXPORT int zsocket_rate (void *zocket); -CZMQ_EXPORT int zsocket_recovery_ivl (void *zocket); -CZMQ_EXPORT int zsocket_sndbuf (void *zocket); -CZMQ_EXPORT int zsocket_rcvbuf (void *zocket); -CZMQ_EXPORT int zsocket_linger (void *zocket); -CZMQ_EXPORT int zsocket_reconnect_ivl (void *zocket); -CZMQ_EXPORT int zsocket_reconnect_ivl_max (void *zocket); -CZMQ_EXPORT int zsocket_backlog (void *zocket); -CZMQ_EXPORT int zsocket_maxmsgsize (void *zocket); -CZMQ_EXPORT int zsocket_multicast_hops (void *zocket); -CZMQ_EXPORT int zsocket_rcvtimeo (void *zocket); -CZMQ_EXPORT int zsocket_sndtimeo (void *zocket); -CZMQ_EXPORT int zsocket_tcp_keepalive (void *zocket); -CZMQ_EXPORT int zsocket_tcp_keepalive_idle (void *zocket); -CZMQ_EXPORT int zsocket_tcp_keepalive_cnt (void *zocket); -CZMQ_EXPORT int zsocket_tcp_keepalive_intvl (void *zocket); -CZMQ_EXPORT char * zsocket_tcp_accept_filter (void *zocket); -CZMQ_EXPORT int zsocket_rcvmore (void *zocket); -CZMQ_EXPORT SOCKET zsocket_fd (void *zocket); -CZMQ_EXPORT int zsocket_events (void *zocket); -CZMQ_EXPORT char * zsocket_last_endpoint (void *zocket); - -// Set socket options -CZMQ_EXPORT void zsocket_set_heartbeat_ivl (void *zocket, int heartbeat_ivl); -CZMQ_EXPORT void zsocket_set_heartbeat_ttl (void *zocket, int heartbeat_ttl); -CZMQ_EXPORT void zsocket_set_heartbeat_timeout (void *zocket, int heartbeat_timeout); -CZMQ_EXPORT void zsocket_set_use_fd (void *zocket, int use_fd); -CZMQ_EXPORT void zsocket_set_tos (void *zocket, int tos); -CZMQ_EXPORT void zsocket_set_router_handover (void *zocket, int router_handover); -CZMQ_EXPORT void zsocket_set_router_mandatory (void *zocket, int router_mandatory); -CZMQ_EXPORT void zsocket_set_probe_router (void *zocket, int probe_router); -CZMQ_EXPORT void zsocket_set_req_relaxed (void *zocket, int req_relaxed); -CZMQ_EXPORT void zsocket_set_req_correlate (void *zocket, int req_correlate); -CZMQ_EXPORT void zsocket_set_conflate (void *zocket, int conflate); -CZMQ_EXPORT void zsocket_set_zap_domain (void *zocket, const char * zap_domain); -CZMQ_EXPORT void zsocket_set_plain_server (void *zocket, int plain_server); -CZMQ_EXPORT void zsocket_set_plain_username (void *zocket, const char * plain_username); -CZMQ_EXPORT void zsocket_set_plain_password (void *zocket, const char * plain_password); -CZMQ_EXPORT void zsocket_set_curve_server (void *zocket, int curve_server); -CZMQ_EXPORT void zsocket_set_curve_publickey (void *zocket, const char * curve_publickey); -CZMQ_EXPORT void zsocket_set_curve_publickey_bin (void *zocket, const byte *curve_publickey); -CZMQ_EXPORT void zsocket_set_curve_secretkey (void *zocket, const char * curve_secretkey); -CZMQ_EXPORT void zsocket_set_curve_secretkey_bin (void *zocket, const byte *curve_secretkey); -CZMQ_EXPORT void zsocket_set_curve_serverkey (void *zocket, const char * curve_serverkey); -CZMQ_EXPORT void zsocket_set_curve_serverkey_bin (void *zocket, const byte *curve_serverkey); -CZMQ_EXPORT void zsocket_set_gssapi_server (void *zocket, int gssapi_server); -CZMQ_EXPORT void zsocket_set_gssapi_plaintext (void *zocket, int gssapi_plaintext); -CZMQ_EXPORT void zsocket_set_gssapi_principal (void *zocket, const char * gssapi_principal); -CZMQ_EXPORT void zsocket_set_gssapi_service_principal (void *zocket, const char * gssapi_service_principal); -CZMQ_EXPORT void zsocket_set_ipv6 (void *zocket, int ipv6); -CZMQ_EXPORT void zsocket_set_immediate (void *zocket, int immediate); -CZMQ_EXPORT void zsocket_set_router_raw (void *zocket, int router_raw); -CZMQ_EXPORT void zsocket_set_ipv4only (void *zocket, int ipv4only); -CZMQ_EXPORT void zsocket_set_delay_attach_on_connect (void *zocket, int delay_attach_on_connect); -CZMQ_EXPORT void zsocket_set_sndhwm (void *zocket, int sndhwm); -CZMQ_EXPORT void zsocket_set_rcvhwm (void *zocket, int rcvhwm); -CZMQ_EXPORT void zsocket_set_affinity (void *zocket, int affinity); -CZMQ_EXPORT void zsocket_set_subscribe (void *zocket, const char * subscribe); -CZMQ_EXPORT void zsocket_set_unsubscribe (void *zocket, const char * unsubscribe); -CZMQ_EXPORT void zsocket_set_identity (void *zocket, const char * identity); -CZMQ_EXPORT void zsocket_set_rate (void *zocket, int rate); -CZMQ_EXPORT void zsocket_set_recovery_ivl (void *zocket, int recovery_ivl); -CZMQ_EXPORT void zsocket_set_sndbuf (void *zocket, int sndbuf); -CZMQ_EXPORT void zsocket_set_rcvbuf (void *zocket, int rcvbuf); -CZMQ_EXPORT void zsocket_set_linger (void *zocket, int linger); -CZMQ_EXPORT void zsocket_set_reconnect_ivl (void *zocket, int reconnect_ivl); -CZMQ_EXPORT void zsocket_set_reconnect_ivl_max (void *zocket, int reconnect_ivl_max); -CZMQ_EXPORT void zsocket_set_backlog (void *zocket, int backlog); -CZMQ_EXPORT void zsocket_set_maxmsgsize (void *zocket, int maxmsgsize); -CZMQ_EXPORT void zsocket_set_multicast_hops (void *zocket, int multicast_hops); -CZMQ_EXPORT void zsocket_set_rcvtimeo (void *zocket, int rcvtimeo); -CZMQ_EXPORT void zsocket_set_sndtimeo (void *zocket, int sndtimeo); -CZMQ_EXPORT void zsocket_set_xpub_verbose (void *zocket, int xpub_verbose); -CZMQ_EXPORT void zsocket_set_tcp_keepalive (void *zocket, int tcp_keepalive); -CZMQ_EXPORT void zsocket_set_tcp_keepalive_idle (void *zocket, int tcp_keepalive_idle); -CZMQ_EXPORT void zsocket_set_tcp_keepalive_cnt (void *zocket, int tcp_keepalive_cnt); -CZMQ_EXPORT void zsocket_set_tcp_keepalive_intvl (void *zocket, int tcp_keepalive_intvl); -CZMQ_EXPORT void zsocket_set_tcp_accept_filter (void *zocket, const char * tcp_accept_filter); -#endif - -#if (ZMQ_VERSION_MAJOR == 3) -// Get socket options -CZMQ_EXPORT int zsocket_ipv4only (void *zocket); -CZMQ_EXPORT int zsocket_type (void *zocket); -CZMQ_EXPORT int zsocket_sndhwm (void *zocket); -CZMQ_EXPORT int zsocket_rcvhwm (void *zocket); -CZMQ_EXPORT int zsocket_affinity (void *zocket); -CZMQ_EXPORT char * zsocket_identity (void *zocket); -CZMQ_EXPORT int zsocket_rate (void *zocket); -CZMQ_EXPORT int zsocket_recovery_ivl (void *zocket); -CZMQ_EXPORT int zsocket_sndbuf (void *zocket); -CZMQ_EXPORT int zsocket_rcvbuf (void *zocket); -CZMQ_EXPORT int zsocket_linger (void *zocket); -CZMQ_EXPORT int zsocket_reconnect_ivl (void *zocket); -CZMQ_EXPORT int zsocket_reconnect_ivl_max (void *zocket); -CZMQ_EXPORT int zsocket_backlog (void *zocket); -CZMQ_EXPORT int zsocket_maxmsgsize (void *zocket); -CZMQ_EXPORT int zsocket_multicast_hops (void *zocket); -CZMQ_EXPORT int zsocket_rcvtimeo (void *zocket); -CZMQ_EXPORT int zsocket_sndtimeo (void *zocket); -CZMQ_EXPORT int zsocket_tcp_keepalive (void *zocket); -CZMQ_EXPORT int zsocket_tcp_keepalive_idle (void *zocket); -CZMQ_EXPORT int zsocket_tcp_keepalive_cnt (void *zocket); -CZMQ_EXPORT int zsocket_tcp_keepalive_intvl (void *zocket); -CZMQ_EXPORT char * zsocket_tcp_accept_filter (void *zocket); -CZMQ_EXPORT int zsocket_rcvmore (void *zocket); -CZMQ_EXPORT SOCKET zsocket_fd (void *zocket); -CZMQ_EXPORT int zsocket_events (void *zocket); -CZMQ_EXPORT char * zsocket_last_endpoint (void *zocket); - -// Set socket options -CZMQ_EXPORT void zsocket_set_router_raw (void *zocket, int router_raw); -CZMQ_EXPORT void zsocket_set_ipv4only (void *zocket, int ipv4only); -CZMQ_EXPORT void zsocket_set_delay_attach_on_connect (void *zocket, int delay_attach_on_connect); -CZMQ_EXPORT void zsocket_set_sndhwm (void *zocket, int sndhwm); -CZMQ_EXPORT void zsocket_set_rcvhwm (void *zocket, int rcvhwm); -CZMQ_EXPORT void zsocket_set_affinity (void *zocket, int affinity); -CZMQ_EXPORT void zsocket_set_subscribe (void *zocket, const char * subscribe); -CZMQ_EXPORT void zsocket_set_unsubscribe (void *zocket, const char * unsubscribe); -CZMQ_EXPORT void zsocket_set_identity (void *zocket, const char * identity); -CZMQ_EXPORT void zsocket_set_rate (void *zocket, int rate); -CZMQ_EXPORT void zsocket_set_recovery_ivl (void *zocket, int recovery_ivl); -CZMQ_EXPORT void zsocket_set_sndbuf (void *zocket, int sndbuf); -CZMQ_EXPORT void zsocket_set_rcvbuf (void *zocket, int rcvbuf); -CZMQ_EXPORT void zsocket_set_linger (void *zocket, int linger); -CZMQ_EXPORT void zsocket_set_reconnect_ivl (void *zocket, int reconnect_ivl); -CZMQ_EXPORT void zsocket_set_reconnect_ivl_max (void *zocket, int reconnect_ivl_max); -CZMQ_EXPORT void zsocket_set_backlog (void *zocket, int backlog); -CZMQ_EXPORT void zsocket_set_maxmsgsize (void *zocket, int maxmsgsize); -CZMQ_EXPORT void zsocket_set_multicast_hops (void *zocket, int multicast_hops); -CZMQ_EXPORT void zsocket_set_rcvtimeo (void *zocket, int rcvtimeo); -CZMQ_EXPORT void zsocket_set_sndtimeo (void *zocket, int sndtimeo); -CZMQ_EXPORT void zsocket_set_xpub_verbose (void *zocket, int xpub_verbose); -CZMQ_EXPORT void zsocket_set_tcp_keepalive (void *zocket, int tcp_keepalive); -CZMQ_EXPORT void zsocket_set_tcp_keepalive_idle (void *zocket, int tcp_keepalive_idle); -CZMQ_EXPORT void zsocket_set_tcp_keepalive_cnt (void *zocket, int tcp_keepalive_cnt); -CZMQ_EXPORT void zsocket_set_tcp_keepalive_intvl (void *zocket, int tcp_keepalive_intvl); -CZMQ_EXPORT void zsocket_set_tcp_accept_filter (void *zocket, const char * tcp_accept_filter); -#endif - -#if (ZMQ_VERSION_MAJOR == 2) -// Get socket options -CZMQ_EXPORT int zsocket_hwm (void *zocket); -CZMQ_EXPORT int zsocket_swap (void *zocket); -CZMQ_EXPORT int zsocket_affinity (void *zocket); -CZMQ_EXPORT char * zsocket_identity (void *zocket); -CZMQ_EXPORT int zsocket_rate (void *zocket); -CZMQ_EXPORT int zsocket_recovery_ivl (void *zocket); -CZMQ_EXPORT int zsocket_recovery_ivl_msec (void *zocket); -CZMQ_EXPORT int zsocket_mcast_loop (void *zocket); -# if (ZMQ_VERSION_MINOR == 2) -CZMQ_EXPORT int zsocket_rcvtimeo (void *zocket); -# endif -# if (ZMQ_VERSION_MINOR == 2) -CZMQ_EXPORT int zsocket_sndtimeo (void *zocket); -# endif -CZMQ_EXPORT int zsocket_sndbuf (void *zocket); -CZMQ_EXPORT int zsocket_rcvbuf (void *zocket); -CZMQ_EXPORT int zsocket_linger (void *zocket); -CZMQ_EXPORT int zsocket_reconnect_ivl (void *zocket); -CZMQ_EXPORT int zsocket_reconnect_ivl_max (void *zocket); -CZMQ_EXPORT int zsocket_backlog (void *zocket); -CZMQ_EXPORT int zsocket_type (void *zocket); -CZMQ_EXPORT int zsocket_rcvmore (void *zocket); -CZMQ_EXPORT SOCKET zsocket_fd (void *zocket); -CZMQ_EXPORT int zsocket_events (void *zocket); - -// Set socket options -CZMQ_EXPORT void zsocket_set_hwm (void *zocket, int hwm); -CZMQ_EXPORT void zsocket_set_swap (void *zocket, int swap); -CZMQ_EXPORT void zsocket_set_affinity (void *zocket, int affinity); -CZMQ_EXPORT void zsocket_set_identity (void *zocket, const char * identity); -CZMQ_EXPORT void zsocket_set_rate (void *zocket, int rate); -CZMQ_EXPORT void zsocket_set_recovery_ivl (void *zocket, int recovery_ivl); -CZMQ_EXPORT void zsocket_set_recovery_ivl_msec (void *zocket, int recovery_ivl_msec); -CZMQ_EXPORT void zsocket_set_mcast_loop (void *zocket, int mcast_loop); -# if (ZMQ_VERSION_MINOR == 2) -CZMQ_EXPORT void zsocket_set_rcvtimeo (void *zocket, int rcvtimeo); -# endif -# if (ZMQ_VERSION_MINOR == 2) -CZMQ_EXPORT void zsocket_set_sndtimeo (void *zocket, int sndtimeo); -# endif -CZMQ_EXPORT void zsocket_set_sndbuf (void *zocket, int sndbuf); -CZMQ_EXPORT void zsocket_set_rcvbuf (void *zocket, int rcvbuf); -CZMQ_EXPORT void zsocket_set_linger (void *zocket, int linger); -CZMQ_EXPORT void zsocket_set_reconnect_ivl (void *zocket, int reconnect_ivl); -CZMQ_EXPORT void zsocket_set_reconnect_ivl_max (void *zocket, int reconnect_ivl_max); -CZMQ_EXPORT void zsocket_set_backlog (void *zocket, int backlog); -CZMQ_EXPORT void zsocket_set_subscribe (void *zocket, const char * subscribe); -CZMQ_EXPORT void zsocket_set_unsubscribe (void *zocket, const char * unsubscribe); -#endif - -// Self test of this class -CZMQ_EXPORT void zsockopt_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zstr.h b/phonelibs/zmq/aarch64/include/zstr.h deleted file mode 100644 index 3d3f1a862a..0000000000 --- a/phonelibs/zmq/aarch64/include/zstr.h +++ /dev/null @@ -1,115 +0,0 @@ -/* ========================================================================= - zstr - sending and receiving strings - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZSTR_H_INCLUDED__ -#define __ZSTR_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zstr.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// Receive C string from socket. Caller must free returned string using -// zstr_free(). Returns NULL if the context is being terminated or the -// process was interrupted. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zstr_recv (void *source); - -// Receive a series of strings (until NULL) from multipart data. -// Each string is allocated and filled with string data; if there -// are not enough frames, unallocated strings are set to NULL. -// Returns -1 if the message could not be read, else returns the -// number of strings filled, zero or more. Free each returned string -// using zstr_free(). If not enough strings are provided, remaining -// multipart frames in the message are dropped. -CZMQ_EXPORT int - zstr_recvx (void *source, char **string_p, ...); - -// Send a C string to a socket, as a frame. The string is sent without -// trailing null byte; to read this you can use zstr_recv, or a similar -// method that adds a null terminator on the received string. String -// may be NULL, which is sent as "". -CZMQ_EXPORT int - zstr_send (void *dest, const char *string); - -// Send a C string to a socket, as zstr_send(), with a MORE flag, so that -// you can send further strings in the same multi-part message. -CZMQ_EXPORT int - zstr_sendm (void *dest, const char *string); - -// Send a formatted string to a socket. Note that you should NOT use -// user-supplied strings in the format (they may contain '%' which -// will create security holes). -CZMQ_EXPORT int - zstr_sendf (void *dest, const char *format, ...); - -// Send a formatted string to a socket, as for zstr_sendf(), with a -// MORE flag, so that you can send further strings in the same multi-part -// message. -CZMQ_EXPORT int - zstr_sendfm (void *dest, const char *format, ...); - -// Send a series of strings (until NULL) as multipart data -// Returns 0 if the strings could be sent OK, or -1 on error. -CZMQ_EXPORT int - zstr_sendx (void *dest, const char *string, ...); - -// Free a provided string, and nullify the parent pointer. Safe to call on -// a null pointer. -CZMQ_EXPORT void - zstr_free (char **string_p); - -// Self test of this class. -CZMQ_EXPORT void - zstr_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Accepts a void pointer and returns a fresh character string. If source -// is null, returns an empty string. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zstr_str (void *source); - -#endif // CZMQ_BUILD_DRAFT_API -// @ignore -CZMQ_EXPORT int - zstr_sendf (void *dest, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int - zstr_sendfm (void *dest, const char *format, ...) CHECK_PRINTF (2); -// @end - - -// DEPRECATED as poor style -- callers should use zloop or zpoller -// Receive C string from socket, if socket had input ready. Caller must -// free returned string using zstr_free. Returns NULL if there was no input -// waiting, or if the context was terminated. Use zctx_interrupted to exit -// any loop that relies on this method. -CZMQ_EXPORT char * - zstr_recv_nowait (void *source); - -// Compiler hints -CZMQ_EXPORT int zstr_sendf (void *dest, const char *format, ...) CHECK_PRINTF (2); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zsys.h b/phonelibs/zmq/aarch64/include/zsys.h deleted file mode 100644 index 97f88a9555..0000000000 --- a/phonelibs/zmq/aarch64/include/zsys.h +++ /dev/null @@ -1,386 +0,0 @@ -/* ========================================================================= - zsys - system-level methods - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZSYS_H_INCLUDED__ -#define __ZSYS_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -#define UDP_FRAME_MAX 255 // Max size of UDP frame - -// Callback for interrupt signal handler -typedef void (zsys_handler_fn) (int signal_value); - -// Initialize CZMQ zsys layer; this happens automatically when you create -// a socket or an actor; however this call lets you force initialization -// earlier, so e.g. logging is properly set-up before you start working. -// Not threadsafe, so call only from main thread. Safe to call multiple -// times. Returns global CZMQ context. -CZMQ_EXPORT void * - zsys_init (void); - -// Optionally shut down the CZMQ zsys layer; this normally happens automatically -// when the process exits; however this call lets you force a shutdown -// earlier, avoiding any potential problems with atexit() ordering, especially -// with Windows dlls. -CZMQ_EXPORT void - zsys_shutdown (void); - -// Get a new ZMQ socket, automagically creating a ZMQ context if this is -// the first time. Caller is responsible for destroying the ZMQ socket -// before process exits, to avoid a ZMQ deadlock. Note: you should not use -// this method in CZMQ apps, use zsock_new() instead. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT void * - zsys_socket (int type, const char *filename, size_t line_nbr); - -// Destroy/close a ZMQ socket. You should call this for every socket you -// create using zsys_socket(). -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT int - zsys_close (void *handle, const char *filename, size_t line_nbr); - -// Return ZMQ socket name for socket type -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT char * - zsys_sockname (int socktype); - -// Create a pipe, which consists of two PAIR sockets connected over inproc. -// The pipe is configured to use the zsys_pipehwm setting. Returns the -// frontend socket successful, NULL if failed. -CZMQ_EXPORT zsock_t * - zsys_create_pipe (zsock_t **backend_p); - -// Set interrupt handler; this saves the default handlers so that a -// zsys_handler_reset () can restore them. If you call this multiple times -// then the last handler will take affect. If handler_fn is NULL, disables -// default SIGINT/SIGTERM handling in CZMQ. -CZMQ_EXPORT void - zsys_handler_set (zsys_handler_fn *handler_fn); - -// Reset interrupt handler, call this at exit if needed -CZMQ_EXPORT void - zsys_handler_reset (void); - -// Set default interrupt handler, so Ctrl-C or SIGTERM will set -// zsys_interrupted. Idempotent; safe to call multiple times. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT void - zsys_catch_interrupts (void); - -// Return 1 if file exists, else zero -CZMQ_EXPORT bool - zsys_file_exists (const char *filename); - -// Return size of file, or -1 if not found -CZMQ_EXPORT ssize_t - zsys_file_size (const char *filename); - -// Return file modification time. Returns 0 if the file does not exist. -CZMQ_EXPORT time_t - zsys_file_modified (const char *filename); - -// Return file mode; provides at least support for the POSIX S_ISREG(m) -// and S_ISDIR(m) macros and the S_IRUSR and S_IWUSR bits, on all boxes. -// Returns a mode_t cast to int, or -1 in case of error. -CZMQ_EXPORT int - zsys_file_mode (const char *filename); - -// Delete file. Does not complain if the file is absent -CZMQ_EXPORT int - zsys_file_delete (const char *filename); - -// Check if file is 'stable' -CZMQ_EXPORT bool - zsys_file_stable (const char *filename); - -// Create a file path if it doesn't exist. The file path is treated as a -// printf format. -CZMQ_EXPORT int - zsys_dir_create (const char *pathname, ...); - -// Remove a file path if empty; the pathname is treated as printf format. -CZMQ_EXPORT int - zsys_dir_delete (const char *pathname, ...); - -// Move to a specified working directory. Returns 0 if OK, -1 if this failed. -CZMQ_EXPORT int - zsys_dir_change (const char *pathname); - -// Set private file creation mode; all files created from here will be -// readable/writable by the owner only. -CZMQ_EXPORT void - zsys_file_mode_private (void); - -// Reset default file creation mode; all files created from here will use -// process file mode defaults. -CZMQ_EXPORT void - zsys_file_mode_default (void); - -// Return the CZMQ version for run-time API detection; returns version -// number into provided fields, providing reference isn't null in each case. -CZMQ_EXPORT void - zsys_version (int *major, int *minor, int *patch); - -// Format a string using printf formatting, returning a freshly allocated -// buffer. If there was insufficient memory, returns NULL. Free the returned -// string using zstr_free(). -CZMQ_EXPORT char * - zsys_sprintf (const char *format, ...); - -// Format a string with a va_list argument, returning a freshly allocated -// buffer. If there was insufficient memory, returns NULL. Free the returned -// string using zstr_free(). -CZMQ_EXPORT char * - zsys_vprintf (const char *format, va_list argptr); - -// Create UDP beacon socket; if the routable option is true, uses -// multicast (not yet implemented), else uses broadcast. This method -// and related ones might _eventually_ be moved to a zudp class. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT SOCKET - zsys_udp_new (bool routable); - -// Close a UDP socket -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT int - zsys_udp_close (SOCKET handle); - -// Send zframe to UDP socket, return -1 if sending failed due to -// interface having disappeared (happens easily with WiFi) -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT int - zsys_udp_send (SOCKET udpsock, zframe_t *frame, inaddr_t *address, int addrlen); - -// Receive zframe from UDP socket, and set address of peer that sent it -// The peername must be a char [INET_ADDRSTRLEN] array. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT zframe_t * - zsys_udp_recv (SOCKET udpsock, char *peername, int peerlen); - -// Handle an I/O error on some socket operation; will report and die on -// fatal errors, and continue silently on "try again" errors. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT void - zsys_socket_error (const char *reason); - -// Return current host name, for use in public tcp:// endpoints. Caller gets -// a freshly allocated string, should free it using zstr_free(). If the host -// name is not resolvable, returns NULL. -CZMQ_EXPORT char * - zsys_hostname (void); - -// Move the current process into the background. The precise effect depends -// on the operating system. On POSIX boxes, moves to a specified working -// directory (if specified), closes all file handles, reopens stdin, stdout, -// and stderr to the null device, and sets the process to ignore SIGHUP. On -// Windows, does nothing. Returns 0 if OK, -1 if there was an error. -CZMQ_EXPORT int - zsys_daemonize (const char *workdir); - -// Drop the process ID into the lockfile, with exclusive lock, and switch -// the process to the specified group and/or user. Any of the arguments -// may be null, indicating a no-op. Returns 0 on success, -1 on failure. -// Note if you combine this with zsys_daemonize, run after, not before -// that method, or the lockfile will hold the wrong process ID. -CZMQ_EXPORT int - zsys_run_as (const char *lockfile, const char *group, const char *user); - -// Returns true if the underlying libzmq supports CURVE security. -// Uses a heuristic probe according to the version of libzmq being used. -CZMQ_EXPORT bool - zsys_has_curve (void); - -// Configure the number of I/O threads that ZeroMQ will use. A good -// rule of thumb is one thread per gigabit of traffic in or out. The -// default is 1, sufficient for most applications. If the environment -// variable ZSYS_IO_THREADS is defined, that provides the default. -// Note that this method is valid only before any socket is created. -CZMQ_EXPORT void - zsys_set_io_threads (size_t io_threads); - -// Configure the number of sockets that ZeroMQ will allow. The default -// is 1024. The actual limit depends on the system, and you can query it -// by using zsys_socket_limit (). A value of zero means "maximum". -// Note that this method is valid only before any socket is created. -CZMQ_EXPORT void - zsys_set_max_sockets (size_t max_sockets); - -// Return maximum number of ZeroMQ sockets that the system will support. -CZMQ_EXPORT size_t - zsys_socket_limit (void); - -// Configure the default linger timeout in msecs for new zsock instances. -// You can also set this separately on each zsock_t instance. The default -// linger time is zero, i.e. any pending messages will be dropped. If the -// environment variable ZSYS_LINGER is defined, that provides the default. -// Note that process exit will typically be delayed by the linger time. -CZMQ_EXPORT void - zsys_set_linger (size_t linger); - -// Configure the default outgoing pipe limit (HWM) for new zsock instances. -// You can also set this separately on each zsock_t instance. The default -// HWM is 1,000, on all versions of ZeroMQ. If the environment variable -// ZSYS_SNDHWM is defined, that provides the default. Note that a value of -// zero means no limit, i.e. infinite memory consumption. -CZMQ_EXPORT void - zsys_set_sndhwm (size_t sndhwm); - -// Configure the default incoming pipe limit (HWM) for new zsock instances. -// You can also set this separately on each zsock_t instance. The default -// HWM is 1,000, on all versions of ZeroMQ. If the environment variable -// ZSYS_RCVHWM is defined, that provides the default. Note that a value of -// zero means no limit, i.e. infinite memory consumption. -CZMQ_EXPORT void - zsys_set_rcvhwm (size_t rcvhwm); - -// Configure the default HWM for zactor internal pipes; this is set on both -// ends of the pipe, for outgoing messages only (sndhwm). The default HWM is -// 1,000, on all versions of ZeroMQ. If the environment var ZSYS_ACTORHWM is -// defined, that provides the default. Note that a value of zero means no -// limit, i.e. infinite memory consumption. -CZMQ_EXPORT void - zsys_set_pipehwm (size_t pipehwm); - -// Return the HWM for zactor internal pipes. -CZMQ_EXPORT size_t - zsys_pipehwm (void); - -// Configure use of IPv6 for new zsock instances. By default sockets accept -// and make only IPv4 connections. When you enable IPv6, sockets will accept -// and connect to both IPv4 and IPv6 peers. You can override the setting on -// each zsock_t instance. The default is IPv4 only (ipv6 set to 0). If the -// environment variable ZSYS_IPV6 is defined (as 1 or 0), this provides the -// default. Note: has no effect on ZMQ v2. -CZMQ_EXPORT void - zsys_set_ipv6 (int ipv6); - -// Return use of IPv6 for zsock instances. -CZMQ_EXPORT int - zsys_ipv6 (void); - -// Set network interface name to use for broadcasts, particularly zbeacon. -// This lets the interface be configured for test environments where required. -// For example, on Mac OS X, zbeacon cannot bind to 255.255.255.255 which is -// the default when there is no specified interface. If the environment -// variable ZSYS_INTERFACE is set, use that as the default interface name. -// Setting the interface to "*" means "use all available interfaces". -CZMQ_EXPORT void - zsys_set_interface (const char *value); - -// Return network interface to use for broadcasts, or "" if none was set. -CZMQ_EXPORT const char * - zsys_interface (void); - -// Set IPv6 address to use zbeacon socket, particularly for receiving zbeacon. -// This needs to be set IPv6 is enabled as IPv6 can have multiple addresses -// on a given interface. If the environment variable ZSYS_IPV6_ADDRESS is set, -// use that as the default IPv6 address. -CZMQ_EXPORT void - zsys_set_ipv6_address (const char *value); - -// Return IPv6 address to use for zbeacon reception, or "" if none was set. -CZMQ_EXPORT const char * - zsys_ipv6_address (void); - -// Set IPv6 milticast address to use for sending zbeacon messages. This needs -// to be set if IPv6 is enabled. If the environment variable -// ZSYS_IPV6_MCAST_ADDRESS is set, use that as the default IPv6 multicast -// address. -CZMQ_EXPORT void - zsys_set_ipv6_mcast_address (const char *value); - -// Return IPv6 multicast address to use for sending zbeacon, or "" if none was -// set. -CZMQ_EXPORT const char * - zsys_ipv6_mcast_address (void); - -// Configure the automatic use of pre-allocated FDs when creating new sockets. -// If 0 (default), nothing will happen. Else, when a new socket is bound, the -// system API will be used to check if an existing pre-allocated FD with a -// matching port (if TCP) or path (if IPC) exists, and if it does it will be -// set via the ZMQ_USE_FD socket option so that the library will use it -// instead of creating a new socket. -CZMQ_EXPORT void - zsys_set_auto_use_fd (int auto_use_fd); - -// Return use of automatic pre-allocated FDs for zsock instances. -CZMQ_EXPORT int - zsys_auto_use_fd (void); - -// Set log identity, which is a string that prefixes all log messages sent -// by this process. The log identity defaults to the environment variable -// ZSYS_LOGIDENT, if that is set. -CZMQ_EXPORT void - zsys_set_logident (const char *value); - -// Set stream to receive log traffic. By default, log traffic is sent to -// stdout. If you set the stream to NULL, no stream will receive the log -// traffic (it may still be sent to the system facility). -CZMQ_EXPORT void - zsys_set_logstream (FILE *stream); - -// Sends log output to a PUB socket bound to the specified endpoint. To -// collect such log output, create a SUB socket, subscribe to the traffic -// you care about, and connect to the endpoint. Log traffic is sent as a -// single string frame, in the same format as when sent to stdout. The -// log system supports a single sender; multiple calls to this method will -// bind the same sender to multiple endpoints. To disable the sender, call -// this method with a null argument. -CZMQ_EXPORT void - zsys_set_logsender (const char *endpoint); - -// Enable or disable logging to the system facility (syslog on POSIX boxes, -// event log on Windows). By default this is disabled. -CZMQ_EXPORT void - zsys_set_logsystem (bool logsystem); - -// Log error condition - highest priority -CZMQ_EXPORT void - zsys_error (const char *format, ...); - -// Log warning condition - high priority -CZMQ_EXPORT void - zsys_warning (const char *format, ...); - -// Log normal, but significant, condition - normal priority -CZMQ_EXPORT void - zsys_notice (const char *format, ...); - -// Log informational message - low priority -CZMQ_EXPORT void - zsys_info (const char *format, ...); - -// Log debug-level message - lowest priority -CZMQ_EXPORT void - zsys_debug (const char *format, ...); - -// Self test of this class -CZMQ_EXPORT void - zsys_test (bool verbose); - -// Global signal indicator, TRUE when user presses Ctrl-C or the process -// gets a SIGTERM signal. -CZMQ_EXPORT extern volatile int zsys_interrupted; -// Deprecated name for this variable -CZMQ_EXPORT extern volatile int zctx_interrupted; -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zthread.h b/phonelibs/zmq/aarch64/include/zthread.h deleted file mode 100644 index fc0602dd9f..0000000000 --- a/phonelibs/zmq/aarch64/include/zthread.h +++ /dev/null @@ -1,50 +0,0 @@ -/* ========================================================================= - zthread - working with system threads (deprecated) - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZTHREAD_H_INCLUDED__ -#define __ZTHREAD_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// Detached threads follow POSIX pthreads API -typedef void *(zthread_detached_fn) (void *args); - -// Attached threads get context and pipe from parent -typedef void (zthread_attached_fn) (void *args, zctx_t *ctx, void *pipe); - -// Create a detached thread. A detached thread operates autonomously -// and is used to simulate a separate process. It gets no ctx, and no -// pipe. -CZMQ_EXPORT int - zthread_new (zthread_detached_fn *thread_fn, void *args); - -// Create an attached thread. An attached thread gets a ctx and a PAIR -// pipe back to its parent. It must monitor its pipe, and exit if the -// pipe becomes unreadable. Do not destroy the ctx, the thread does this -// automatically when it ends. -CZMQ_EXPORT void * - zthread_fork (zctx_t *ctx, zthread_attached_fn *thread_fn, void *args); - -// Self test of this class -CZMQ_EXPORT void - zthread_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/ztimerset.h b/phonelibs/zmq/aarch64/include/ztimerset.h deleted file mode 100644 index 29633fafdb..0000000000 --- a/phonelibs/zmq/aarch64/include/ztimerset.h +++ /dev/null @@ -1,90 +0,0 @@ -/* ========================================================================= - ztimerset - timer set - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef ZTIMERSET_H_INCLUDED -#define ZTIMERSET_H_INCLUDED - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/ztimerset.api" to make changes. -// @interface -// This is a draft class, and may change without notice. It is disabled in -// stable builds by default. If you use this in applications, please ask -// for it to be pushed to stable state. Use --enable-drafts to enable. -#ifdef CZMQ_BUILD_DRAFT_API -// Callback function for timer event. -typedef void (ztimerset_fn) ( - int timer_id, void *arg); - -// *** Draft method, for development use, may change without warning *** -// Create new timer set. -CZMQ_EXPORT ztimerset_t * - ztimerset_new (void); - -// *** Draft method, for development use, may change without warning *** -// Destroy a timer set -CZMQ_EXPORT void - ztimerset_destroy (ztimerset_t **self_p); - -// *** Draft method, for development use, may change without warning *** -// Add a timer to the set. Returns timer id if OK, -1 on failure. -CZMQ_EXPORT int - ztimerset_add (ztimerset_t *self, size_t interval, ztimerset_fn handler, void *arg); - -// *** Draft method, for development use, may change without warning *** -// Cancel a timer. Returns 0 if OK, -1 on failure. -CZMQ_EXPORT int - ztimerset_cancel (ztimerset_t *self, int timer_id); - -// *** Draft method, for development use, may change without warning *** -// Set timer interval. Returns 0 if OK, -1 on failure. -// This method is slow, canceling the timer and adding a new one yield better performance. -CZMQ_EXPORT int - ztimerset_set_interval (ztimerset_t *self, int timer_id, size_t interval); - -// *** Draft method, for development use, may change without warning *** -// Reset timer to start interval counting from current time. Returns 0 if OK, -1 on failure. -// This method is slow, canceling the timer and adding a new one yield better performance. -CZMQ_EXPORT int - ztimerset_reset (ztimerset_t *self, int timer_id); - -// *** Draft method, for development use, may change without warning *** -// Return the time until the next interval. -// Should be used as timeout parameter for the zpoller wait method. -// The timeout is in msec. -CZMQ_EXPORT int - ztimerset_timeout (ztimerset_t *self); - -// *** Draft method, for development use, may change without warning *** -// Invoke callback function of all timers which their interval has elapsed. -// Should be call after zpoller wait method. -// Returns 0 if OK, -1 on failure. -CZMQ_EXPORT int - ztimerset_execute (ztimerset_t *self); - -// *** Draft method, for development use, may change without warning *** -// Self test of this class. -CZMQ_EXPORT void - ztimerset_test (bool verbose); - -#endif // CZMQ_BUILD_DRAFT_API -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/ztrie.h b/phonelibs/zmq/aarch64/include/ztrie.h deleted file mode 100644 index 6fd53234b1..0000000000 --- a/phonelibs/zmq/aarch64/include/ztrie.h +++ /dev/null @@ -1,106 +0,0 @@ -/* ========================================================================= - ztrie - simple trie for tokenizable strings - - Copyright (c) 1991-2012 iMatix Corporation -- http://www.imatix.com - Copyright other contributors as noted in the AUTHORS file. - - This file is part of CZMQ, the high-level C binding for 0MQ: http://czmq.zeromq.org - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef ZTRIE_H_INCLUDED -#define ZTRIE_H_INCLUDED - -#ifdef __cplusplus -extern "C" { -#endif - - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/ztrie.api" to make changes. -// @interface -// This is a draft class, and may change without notice. It is disabled in -// stable builds by default. If you use this in applications, please ask -// for it to be pushed to stable state. Use --enable-drafts to enable. -#ifdef CZMQ_BUILD_DRAFT_API -// Callback function for ztrie_node to destroy node data. -typedef void (ztrie_destroy_data_fn) ( - void **data); - -// *** Draft method, for development use, may change without warning *** -// Creates a new ztrie. -CZMQ_EXPORT ztrie_t * - ztrie_new (char delimiter); - -// *** Draft method, for development use, may change without warning *** -// Destroy the ztrie. -CZMQ_EXPORT void - ztrie_destroy (ztrie_t **self_p); - -// *** Draft method, for development use, may change without warning *** -// Inserts a new route into the tree and attaches the data. Returns -1 -// if the route already exists, otherwise 0. This method takes ownership of -// the provided data if a destroy_data_fn is provided. -CZMQ_EXPORT int - ztrie_insert_route (ztrie_t *self, const char *path, void *data, ztrie_destroy_data_fn destroy_data_fn); - -// *** Draft method, for development use, may change without warning *** -// Removes a route from the trie and destroys its data. Returns -1 if the -// route does not exists, otherwise 0. -// the start of the list call zlist_first (). Advances the cursor. -CZMQ_EXPORT int - ztrie_remove_route (ztrie_t *self, const char *path); - -// *** Draft method, for development use, may change without warning *** -// Returns true if the path matches a route in the tree, otherwise false. -CZMQ_EXPORT bool - ztrie_matches (ztrie_t *self, const char *path); - -// *** Draft method, for development use, may change without warning *** -// Returns the data of a matched route from last ztrie_matches. If the path -// did not match, returns NULL. Do not delete the data as it's owned by -// ztrie. -CZMQ_EXPORT void * - ztrie_hit_data (ztrie_t *self); - -// *** Draft method, for development use, may change without warning *** -// Returns the count of parameters that a matched route has. -CZMQ_EXPORT size_t - ztrie_hit_parameter_count (ztrie_t *self); - -// *** Draft method, for development use, may change without warning *** -// Returns the parameters of a matched route with named regexes from last -// ztrie_matches. If the path did not match or the route did not contain any -// named regexes, returns NULL. -CZMQ_EXPORT zhashx_t * - ztrie_hit_parameters (ztrie_t *self); - -// *** Draft method, for development use, may change without warning *** -// Returns the asterisk matched part of a route, if there has been no match -// or no asterisk match, returns NULL. -CZMQ_EXPORT const char * - ztrie_hit_asterisk_match (ztrie_t *self); - -// *** Draft method, for development use, may change without warning *** -// Print the trie -CZMQ_EXPORT void - ztrie_print (ztrie_t *self); - -// *** Draft method, for development use, may change without warning *** -// Self test of this class. -CZMQ_EXPORT void - ztrie_test (bool verbose); - -#endif // CZMQ_BUILD_DRAFT_API -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/include/zuuid.h b/phonelibs/zmq/aarch64/include/zuuid.h deleted file mode 100644 index afc1104fea..0000000000 --- a/phonelibs/zmq/aarch64/include/zuuid.h +++ /dev/null @@ -1,96 +0,0 @@ -/* ========================================================================= - zuuid - UUID support class - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZUUID_H_INCLUDED__ -#define __ZUUID_H_INCLUDED__ - -#define ZUUID_LEN 16 -#define ZUUID_STR_LEN (ZUUID_LEN * 2) - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zuuid.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Create a new UUID object. -CZMQ_EXPORT zuuid_t * - zuuid_new (void); - -// Create UUID object from supplied ZUUID_LEN-octet value. -CZMQ_EXPORT zuuid_t * - zuuid_new_from (const byte *source); - -// Destroy a specified UUID object. -CZMQ_EXPORT void - zuuid_destroy (zuuid_t **self_p); - -// Set UUID to new supplied ZUUID_LEN-octet value. -CZMQ_EXPORT void - zuuid_set (zuuid_t *self, const byte *source); - -// Set UUID to new supplied string value skipping '-' and '{' '}' -// optional delimiters. Return 0 if OK, else returns -1. -CZMQ_EXPORT int - zuuid_set_str (zuuid_t *self, const char *source); - -// Return UUID binary data. -CZMQ_EXPORT const byte * - zuuid_data (zuuid_t *self); - -// Return UUID binary size -CZMQ_EXPORT size_t - zuuid_size (zuuid_t *self); - -// Returns UUID as string -CZMQ_EXPORT const char * - zuuid_str (zuuid_t *self); - -// Return UUID in the canonical string format: 8-4-4-4-12, in lower -// case. Caller does not modify or free returned value. See -// http://en.wikipedia.org/wiki/Universally_unique_identifier -CZMQ_EXPORT const char * - zuuid_str_canonical (zuuid_t *self); - -// Store UUID blob in target array -CZMQ_EXPORT void - zuuid_export (zuuid_t *self, byte *target); - -// Check if UUID is same as supplied value -CZMQ_EXPORT bool - zuuid_eq (zuuid_t *self, const byte *compare); - -// Check if UUID is different from supplied value -CZMQ_EXPORT bool - zuuid_neq (zuuid_t *self, const byte *compare); - -// Make copy of UUID object; if uuid is null, or memory was exhausted, -// returns null. -CZMQ_EXPORT zuuid_t * - zuuid_dup (zuuid_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zuuid_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/aarch64/lib/libczmq.a b/phonelibs/zmq/aarch64/lib/libczmq.a deleted file mode 100644 index 2d2a251c2f..0000000000 Binary files a/phonelibs/zmq/aarch64/lib/libczmq.a and /dev/null differ diff --git a/phonelibs/zmq/aarch64/lib/libczmq.la b/phonelibs/zmq/aarch64/lib/libczmq.la deleted file mode 100755 index 7eb675e692..0000000000 --- a/phonelibs/zmq/aarch64/lib/libczmq.la +++ /dev/null @@ -1,41 +0,0 @@ -# libczmq.la - a libtool library file -# Generated by libtool (GNU libtool) 2.4.6 -# -# Please DO NOT delete this file! -# It is necessary for linking the library. - -# The name that we can dlopen(3). -dlname='libczmq.so' - -# Names of this library. -library_names='libczmq.so' - -# The name of the static archive. -old_library='libczmq.a' - -# Linker flags that cannot go in dependency_libs. -inherited_linker_flags='' - -# Libraries that this one depends upon. -dependency_libs=' -L/Users/batman/src/czmq/builds/android/prefix/aarch64-linux-android-4.9/lib -L/opt/android-ndk/platforms/android-21/arch-arm64/usr/lib -L/opt/android-ndk/sources/cxx-stl/gnu-libstdc++/4.9/libs/arm64-v8a -L/Users/batman/src/libzmq/builds/android/prefix/aarch64-linux-android-4.9/lib /Users/batman/src/libzmq/builds/android/prefix/aarch64-linux-android-4.9/lib/libzmq.la -llog -lc -lgcc -ldl -lm -lgnustl_shared' - -# Names of additional weak libraries provided by this library -weak_library_names='' - -# Version information for libczmq. -current=3 -age=0 -revision=0 - -# Is this an already installed library? -installed=yes - -# Should we warn about portability when linking against -modules? -shouldnotlink=no - -# Files to dlopen/dlpreopen -dlopen='' -dlpreopen='' - -# Directory that this library needs to be installed in: -libdir='/Users/batman/src/czmq/builds/android/prefix/aarch64-linux-android-4.9/lib' diff --git a/phonelibs/zmq/aarch64/lib/libczmq.so b/phonelibs/zmq/aarch64/lib/libczmq.so deleted file mode 100755 index 6b662a197f..0000000000 Binary files a/phonelibs/zmq/aarch64/lib/libczmq.so and /dev/null differ diff --git a/phonelibs/zmq/aarch64/lib/libzmq.a b/phonelibs/zmq/aarch64/lib/libzmq.a deleted file mode 100644 index b764af7b61..0000000000 Binary files a/phonelibs/zmq/aarch64/lib/libzmq.a and /dev/null differ diff --git a/phonelibs/zmq/aarch64/lib/libzmq.la b/phonelibs/zmq/aarch64/lib/libzmq.la deleted file mode 100755 index d7d420a4bd..0000000000 --- a/phonelibs/zmq/aarch64/lib/libzmq.la +++ /dev/null @@ -1,41 +0,0 @@ -# libzmq.la - a libtool library file -# Generated by libtool (GNU libtool) 2.4.6 -# -# Please DO NOT delete this file! -# It is necessary for linking the library. - -# The name that we can dlopen(3). -dlname='libzmq.so' - -# Names of this library. -library_names='libzmq.so' - -# The name of the static archive. -old_library='libzmq.a' - -# Linker flags that cannot go in dependency_libs. -inherited_linker_flags='' - -# Libraries that this one depends upon. -dependency_libs=' -L/Users/batman/src/libzmq/builds/android/prefix/aarch64-linux-android-4.9/lib -L/opt/android-ndk/sources/cxx-stl/gnu-libstdc++/4.9/libs/arm64-v8a -lgnustl_shared' - -# Names of additional weak libraries provided by this library -weak_library_names='' - -# Version information for libzmq. -current=5 -age=0 -revision=0 - -# Is this an already installed library? -installed=yes - -# Should we warn about portability when linking against -modules? -shouldnotlink=no - -# Files to dlopen/dlpreopen -dlopen='' -dlpreopen='' - -# Directory that this library needs to be installed in: -libdir='/Users/batman/src/libzmq/builds/android/prefix/aarch64-linux-android-4.9/lib' diff --git a/phonelibs/zmq/aarch64/lib/libzmq.so b/phonelibs/zmq/aarch64/lib/libzmq.so deleted file mode 100755 index 909c7f43a6..0000000000 Binary files a/phonelibs/zmq/aarch64/lib/libzmq.so and /dev/null differ diff --git a/phonelibs/zmq/arm/include/czmq.h b/phonelibs/zmq/arm/include/czmq.h deleted file mode 100644 index ba21aa3bd1..0000000000 --- a/phonelibs/zmq/arm/include/czmq.h +++ /dev/null @@ -1,31 +0,0 @@ -/* ========================================================================= - CZMQ - a high-level binding in C for ZeroMQ - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __CZMQ_H_INCLUDED__ -#define __CZMQ_H_INCLUDED__ - -// These are signatures for handler functions that customize the -// behavior of CZMQ containers. These are shared between all CZMQ -// container types. - -// -- destroy an item -typedef void (czmq_destructor) (void **item); -// -- duplicate an item -typedef void *(czmq_duplicator) (const void *item); -// - compare two items, for sorting -typedef int (czmq_comparator) (const void *item1, const void *item2); - -// Include the project library file -#include "czmq_library.h" - -#endif diff --git a/phonelibs/zmq/arm/include/czmq_library.h b/phonelibs/zmq/arm/include/czmq_library.h deleted file mode 100644 index be348db3e9..0000000000 --- a/phonelibs/zmq/arm/include/czmq_library.h +++ /dev/null @@ -1,199 +0,0 @@ -/* ========================================================================= - czmq - generated layer of public API - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - -################################################################################ -# THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY # -# Read the zproject/README.md for information about making permanent changes. # -################################################################################ - ========================================================================= -*/ - -#ifndef CZMQ_LIBRARY_H_INCLUDED -#define CZMQ_LIBRARY_H_INCLUDED - -// Set up environment for the application -#include "czmq_prelude.h" - -// External dependencies -#include - -// CZMQ version macros for compile-time API detection -#define CZMQ_VERSION_MAJOR 3 -#define CZMQ_VERSION_MINOR 0 -#define CZMQ_VERSION_PATCH 3 - -#define CZMQ_MAKE_VERSION(major, minor, patch) \ - ((major) * 10000 + (minor) * 100 + (patch)) -#define CZMQ_VERSION \ - CZMQ_MAKE_VERSION(CZMQ_VERSION_MAJOR, CZMQ_VERSION_MINOR, CZMQ_VERSION_PATCH) - -#if defined (__WINDOWS__) -# if defined CZMQ_STATIC -# define CZMQ_EXPORT -# elif defined CZMQ_INTERNAL_BUILD -# if defined DLL_EXPORT -# define CZMQ_EXPORT __declspec(dllexport) -# else -# define CZMQ_EXPORT -# endif -# elif defined CZMQ_EXPORTS -# define CZMQ_EXPORT __declspec(dllexport) -# else -# define CZMQ_EXPORT __declspec(dllimport) -# endif -#else -# define CZMQ_EXPORT -#endif - -// Opaque class structures to allow forward references -// These classes are stable or legacy and built in all releases -typedef struct _zactor_t zactor_t; -#define ZACTOR_T_DEFINED -typedef struct _zarmour_t zarmour_t; -#define ZARMOUR_T_DEFINED -typedef struct _zcert_t zcert_t; -#define ZCERT_T_DEFINED -typedef struct _zcertstore_t zcertstore_t; -#define ZCERTSTORE_T_DEFINED -typedef struct _zchunk_t zchunk_t; -#define ZCHUNK_T_DEFINED -typedef struct _zclock_t zclock_t; -#define ZCLOCK_T_DEFINED -typedef struct _zconfig_t zconfig_t; -#define ZCONFIG_T_DEFINED -typedef struct _zdigest_t zdigest_t; -#define ZDIGEST_T_DEFINED -typedef struct _zdir_t zdir_t; -#define ZDIR_T_DEFINED -typedef struct _zdir_patch_t zdir_patch_t; -#define ZDIR_PATCH_T_DEFINED -typedef struct _zfile_t zfile_t; -#define ZFILE_T_DEFINED -typedef struct _zframe_t zframe_t; -#define ZFRAME_T_DEFINED -typedef struct _zhash_t zhash_t; -#define ZHASH_T_DEFINED -typedef struct _zhashx_t zhashx_t; -#define ZHASHX_T_DEFINED -typedef struct _ziflist_t ziflist_t; -#define ZIFLIST_T_DEFINED -typedef struct _zlist_t zlist_t; -#define ZLIST_T_DEFINED -typedef struct _zlistx_t zlistx_t; -#define ZLISTX_T_DEFINED -typedef struct _zloop_t zloop_t; -#define ZLOOP_T_DEFINED -typedef struct _zmsg_t zmsg_t; -#define ZMSG_T_DEFINED -typedef struct _zpoller_t zpoller_t; -#define ZPOLLER_T_DEFINED -typedef struct _zsock_t zsock_t; -#define ZSOCK_T_DEFINED -typedef struct _zstr_t zstr_t; -#define ZSTR_T_DEFINED -typedef struct _zuuid_t zuuid_t; -#define ZUUID_T_DEFINED -typedef struct _zauth_t zauth_t; -#define ZAUTH_T_DEFINED -typedef struct _zbeacon_t zbeacon_t; -#define ZBEACON_T_DEFINED -typedef struct _zgossip_t zgossip_t; -#define ZGOSSIP_T_DEFINED -typedef struct _zmonitor_t zmonitor_t; -#define ZMONITOR_T_DEFINED -typedef struct _zproxy_t zproxy_t; -#define ZPROXY_T_DEFINED -typedef struct _zrex_t zrex_t; -#define ZREX_T_DEFINED -typedef struct _zsys_t zsys_t; -#define ZSYS_T_DEFINED -typedef struct _zauth_v2_t zauth_v2_t; -#define ZAUTH_V2_T_DEFINED -typedef struct _zbeacon_v2_t zbeacon_v2_t; -#define ZBEACON_V2_T_DEFINED -typedef struct _zctx_t zctx_t; -#define ZCTX_T_DEFINED -typedef struct _zmonitor_v2_t zmonitor_v2_t; -#define ZMONITOR_V2_T_DEFINED -typedef struct _zmutex_t zmutex_t; -#define ZMUTEX_T_DEFINED -typedef struct _zproxy_v2_t zproxy_v2_t; -#define ZPROXY_V2_T_DEFINED -typedef struct _zsocket_t zsocket_t; -#define ZSOCKET_T_DEFINED -typedef struct _zsockopt_t zsockopt_t; -#define ZSOCKOPT_T_DEFINED -typedef struct _zthread_t zthread_t; -#define ZTHREAD_T_DEFINED -// Draft classes are by default not built in stable releases -#ifdef CZMQ_BUILD_DRAFT_API -typedef struct _zproc_t zproc_t; -#define ZPROC_T_DEFINED -typedef struct _ztimerset_t ztimerset_t; -#define ZTIMERSET_T_DEFINED -typedef struct _ztrie_t ztrie_t; -#define ZTRIE_T_DEFINED -#endif // CZMQ_BUILD_DRAFT_API - - -// Public classes, each with its own header file -#include "zactor.h" -#include "zarmour.h" -#include "zcert.h" -#include "zcertstore.h" -#include "zchunk.h" -#include "zclock.h" -#include "zconfig.h" -#include "zdigest.h" -#include "zdir.h" -#include "zdir_patch.h" -#include "zfile.h" -#include "zframe.h" -#include "zhash.h" -#include "zhashx.h" -#include "ziflist.h" -#include "zlist.h" -#include "zlistx.h" -#include "zloop.h" -#include "zmsg.h" -#include "zpoller.h" -#include "zsock.h" -#include "zstr.h" -#include "zuuid.h" -#include "zauth.h" -#include "zbeacon.h" -#include "zgossip.h" -#include "zmonitor.h" -#include "zproxy.h" -#include "zrex.h" -#include "zsys.h" -#include "zauth_v2.h" -#include "zbeacon_v2.h" -#include "zctx.h" -#include "zmonitor_v2.h" -#include "zmutex.h" -#include "zproxy_v2.h" -#include "zsocket.h" -#include "zsockopt.h" -#include "zthread.h" -#ifdef CZMQ_BUILD_DRAFT_API -#include "zproc.h" -#include "ztimerset.h" -#include "ztrie.h" -#endif // CZMQ_BUILD_DRAFT_API - -#endif -/* -################################################################################ -# THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY # -# Read the zproject/README.md for information about making permanent changes. # -################################################################################ -*/ diff --git a/phonelibs/zmq/arm/include/czmq_prelude.h b/phonelibs/zmq/arm/include/czmq_prelude.h deleted file mode 100644 index e9ceb691e8..0000000000 --- a/phonelibs/zmq/arm/include/czmq_prelude.h +++ /dev/null @@ -1,641 +0,0 @@ -/* ========================================================================= - czmq_prelude.h - CZMQ environment - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __CZMQ_PRELUDE_H_INCLUDED__ -#define __CZMQ_PRELUDE_H_INCLUDED__ - -//- Establish the compiler and computer system ------------------------------ -/* - * Defines zero or more of these symbols, for use in any non-portable - * code: - * - * __WINDOWS__ Microsoft C/C++ with Windows calls - * __MSDOS__ System is MS-DOS (set if __WINDOWS__ set) - * __VMS__ System is VAX/VMS or Alpha/OpenVMS - * __UNIX__ System is UNIX - * __OS2__ System is OS/2 - * - * __IS_32BIT__ OS/compiler is 32 bits - * __IS_64BIT__ OS/compiler is 64 bits - * - * When __UNIX__ is defined, we also define exactly one of these: - * - * __UTYPE_AUX Apple AUX - * __UTYPE_BEOS BeOS - * __UTYPE_BSDOS BSD/OS - * __UTYPE_DECALPHA Digital UNIX (Alpha) - * __UTYPE_IBMAIX IBM RS/6000 AIX - * __UTYPE_FREEBSD FreeBSD - * __UTYPE_HPUX HP/UX - * __UTYPE_ANDROID Android - * __UTYPE_LINUX Linux - * __UTYPE_GNU GNU/Hurd - * __UTYPE_MIPS MIPS (BSD 4.3/System V mixture) - * __UTYPE_NETBSD NetBSD - * __UTYPE_NEXT NeXT - * __UTYPE_OPENBSD OpenBSD - * __UTYPE_OSX Apple Macintosh OS X - * __UTYPE_IOS Apple iOS - * __UTYPE_QNX QNX - * __UTYPE_IRIX Silicon Graphics IRIX - * __UTYPE_SINIX SINIX-N (Siemens-Nixdorf Unix) - * __UTYPE_SUNOS SunOS - * __UTYPE_SUNSOLARIS Sun Solaris - * __UTYPE_UNIXWARE SCO UnixWare - * ... these are the ones I know about so far. - * __UTYPE_GENERIC Any other UNIX - * - * When __VMS__ is defined, we may define one or more of these: - * - * __VMS_XOPEN Supports XOPEN functions - */ - -#if (defined (__64BIT__) || defined (__x86_64__)) -# define __IS_64BIT__ // May have 64-bit OS/compiler -#else -# define __IS_32BIT__ // Else assume 32-bit OS/compiler -#endif - -#if (defined WIN32 || defined _WIN32) -# undef __WINDOWS__ -# define __WINDOWS__ -# undef __MSDOS__ -# define __MSDOS__ -#endif - -#if (defined WINDOWS || defined _WINDOWS || defined __WINDOWS__) -# undef __WINDOWS__ -# define __WINDOWS__ -# undef __MSDOS__ -# define __MSDOS__ -// Stop cheeky warnings about "deprecated" functions like fopen -# if _MSC_VER >= 1500 -# undef _CRT_SECURE_NO_DEPRECATE -# define _CRT_SECURE_NO_DEPRECATE -# pragma warning(disable: 4996) -# endif -#endif - -// MSDOS Microsoft C -// _MSC_VER Microsoft C -#if (defined (MSDOS) || defined (_MSC_VER)) -# undef __MSDOS__ -# define __MSDOS__ -# if (defined (_DEBUG) && !defined (DEBUG)) -# define DEBUG -# endif -#endif - -#if (defined (__EMX__) && defined (__i386__)) -# undef __OS2__ -# define __OS2__ -#endif - -// VMS VAX C (VAX/VMS) -// __VMS Dec C (Alpha/OpenVMS) -// __vax__ gcc -#if (defined (VMS) || defined (__VMS) || defined (__vax__)) -# undef __VMS__ -# define __VMS__ -# if (__VMS_VER >= 70000000) -# define __VMS_XOPEN -# endif -#endif - -// Try to define a __UTYPE_xxx symbol... -// unix SunOS at least -// __unix__ gcc -// _POSIX_SOURCE is various UNIX systems, maybe also VAX/VMS -#if (defined (unix) || defined (__unix__) || defined (_POSIX_SOURCE)) -# if (!defined (__VMS__)) -# undef __UNIX__ -# define __UNIX__ -# if (defined (__alpha)) // Digital UNIX is 64-bit -# undef __IS_32BIT__ -# define __IS_64BIT__ -# define __UTYPE_DECALPHA -# endif -# endif -#endif - -#if (defined (_AUX)) -# define __UTYPE_AUX -# define __UNIX__ -#elif (defined (__BEOS__)) -# define __UTYPE_BEOS -# define __UNIX__ -#elif (defined (__hpux)) -# define __UTYPE_HPUX -# define __UNIX__ -# define _INCLUDE_HPUX_SOURCE -# define _INCLUDE_XOPEN_SOURCE -# define _INCLUDE_POSIX_SOURCE -#elif (defined (_AIX) || defined (AIX)) -# define __UTYPE_IBMAIX -# define __UNIX__ -#elif (defined (BSD) || defined (bsd)) -# define __UTYPE_BSDOS -# define __UNIX__ -#elif (defined (__ANDROID__)) -# define __UTYPE_ANDROID -# define __UNIX__ -#elif (defined (LINUX) || defined (linux) || defined (__linux__)) -# define __UTYPE_LINUX -# define __UNIX__ -# ifndef __NO_CTYPE -# define __NO_CTYPE // Suppress warnings on tolower() -# endif -# ifndef _DEFAULT_SOURCE -# define _DEFAULT_SOURCE // Include stuff from 4.3 BSD Unix -# endif -#elif (defined (__GNU__)) -# define __UTYPE_GNU -# define __UNIX__ -#elif (defined (Mips)) -# define __UTYPE_MIPS -# define __UNIX__ -#elif (defined (FreeBSD) || defined (__FreeBSD__)) -# define __UTYPE_FREEBSD -# define __UNIX__ -#elif (defined (NetBSD) || defined (__NetBSD__)) -# define __UTYPE_NETBSD -# define __UNIX__ -#elif (defined (OpenBSD) || defined (__OpenBSD__)) -# define __UTYPE_OPENBSD -# define __UNIX__ -#elif (defined (APPLE) || defined (__APPLE__)) -# include -# define __UNIX__ -# if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR -# define __UTYPE_IOS -# else -# define __UTYPE_OSX -# endif -#elif (defined (NeXT)) -# define __UTYPE_NEXT -# define __UNIX__ -#elif (defined (__QNX__)) -# define __UTYPE_QNX -# define __UNIX__ -#elif (defined (sgi)) -# define __UTYPE_IRIX -# define __UNIX__ -#elif (defined (sinix)) -# define __UTYPE_SINIX -# define __UNIX__ -#elif (defined (SOLARIS) || defined (__SRV4)) -# define __UTYPE_SUNSOLARIS -# define __UNIX__ -#elif (defined (SUNOS) || defined (SUN) || defined (sun)) -# define __UTYPE_SUNOS -# define __UNIX__ -#elif (defined (__USLC__) || defined (UnixWare)) -# define __UTYPE_UNIXWARE -# define __UNIX__ -#elif (defined (__CYGWIN__)) -# define __UTYPE_CYGWIN -# define __UNIX__ -#elif (defined (__UNIX__)) -# define __UTYPE_GENERIC -#endif - -//- Always include ZeroMQ headers ------------------------------------------- - -#include "zmq.h" -#if (ZMQ_VERSION < ZMQ_MAKE_VERSION (4, 2, 0)) -# include "zmq_utils.h" -#endif - -//- Standard ANSI include files --------------------------------------------- - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -//- System-specific include files ------------------------------------------- - -#if (defined (__MSDOS__)) -# if (defined (__WINDOWS__)) -# if (_WIN32_WINNT < 0x0501) -# undef _WIN32_WINNT -# define _WIN32_WINNT 0x0501 -# endif -# if (!defined (FD_SETSIZE)) -# define FD_SETSIZE 1024 // Max. filehandles/sockets -# endif -# include -# include -# include -# include -# include // For getnameinfo () -# include // For GetAdaptersAddresses () -# endif -# include -# include -# include -# include -# include -# include -# include -# include -#endif - -#if (defined (__UNIX__)) -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include // Let CZMQ build with libzmq/3.x -# include // Must come before arpa/inet.h -# if (!defined (__UTYPE_ANDROID)) && (!defined (__UTYPE_IBMAIX)) \ - && (!defined (__UTYPE_HPUX)) -# include -# endif -# if defined (__UTYPE_SUNSOLARIS) || defined (__UTYPE_SUNOS) -# include -# endif -# if (!defined (__UTYPE_BEOS)) -# include -# if (!defined (TCP_NODELAY)) -# include -# endif -# endif -# if (defined (__UTYPE_IBMAIX) || defined(__UTYPE_QNX)) -# include -# endif -# if (defined (__UTYPE_BEOS)) -# include -# endif -# if ((defined (_XOPEN_REALTIME) && (_XOPEN_REALTIME >= 1)) \ - || (defined (_POSIX_VERSION) && (_POSIX_VERSION >= 199309L))) -# include -# endif -# if (defined (__UTYPE_OSX) || defined (__UTYPE_IOS)) -# include -# include // For monotonic clocks -# endif -# if (defined (__UTYPE_OSX)) -# include // For _NSGetEnviron() -# endif -# if (defined (__UTYPE_ANDROID)) -# include -# endif -# if (defined (__UTYPE_LINUX) && defined (HAVE_LIBSYSTEMD)) -# include -# endif -#endif - -#if (defined (__VMS__)) -# if (!defined (vaxc)) -# include // Not provided by Vax C -# endif -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -#endif - -#if (defined (__OS2__)) -# include // Required near top -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include // Must come before arpa/inet.h -# include -# include -# if (!defined (TCP_NODELAY)) -# include -# endif -#endif - -// Add missing defines for non-POSIX systems -#ifndef S_IRUSR -# define S_IRUSR S_IREAD -#endif -#ifndef S_IWUSR -# define S_IWUSR S_IWRITE -#endif -#ifndef S_ISDIR -# define S_ISDIR(m) (((m) & S_IFDIR) != 0) -#endif -#ifndef S_ISREG -# define S_ISREG(m) (((m) & S_IFREG) != 0) -#endif - - -//- Check compiler data type sizes ------------------------------------------ - -#if (UCHAR_MAX != 0xFF) -# error "Cannot compile: must change definition of 'byte'." -#endif -#if (USHRT_MAX != 0xFFFFU) -# error "Cannot compile: must change definition of 'dbyte'." -#endif -#if (UINT_MAX != 0xFFFFFFFFU) -# error "Cannot compile: must change definition of 'qbyte'." -#endif - -//- Data types -------------------------------------------------------------- - -typedef unsigned char byte; // Single unsigned byte = 8 bits -typedef unsigned short dbyte; // Double byte = 16 bits -typedef unsigned int qbyte; // Quad byte = 32 bits -typedef struct sockaddr_in inaddr_t; // Internet socket address structure -typedef struct sockaddr_in6 in6addr_t; // Internet 6 socket address structure - -// Common structure to hold inaddr_t and in6addr_t with length -typedef struct { - union { - inaddr_t __addr; // IPv4 address - in6addr_t __addr6; // IPv6 address - } __inaddr_u; -#define ipv4addr __inaddr_u.__addr -#define ipv6addr __inaddr_u.__addr6 - int inaddrlen; -} inaddr_storage_t; - -//- Inevitable macros ------------------------------------------------------- - -#define streq(s1,s2) (!strcmp ((s1), (s2))) -#define strneq(s1,s2) (strcmp ((s1), (s2))) - -// Provide random number from 0..(num-1) -#if (defined (__WINDOWS__)) || (defined (__UTYPE_IBMAIX)) \ - || (defined (__UTYPE_HPUX)) || (defined (__UTYPE_SUNOS)) -# define randof(num) (int) ((float) (num) * rand () / (RAND_MAX + 1.0)) -#else -# define randof(num) (int) ((float) (num) * random () / (RAND_MAX + 1.0)) -#endif - -// Windows MSVS doesn't have stdbool -#if (defined (_MSC_VER)) -# if (!defined (__cplusplus) && (!defined (true))) -# define true 1 -# define false 0 - typedef char bool; -# endif -#else -# include -#endif - -//- A number of POSIX and C99 keywords and data types ----------------------- -// CZMQ uses uint for array indices; equivalent to unsigned int, but more -// convenient in code. We define it in czmq_prelude.h on systems that do -// not define it by default. - -#if (defined (__WINDOWS__)) -# if (!defined (__cplusplus) && (!defined (inline))) -# define inline __inline -# endif -# define strtoull _strtoui64 -# define atoll _atoi64 -# define srandom srand -# define TIMEZONE _timezone -# if (!defined (__MINGW32__)) -# define snprintf _snprintf -# define vsnprintf _vsnprintf -# endif - typedef unsigned long ulong; - typedef unsigned int uint; -# if (!defined (__MINGW32__)) - typedef int mode_t; -# if !defined (_SSIZE_T_DEFINED) -typedef intptr_t ssize_t; -# define _SSIZE_T_DEFINED -# endif -# endif -# if ((!defined (__MINGW32__) \ - || (defined (__MINGW32__) && defined (__IS_64BIT__))) \ - && !defined (ZMQ_DEFINED_STDINT)) - typedef __int8 int8_t; - typedef __int16 int16_t; - typedef __int32 int32_t; - typedef __int64 int64_t; - typedef unsigned __int8 uint8_t; - typedef unsigned __int16 uint16_t; - typedef unsigned __int32 uint32_t; - typedef unsigned __int64 uint64_t; -# endif - typedef uint32_t in_addr_t; -# if (!defined (PRId8)) -# define PRId8 "d" -# endif -# if (!defined (PRId16)) -# define PRId16 "d" -# endif -# if (!defined (PRId32)) -# define PRId32 "d" -# endif -# if (!defined (PRId64)) -# define PRId64 "I64d" -# endif -# if (!defined (PRIu8)) -# define PRIu8 "u" -# endif -# if (!defined (PRIu16)) -# define PRIu16 "u" -# endif -# if (!defined (PRIu32)) -# define PRIu32 "u" -# endif -# if (!defined (PRIu64)) -# define PRIu64 "I64u" -# endif -# if (!defined (va_copy)) - // MSVC does not support C99's va_copy so we use a regular assignment -# define va_copy(dest,src) (dest) = (src) -# endif -#elif (defined (__UTYPE_OSX)) - typedef unsigned long ulong; - typedef unsigned int uint; - // This fixes header-order dependence problem with some Linux versions -#elif (defined (__UTYPE_LINUX)) -# if (__STDC_VERSION__ >= 199901L && !defined (__USE_MISC)) - typedef unsigned int uint; -# endif -#endif - -//- Non-portable declaration specifiers ------------------------------------- - -// For thread-local storage -#if defined (__WINDOWS__) -# define CZMQ_THREADLS __declspec(thread) -#else -# define CZMQ_THREADLS __thread -#endif - -// Replacement for malloc() which asserts if we run out of heap, and -// which zeroes the allocated block. -static inline void * -safe_malloc (size_t size, const char *file, unsigned line) -{ -// printf ("%s:%u %08d\n", file, line, (int) size); - void *mem = calloc (1, size); - if (mem == NULL) { - fprintf (stderr, "FATAL ERROR at %s:%u\n", file, line); - fprintf (stderr, "OUT OF MEMORY (malloc returned NULL)\n"); - fflush (stderr); - abort (); - } - return mem; -} - -// Define _ZMALLOC_DEBUG if you need to trace memory leaks using e.g. mtrace, -// otherwise all allocations will claim to come from czmq_prelude.h. For best -// results, compile all classes so you see dangling object allocations. -// _ZMALLOC_PEDANTIC does the same thing, but its intention is to propagate -// out of memory condition back up the call stack. -#if defined _ZMALLOC_DEBUG || _ZMALLOC_PEDANTIC -# define zmalloc(size) calloc(1,(size)) -#else -# define zmalloc(size) safe_malloc((size), __FILE__, __LINE__) -#endif - -// GCC supports validating format strings for functions that act like printf -#if defined (__GNUC__) && (__GNUC__ >= 2) -# define CHECK_PRINTF(a) __attribute__((format (printf, a, a + 1))) -#else -# define CHECK_PRINTF(a) -#endif - -// Lets us write code that compiles both on Windows and normal platforms -#if !defined (__WINDOWS__) -typedef int SOCKET; -# define closesocket close -# define INVALID_SOCKET -1 -# define SOCKET_ERROR -1 -# define O_BINARY 0 -#endif - -//- Include non-portable header files based on platform.h ------------------- - -#if defined (HAVE_LINUX_WIRELESS_H) -# include -// This would normally come from net/if.h -unsigned int if_nametoindex (const char *ifname); -#else -# if defined (HAVE_NET_IF_H) -# include -# endif -# if defined (HAVE_NET_IF_MEDIA_H) -# include -# endif -#endif - -#if defined (__WINDOWS__) && !defined (HAVE_UUID) -# define HAVE_UUID 1 -#endif -#if defined (__UTYPE_OSX) && !defined (HAVE_UUID) -# define HAVE_UUID 1 -#endif -#if defined (HAVE_UUID) -# if defined (__UTYPE_FREEBSD) || defined (__UTYPE_NETBSD) -# include -# elif defined __UTYPE_HPUX -# include -# elif defined (__UNIX__) -# include -# endif -#endif - -// ZMQ compatibility macros - -#if ZMQ_VERSION_MAJOR == 4 -# define ZMQ_POLL_MSEC 1 // zmq_poll is msec - -#elif ZMQ_VERSION_MAJOR == 3 -# define ZMQ_POLL_MSEC 1 // zmq_poll is msec -# if ZMQ_VERSION_MINOR < 2 -# define zmq_ctx_new zmq_init -# endif -# define zmq_ctx_term zmq_term - -#elif ZMQ_VERSION_MAJOR == 2 -# define ZMQ_POLL_MSEC 1000 // zmq_poll is usec -# define zmq_sendmsg zmq_send // Smooth out 2.x changes -# define zmq_recvmsg zmq_recv -# define zmq_ctx_new zmq_init -# define zmq_ctx_term zmq_term -# define zmq_msg_send(m,s,f) zmq_sendmsg ((s),(m),(f)) -# define zmq_msg_recv(m,s,f) zmq_recvmsg ((s),(m),(f)) - // Older libzmq APIs may be missing some aspects of libzmq v3.0 -# ifndef ZMQ_ROUTER -# define ZMQ_ROUTER ZMQ_XREP -# endif -# ifndef ZMQ_DEALER -# define ZMQ_DEALER ZMQ_XREQ -# endif -# ifndef ZMQ_DONTWAIT -# define ZMQ_DONTWAIT ZMQ_NOBLOCK -# endif -# ifndef ZMQ_XSUB -# error "please upgrade your libzmq from http://zeromq.org" -# endif -# if ZMQ_VERSION_MINOR == 0 \ - || (ZMQ_VERSION_MINOR == 1 && ZMQ_VERSION_PATCH < 7) -# error "CZMQ requires at least libzmq/2.1.7 stable" -# endif -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zactor.h b/phonelibs/zmq/arm/include/zactor.h deleted file mode 100644 index c865c65daf..0000000000 --- a/phonelibs/zmq/arm/include/zactor.h +++ /dev/null @@ -1,76 +0,0 @@ -/* ========================================================================= - zactor - actor - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZACTOR_H_INCLUDED__ -#define __ZACTOR_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zactor.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Actors get a pipe and arguments from caller -typedef void (zactor_fn) ( - zsock_t *pipe, void *args); - -// Create a new actor passing arbitrary arguments reference. -CZMQ_EXPORT zactor_t * - zactor_new (zactor_fn task, void *args); - -// Destroy an actor. -CZMQ_EXPORT void - zactor_destroy (zactor_t **self_p); - -// Send a zmsg message to the actor, take ownership of the message -// and destroy when it has been sent. -CZMQ_EXPORT int - zactor_send (zactor_t *self, zmsg_t **msg_p); - -// Receive a zmsg message from the actor. Returns NULL if the actor -// was interrupted before the message could be received, or if there -// was a timeout on the actor. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zmsg_t * - zactor_recv (zactor_t *self); - -// Probe the supplied object, and report if it looks like a zactor_t. -CZMQ_EXPORT bool - zactor_is (void *self); - -// Probe the supplied reference. If it looks like a zactor_t instance, -// return the underlying libzmq actor handle; else if it looks like -// a libzmq actor handle, return the supplied value. -CZMQ_EXPORT void * - zactor_resolve (void *self); - -// Return the actor's zsock handle. Use this when you absolutely need -// to work with the zsock instance rather than the actor. -CZMQ_EXPORT zsock_t * - zactor_sock (zactor_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zactor_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zarmour.h b/phonelibs/zmq/arm/include/zarmour.h deleted file mode 100644 index c7f299f7af..0000000000 --- a/phonelibs/zmq/arm/include/zarmour.h +++ /dev/null @@ -1,114 +0,0 @@ -/* ========================================================================= - zarmour - armoured text encoding and decoding - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZARMOUR_H_INCLUDED__ -#define __ZARMOUR_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zarmour.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -#define ZARMOUR_MODE_BASE64_STD 0 // Standard base 64 -#define ZARMOUR_MODE_BASE64_URL 1 // URL and filename friendly base 64 -#define ZARMOUR_MODE_BASE32_STD 2 // Standard base 32 -#define ZARMOUR_MODE_BASE32_HEX 3 // Extended hex base 32 -#define ZARMOUR_MODE_BASE16 4 // Standard base 16 -#define ZARMOUR_MODE_Z85 5 // Z85 from ZeroMQ RFC 32 - -// Create a new zarmour -CZMQ_EXPORT zarmour_t * - zarmour_new (void); - -// Destroy the zarmour -CZMQ_EXPORT void - zarmour_destroy (zarmour_t **self_p); - -// Encode a stream of bytes into an armoured string. Returns the armoured -// string, or NULL if there was insufficient memory available to allocate -// a new string. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zarmour_encode (zarmour_t *self, const byte *data, size_t size); - -// Decode an armoured string into a chunk. The decoded output is -// null-terminated, so it may be treated as a string, if that's what -// it was prior to encoding. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zchunk_t * - zarmour_decode (zarmour_t *self, const char *data); - -// Get the mode property. -CZMQ_EXPORT int - zarmour_mode (zarmour_t *self); - -// Get printable string for mode. -CZMQ_EXPORT const char * - zarmour_mode_str (zarmour_t *self); - -// Set the mode property. -CZMQ_EXPORT void - zarmour_set_mode (zarmour_t *self, int mode); - -// Return true if padding is turned on. -CZMQ_EXPORT bool - zarmour_pad (zarmour_t *self); - -// Turn padding on or off. Default is on. -CZMQ_EXPORT void - zarmour_set_pad (zarmour_t *self, bool pad); - -// Get the padding character. -CZMQ_EXPORT char - zarmour_pad_char (zarmour_t *self); - -// Set the padding character. -CZMQ_EXPORT void - zarmour_set_pad_char (zarmour_t *self, char pad_char); - -// Return if splitting output into lines is turned on. Default is off. -CZMQ_EXPORT bool - zarmour_line_breaks (zarmour_t *self); - -// Turn splitting output into lines on or off. -CZMQ_EXPORT void - zarmour_set_line_breaks (zarmour_t *self, bool line_breaks); - -// Get the line length used for splitting lines. -CZMQ_EXPORT size_t - zarmour_line_length (zarmour_t *self); - -// Set the line length used for splitting lines. -CZMQ_EXPORT void - zarmour_set_line_length (zarmour_t *self, size_t line_length); - -// Print properties of object -CZMQ_EXPORT void - zarmour_print (zarmour_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zarmour_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zauth.h b/phonelibs/zmq/arm/include/zauth.h deleted file mode 100644 index ca6bb913c8..0000000000 --- a/phonelibs/zmq/arm/include/zauth.h +++ /dev/null @@ -1,100 +0,0 @@ -/* ========================================================================= - zauth - authentication for ZeroMQ security mechanisms - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZAUTH_H_INCLUDED__ -#define __ZAUTH_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -#define CURVE_ALLOW_ANY "*" - -// CZMQ v3 API (for use with zsock, not zsocket, which is deprecated). -// -// Create new zauth actor instance. This installs authentication on all -// zsock sockets. Until you add policies, all incoming NULL connections are -// allowed (classic ZeroMQ behaviour), and all PLAIN and CURVE connections -// are denied: -// -// zactor_t *auth = zactor_new (zauth, NULL); -// -// Destroy zauth instance. This removes authentication and allows all -// connections to pass, without authentication: -// -// zactor_destroy (&auth); -// -// Note that all zauth commands are synchronous, so your application always -// waits for a signal from the actor after each command. -// -// Enable verbose logging of commands and activity. Verbose logging can help -// debug non-trivial authentication policies: -// -// zstr_send (auth, "VERBOSE"); -// zsock_wait (auth); -// -// Allow (whitelist) a list of IP addresses. For NULL, all clients from -// these addresses will be accepted. For PLAIN and CURVE, they will be -// allowed to continue with authentication. You can call this method -// multiple times to whitelist more IP addresses. If you whitelist one -// or nmore addresses, any non-whitelisted addresses are treated as -// blacklisted: -// -// zstr_sendx (auth, "ALLOW", "127.0.0.1", "127.0.0.2", NULL); -// zsock_wait (auth); -// -// Deny (blacklist) a list of IP addresses. For all security mechanisms, -// this rejects the connection without any further authentication. Use -// either a whitelist, or a blacklist, not not both. If you define both -// a whitelist and a blacklist, only the whitelist takes effect: -// -// zstr_sendx (auth, "DENY", "192.168.0.1", "192.168.0.2", NULL); -// zsock_wait (auth); -// -// Configure PLAIN authentication using a plain-text password file. You can -// modify the password file at any time; zauth will reload it automatically -// if modified externally: -// -// zstr_sendx (auth, "PLAIN", filename, NULL); -// zsock_wait (auth); -// -// Configure CURVE authentication, using a directory that holds all public -// client certificates, i.e. their public keys. The certificates must be in -// zcert_save format. You can add and remove certificates in that directory -// at any time. To allow all client keys without checking, specify -// CURVE_ALLOW_ANY for the directory name: -// -// zstr_sendx (auth, "CURVE", directory, NULL); -// zsock_wait (auth); -// -// Configure GSSAPI authentication, using an underlying mechanism (usually -// Kerberos) to establish a secure context and perform mutual authentication: -// -// zstr_sendx (auth, "GSSAPI", NULL); -// zsock_wait (auth); -// -// This is the zauth constructor as a zactor_fn: -CZMQ_EXPORT void - zauth (zsock_t *pipe, void *certstore); - -// Selftest -CZMQ_EXPORT void - zauth_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zauth_v2.h b/phonelibs/zmq/arm/include/zauth_v2.h deleted file mode 100644 index bbbee86b03..0000000000 --- a/phonelibs/zmq/arm/include/zauth_v2.h +++ /dev/null @@ -1,88 +0,0 @@ -/* ========================================================================= - zauth_v2 - authentication for ZeroMQ servers (deprecated) - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZAUTH_V2_H_INCLUDED__ -#define __ZAUTH_V2_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -#ifndef CURVE_ALLOW_ANY -# define CURVE_ALLOW_ANY "*" -#endif - -// Constructor -// Install authentication for the specified context. Returns a new zauth -// object that you can use to configure authentication. Note that until you -// add policies, all incoming NULL connections are allowed (classic ZeroMQ -// behaviour), and all PLAIN and CURVE connections are denied. If there was -// an error during initialization, returns NULL. -CZMQ_EXPORT zauth_t * - zauth_new (zctx_t *ctx); - -// Destructor -CZMQ_EXPORT void - zauth_destroy (zauth_t **self_p); - -// Allow (whitelist) a single IP address. For NULL, all clients from this -// address will be accepted. For PLAIN and CURVE, they will be allowed to -// continue with authentication. You can call this method multiple times -// to whitelist multiple IP addresses. If you whitelist a single address, -// any non-whitelisted addresses are treated as blacklisted. -CZMQ_EXPORT void - zauth_allow (zauth_t *self, const char *address); - -// Deny (blacklist) a single IP address. For all security mechanisms, this -// rejects the connection without any further authentication. Use either a -// whitelist, or a blacklist, not not both. If you define both a whitelist -// and a blacklist, only the whitelist takes effect. -CZMQ_EXPORT void - zauth_deny (zauth_t *self, const char *address); - -// Configure PLAIN authentication for a given domain. PLAIN authentication -// uses a plain-text password file. To cover all domains, use "*". You can -// modify the password file at any time; it is reloaded automatically. -CZMQ_EXPORT void - zauth_configure_plain (zauth_t *self, const char *domain, const char *filename); - -// Configure CURVE authentication for a given domain. CURVE authentication -// uses a directory that holds all public client certificates, i.e. their -// public keys. The certificates must be in zcert_save () format. To cover -// all domains, use "*". You can add and remove certificates in that -// directory at any time. To allow all client keys without checking, specify -// CURVE_ALLOW_ANY for the location. -CZMQ_EXPORT void - zauth_configure_curve (zauth_t *self, const char *domain, const char *location); - -// Configure GSSAPI authentication for a given domain. GSSAPI authentication -// uses an underlying mechanism (usually Kerberos) to establish a secure -// context and perform mutual authentication. To cover all domains, use "*". -CZMQ_EXPORT void - zauth_configure_gssapi (zauth_t *self, char *domain); - -// Enable verbose tracing of commands and activity -CZMQ_EXPORT void - zauth_set_verbose (zauth_t *self, bool verbose); - -// Selftest -CZMQ_EXPORT void - zauth_v2_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zbeacon.h b/phonelibs/zmq/arm/include/zbeacon.h deleted file mode 100644 index 78917e9577..0000000000 --- a/phonelibs/zmq/arm/include/zbeacon.h +++ /dev/null @@ -1,86 +0,0 @@ -/* ========================================================================= - zbeacon - LAN discovery and presence - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZBEACON_H_INCLUDED__ -#define __ZBEACON_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// Create new zbeacon actor instance: -// -// zactor_t *beacon = zactor_new (zbeacon, NULL); -// -// Destroy zbeacon instance: -// -// zactor_destroy (&beacon); -// -// Enable verbose logging of commands and activity: -// -// zstr_send (beacon, "VERBOSE"); -// -// Configure beacon to run on specified UDP port, and return the name of -// the host, which can be used as endpoint for incoming connections. To -// force the beacon to operate on a given interface, set the environment -// variable ZSYS_INTERFACE, or call zsys_set_interface() before creating -// the beacon. If the system does not support UDP broadcasts (lacking a -// workable interface), returns an empty hostname: -// -// // Pictures: 's' = C string, 'i' = int -// zsock_send (beacon, "si", "CONFIGURE", port_number); -// char *hostname = zstr_recv (beacon); -// -// Start broadcasting a beacon at a specified interval in msec. The beacon -// data can be at most UDP_FRAME_MAX bytes; this constant is defined in -// zsys.h to be 255: -// -// // Pictures: 'b' = byte * data + size_t size -// zsock_send (beacon, "sbi", "PUBLISH", data, size, interval); -// -// Stop broadcasting the beacon: -// -// zstr_sendx (beacon, "SILENCE", NULL); -// -// Start listening to beacons from peers. The filter is used to do a prefix -// match on received beacons, to remove junk. Note that any received data -// that is identical to our broadcast beacon_data is discarded in any case. -// If the filter size is zero, we get all peer beacons: -// -// zsock_send (beacon, "sb", "SUBSCRIBE", filter_data, filter_size); -// -// Stop listening to other peers -// -// zstr_sendx (beacon, "UNSUBSCRIBE", NULL); -// -// Receive next beacon from a peer. Received beacons are always a 2-frame -// message containing the ipaddress of the sender, and then the binary -// beacon data as published by the sender: -// -// zmsg_t *msg = zmsg_recv (beacon); -// -// This is the zbeacon constructor as a zactor_fn: -CZMQ_EXPORT void - zbeacon (zsock_t *pipe, void *unused); - -// Self test of this class -CZMQ_EXPORT void - zbeacon_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zbeacon_v2.h b/phonelibs/zmq/arm/include/zbeacon_v2.h deleted file mode 100644 index 8e8f3b4cde..0000000000 --- a/phonelibs/zmq/arm/include/zbeacon_v2.h +++ /dev/null @@ -1,75 +0,0 @@ -/* ========================================================================= - zbeacon - LAN discovery and presence (deprecated) - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZBEACON_V2_H_INCLUDED__ -#define __ZBEACON_V2_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// Create a new beacon on a certain UDP port. If the system does not -// support UDP broadcasts (lacking a useful interface), returns NULL. -// To force the beacon to operate on a given port, set the environment -// variable ZSYS_INTERFACE, or call zsys_set_interface() beforehand. -// If you are using the new zsock API then pass NULL as the ctx here. -CZMQ_EXPORT zbeacon_t * - zbeacon_new (zctx_t *ctx, int port_nbr); - -// Destroy a beacon -CZMQ_EXPORT void - zbeacon_destroy (zbeacon_t **self_p); - -// Return our own IP address as printable string -CZMQ_EXPORT char * - zbeacon_hostname (zbeacon_t *self); - -// Set broadcast interval in milliseconds (default is 1000 msec) -CZMQ_EXPORT void - zbeacon_set_interval (zbeacon_t *self, int interval); - -// Filter out any beacon that looks exactly like ours -CZMQ_EXPORT void - zbeacon_noecho (zbeacon_t *self); - -// Start broadcasting beacon to peers at the specified interval -CZMQ_EXPORT void - zbeacon_publish (zbeacon_t *self, byte *transmit, size_t size); - -// Stop broadcasting beacons -CZMQ_EXPORT void - zbeacon_silence (zbeacon_t *self); - -// Start listening to other peers; zero-sized filter means get everything -CZMQ_EXPORT void - zbeacon_subscribe (zbeacon_t *self, byte *filter, size_t size); - -// Stop listening to other peers -CZMQ_EXPORT void - zbeacon_unsubscribe (zbeacon_t *self); - -// Get beacon ZeroMQ socket, for polling or receiving messages -CZMQ_EXPORT void * - zbeacon_socket (zbeacon_t *self); - -// Self test of this class -CZMQ_EXPORT void - zbeacon_v2_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zcert.h b/phonelibs/zmq/arm/include/zcert.h deleted file mode 100644 index 495b579cda..0000000000 --- a/phonelibs/zmq/arm/include/zcert.h +++ /dev/null @@ -1,139 +0,0 @@ -/* ========================================================================= - zcert - work with CURVE security certificates - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZCERT_H_INCLUDED__ -#define __ZCERT_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zcert.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// This class has legacy methods, which will be removed over time. You -// should not use them, and migrate any code that is still using them. -// Create and initialize a new certificate in memory -CZMQ_EXPORT zcert_t * - zcert_new (void); - -// Accepts public/secret key pair from caller -CZMQ_EXPORT zcert_t * - zcert_new_from (const byte *public_key, const byte *secret_key); - -// Load certificate from file -CZMQ_EXPORT zcert_t * - zcert_load (const char *filename); - -// Destroy a certificate in memory -CZMQ_EXPORT void - zcert_destroy (zcert_t **self_p); - -// Return public part of key pair as 32-byte binary string -CZMQ_EXPORT const byte * - zcert_public_key (zcert_t *self); - -// Return secret part of key pair as 32-byte binary string -CZMQ_EXPORT const byte * - zcert_secret_key (zcert_t *self); - -// Return public part of key pair as Z85 armored string -CZMQ_EXPORT const char * - zcert_public_txt (zcert_t *self); - -// Return secret part of key pair as Z85 armored string -CZMQ_EXPORT const char * - zcert_secret_txt (zcert_t *self); - -// Set certificate metadata from formatted string. -CZMQ_EXPORT void - zcert_set_meta (zcert_t *self, const char *name, const char *format, ...); - -// Get metadata value from certificate; if the metadata value doesn't -// exist, returns NULL. -CZMQ_EXPORT const char * - zcert_meta (zcert_t *self, const char *name); - -// Get list of metadata fields from certificate. Caller is responsible for -// destroying list. Caller should not modify the values of list items. -CZMQ_EXPORT zlist_t * - zcert_meta_keys (zcert_t *self); - -// Save full certificate (public + secret) to file for persistent storage -// This creates one public file and one secret file (filename + "_secret"). -CZMQ_EXPORT int - zcert_save (zcert_t *self, const char *filename); - -// Save public certificate only to file for persistent storage -CZMQ_EXPORT int - zcert_save_public (zcert_t *self, const char *filename); - -// Save secret certificate only to file for persistent storage -CZMQ_EXPORT int - zcert_save_secret (zcert_t *self, const char *filename); - -// Apply certificate to socket, i.e. use for CURVE security on socket. -// If certificate was loaded from public file, the secret key will be -// undefined, and this certificate will not work successfully. -CZMQ_EXPORT void - zcert_apply (zcert_t *self, void *socket); - -// Return copy of certificate; if certificate is NULL or we exhausted -// heap memory, returns NULL. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zcert_t * - zcert_dup (zcert_t *self); - -// Return true if two certificates have the same keys -CZMQ_EXPORT bool - zcert_eq (zcert_t *self, zcert_t *compare); - -// Print certificate contents to stdout -CZMQ_EXPORT void - zcert_print (zcert_t *self); - -// *** Deprecated method, slated for removal: avoid using it *** -// Print certificate contents to open stream. This method is deprecated -// and you should use the print method. -CZMQ_EXPORT void - zcert_fprint (zcert_t *self, FILE *file); - -// Self test of this class -CZMQ_EXPORT void - zcert_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Unset certificate metadata. -CZMQ_EXPORT void - zcert_unset_meta (zcert_t *self, const char *name); - -#endif // CZMQ_BUILD_DRAFT_API -// @ignore -CZMQ_EXPORT void - zcert_set_meta (zcert_t *self, const char *name, const char *format, ...) CHECK_PRINTF (3); -// @end - - -#ifdef __cplusplus -} -#endif - -// Deprecated method aliases -#define zcert_dump(s) zcert_print(s) - -#endif diff --git a/phonelibs/zmq/arm/include/zcertstore.h b/phonelibs/zmq/arm/include/zcertstore.h deleted file mode 100644 index c7f93c5a7d..0000000000 --- a/phonelibs/zmq/arm/include/zcertstore.h +++ /dev/null @@ -1,100 +0,0 @@ -/* ========================================================================= - zcertstore - work with CURVE security certificate stores - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZCERTSTORE_H_INCLUDED__ -#define __ZCERTSTORE_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zcertstore.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// This class has legacy methods, which will be removed over time. You -// should not use them, and migrate any code that is still using them. -// Create a new certificate store from a disk directory, loading and -// indexing all certificates in that location. The directory itself may be -// absent, and created later, or modified at any time. The certificate store -// is automatically refreshed on any zcertstore_lookup() call. If the -// location is specified as NULL, creates a pure-memory store, which you -// can work with by inserting certificates at runtime. -CZMQ_EXPORT zcertstore_t * - zcertstore_new (const char *location); - -// Destroy a certificate store object in memory. Does not affect anything -// stored on disk. -CZMQ_EXPORT void - zcertstore_destroy (zcertstore_t **self_p); - -// Look up certificate by public key, returns zcert_t object if found, -// else returns NULL. The public key is provided in Z85 text format. -CZMQ_EXPORT zcert_t * - zcertstore_lookup (zcertstore_t *self, const char *public_key); - -// Insert certificate into certificate store in memory. Note that this -// does not save the certificate to disk. To do that, use zcert_save() -// directly on the certificate. Takes ownership of zcert_t object. -CZMQ_EXPORT void - zcertstore_insert (zcertstore_t *self, zcert_t **cert_p); - -// Print list of certificates in store to logging facility -CZMQ_EXPORT void - zcertstore_print (zcertstore_t *self); - -// *** Deprecated method, slated for removal: avoid using it *** -// Print list of certificates in store to open stream. This method is -// deprecated, and you should use the print method. -CZMQ_EXPORT void - zcertstore_fprint (zcertstore_t *self, FILE *file); - -// Self test of this class -CZMQ_EXPORT void - zcertstore_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// Loaders retrieve certificates from an arbitrary source. -typedef void (zcertstore_loader) ( - zcertstore_t *self); - -// Destructor for loader state. -typedef void (zcertstore_destructor) ( - void **self_p); - -// *** Draft method, for development use, may change without warning *** -// Override the default disk loader with a custom loader fn. -CZMQ_EXPORT void - zcertstore_set_loader (zcertstore_t *self, zcertstore_loader loader, zcertstore_destructor destructor, void *state); - -// *** Draft method, for development use, may change without warning *** -// Empty certificate hashtable. This wrapper exists to be friendly to bindings, -// which don't usually have access to struct internals. -CZMQ_EXPORT void - zcertstore_empty (zcertstore_t *self); - -#endif // CZMQ_BUILD_DRAFT_API -// @end - - -#ifdef __cplusplus -} -#endif - -// Deprecated method aliases -#define zcertstore_dump(s) zcertstore_print(s) - -#endif diff --git a/phonelibs/zmq/arm/include/zchunk.h b/phonelibs/zmq/arm/include/zchunk.h deleted file mode 100644 index 56f29b161a..0000000000 --- a/phonelibs/zmq/arm/include/zchunk.h +++ /dev/null @@ -1,163 +0,0 @@ -/* ========================================================================= - zchunk - work with memory chunks - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZCHUNK_H_INCLUDED__ -#define __ZCHUNK_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zchunk.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Create a new chunk of the specified size. If you specify the data, it -// is copied into the chunk. If you do not specify the data, the chunk is -// allocated and left empty, and you can then add data using zchunk_append. -CZMQ_EXPORT zchunk_t * - zchunk_new (const void *data, size_t size); - -// Destroy a chunk -CZMQ_EXPORT void - zchunk_destroy (zchunk_t **self_p); - -// Resizes chunk max_size as requested; chunk_cur size is set to zero -CZMQ_EXPORT void - zchunk_resize (zchunk_t *self, size_t size); - -// Return chunk cur size -CZMQ_EXPORT size_t - zchunk_size (zchunk_t *self); - -// Return chunk max size -CZMQ_EXPORT size_t - zchunk_max_size (zchunk_t *self); - -// Return chunk data -CZMQ_EXPORT byte * - zchunk_data (zchunk_t *self); - -// Set chunk data from user-supplied data; truncate if too large. Data may -// be null. Returns actual size of chunk -CZMQ_EXPORT size_t - zchunk_set (zchunk_t *self, const void *data, size_t size); - -// Fill chunk data from user-supplied octet -CZMQ_EXPORT size_t - zchunk_fill (zchunk_t *self, byte filler, size_t size); - -// Append user-supplied data to chunk, return resulting chunk size. If the -// data would exceeded the available space, it is truncated. If you want to -// grow the chunk to accommodate new data, use the zchunk_extend method. -CZMQ_EXPORT size_t - zchunk_append (zchunk_t *self, const void *data, size_t size); - -// Append user-supplied data to chunk, return resulting chunk size. If the -// data would exceeded the available space, the chunk grows in size. -CZMQ_EXPORT size_t - zchunk_extend (zchunk_t *self, const void *data, size_t size); - -// Copy as much data from 'source' into the chunk as possible; returns the -// new size of chunk. If all data from 'source' is used, returns exhausted -// on the source chunk. Source can be consumed as many times as needed until -// it is exhausted. If source was already exhausted, does not change chunk. -CZMQ_EXPORT size_t - zchunk_consume (zchunk_t *self, zchunk_t *source); - -// Returns true if the chunk was exhausted by consume methods, or if the -// chunk has a size of zero. -CZMQ_EXPORT bool - zchunk_exhausted (zchunk_t *self); - -// Read chunk from an open file descriptor -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zchunk_t * - zchunk_read (FILE *handle, size_t bytes); - -// Write chunk to an open file descriptor -CZMQ_EXPORT int - zchunk_write (zchunk_t *self, FILE *handle); - -// Try to slurp an entire file into a chunk. Will read up to maxsize of -// the file. If maxsize is 0, will attempt to read the entire file and -// fail with an assertion if that cannot fit into memory. Returns a new -// chunk containing the file data, or NULL if the file could not be read. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zchunk_t * - zchunk_slurp (const char *filename, size_t maxsize); - -// Create copy of chunk, as new chunk object. Returns a fresh zchunk_t -// object, or null if there was not enough heap memory. If chunk is null, -// returns null. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zchunk_t * - zchunk_dup (zchunk_t *self); - -// Return chunk data encoded as printable hex string. Caller must free -// string when finished with it. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zchunk_strhex (zchunk_t *self); - -// Return chunk data copied into freshly allocated string -// Caller must free string when finished with it. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zchunk_strdup (zchunk_t *self); - -// Return TRUE if chunk body is equal to string, excluding terminator -CZMQ_EXPORT bool - zchunk_streq (zchunk_t *self, const char *string); - -// Transform zchunk into a zframe that can be sent in a message. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zchunk_pack (zchunk_t *self); - -// Transform a zframe into a zchunk. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zchunk_t * - zchunk_unpack (zframe_t *frame); - -// Calculate SHA1 digest for chunk, using zdigest class. -CZMQ_EXPORT const char * - zchunk_digest (zchunk_t *self); - -// Dump chunk to FILE stream, for debugging and tracing. -CZMQ_EXPORT void - zchunk_fprint (zchunk_t *self, FILE *file); - -// Dump message to stderr, for debugging and tracing. -// See zchunk_fprint for details -CZMQ_EXPORT void - zchunk_print (zchunk_t *self); - -// Probe the supplied object, and report if it looks like a zchunk_t. -CZMQ_EXPORT bool - zchunk_is (void *self); - -// Self test of this class. -CZMQ_EXPORT void - zchunk_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/phonelibs/zmq/arm/include/zclock.h b/phonelibs/zmq/arm/include/zclock.h deleted file mode 100644 index eb064162c4..0000000000 --- a/phonelibs/zmq/arm/include/zclock.h +++ /dev/null @@ -1,73 +0,0 @@ -/* ========================================================================= - zclock - millisecond clocks and delays - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZCLOCK_H_INCLUDED__ -#define __ZCLOCK_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zclock.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Sleep for a number of milliseconds -CZMQ_EXPORT void - zclock_sleep (int msecs); - -// Return current system clock as milliseconds. Note that this clock can -// jump backwards (if the system clock is changed) so is unsafe to use for -// timers and time offsets. Use zclock_mono for that instead. -CZMQ_EXPORT int64_t - zclock_time (void); - -// Return current monotonic clock in milliseconds. Use this when you compute -// time offsets. The monotonic clock is not affected by system changes and -// so will never be reset backwards, unlike a system clock. -CZMQ_EXPORT int64_t - zclock_mono (void); - -// Return current monotonic clock in microseconds. Use this when you compute -// time offsets. The monotonic clock is not affected by system changes and -// so will never be reset backwards, unlike a system clock. -CZMQ_EXPORT int64_t - zclock_usecs (void); - -// Return formatted date/time as fresh string. Free using zstr_free(). -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zclock_timestr (void); - -// Self test of this class. -CZMQ_EXPORT void - zclock_test (bool verbose); - -// @end - - -// DEPRECATED in favor of zsys logging, see issue #519 -// Print formatted string to stdout, prefixed by date/time and -// terminated with a newline. -CZMQ_EXPORT void - zclock_log (const char *format, ...); - -// Compiler hints -CZMQ_EXPORT void zclock_log (const char *format, ...) CHECK_PRINTF (1); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zconfig.h b/phonelibs/zmq/arm/include/zconfig.h deleted file mode 100644 index 4ec4e1c81f..0000000000 --- a/phonelibs/zmq/arm/include/zconfig.h +++ /dev/null @@ -1,194 +0,0 @@ -/* ========================================================================= - zconfig - work with config files written in rfc.zeromq.org/spec:4/ZPL. - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZCONFIG_H_INCLUDED__ -#define __ZCONFIG_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zconfig.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// -typedef int (zconfig_fct) ( - zconfig_t *self, void *arg, int level); - -// Create new config item -CZMQ_EXPORT zconfig_t * - zconfig_new (const char *name, zconfig_t *parent); - -// Load a config tree from a specified ZPL text file; returns a zconfig_t -// reference for the root, if the file exists and is readable. Returns NULL -// if the file does not exist. -CZMQ_EXPORT zconfig_t * - zconfig_load (const char *filename); - -// Equivalent to zconfig_load, taking a format string instead of a fixed -// filename. -CZMQ_EXPORT zconfig_t * - zconfig_loadf (const char *format, ...); - -// Destroy a config item and all its children -CZMQ_EXPORT void - zconfig_destroy (zconfig_t **self_p); - -// Return name of config item -CZMQ_EXPORT char * - zconfig_name (zconfig_t *self); - -// Return value of config item -CZMQ_EXPORT char * - zconfig_value (zconfig_t *self); - -// Insert or update configuration key with value -CZMQ_EXPORT void - zconfig_put (zconfig_t *self, const char *path, const char *value); - -// Equivalent to zconfig_put, accepting a format specifier and variable -// argument list, instead of a single string value. -CZMQ_EXPORT void - zconfig_putf (zconfig_t *self, const char *path, const char *format, ...); - -// Get value for config item into a string value; leading slash is optional -// and ignored. -CZMQ_EXPORT char * - zconfig_get (zconfig_t *self, const char *path, const char *default_value); - -// Set config item name, name may be NULL -CZMQ_EXPORT void - zconfig_set_name (zconfig_t *self, const char *name); - -// Set new value for config item. The new value may be a string, a printf -// format, or NULL. Note that if string may possibly contain '%', or if it -// comes from an insecure source, you must use '%s' as the format, followed -// by the string. -CZMQ_EXPORT void - zconfig_set_value (zconfig_t *self, const char *format, ...); - -// Find our first child, if any -CZMQ_EXPORT zconfig_t * - zconfig_child (zconfig_t *self); - -// Find our first sibling, if any -CZMQ_EXPORT zconfig_t * - zconfig_next (zconfig_t *self); - -// Find a config item along a path; leading slash is optional and ignored. -CZMQ_EXPORT zconfig_t * - zconfig_locate (zconfig_t *self, const char *path); - -// Locate the last config item at a specified depth -CZMQ_EXPORT zconfig_t * - zconfig_at_depth (zconfig_t *self, int level); - -// Execute a callback for each config item in the tree; returns zero if -// successful, else -1. -CZMQ_EXPORT int - zconfig_execute (zconfig_t *self, zconfig_fct handler, void *arg); - -// Add comment to config item before saving to disk. You can add as many -// comment lines as you like. If you use a null format, all comments are -// deleted. -CZMQ_EXPORT void - zconfig_set_comment (zconfig_t *self, const char *format, ...); - -// Return comments of config item, as zlist. -CZMQ_EXPORT zlist_t * - zconfig_comments (zconfig_t *self); - -// Save a config tree to a specified ZPL text file, where a filename -// "-" means dump to standard output. -CZMQ_EXPORT int - zconfig_save (zconfig_t *self, const char *filename); - -// Equivalent to zconfig_save, taking a format string instead of a fixed -// filename. -CZMQ_EXPORT int - zconfig_savef (zconfig_t *self, const char *format, ...); - -// Report filename used during zconfig_load, or NULL if none -CZMQ_EXPORT const char * - zconfig_filename (zconfig_t *self); - -// Reload config tree from same file that it was previously loaded from. -// Returns 0 if OK, -1 if there was an error (and then does not change -// existing data). -CZMQ_EXPORT int - zconfig_reload (zconfig_t **self_p); - -// Load a config tree from a memory chunk -CZMQ_EXPORT zconfig_t * - zconfig_chunk_load (zchunk_t *chunk); - -// Save a config tree to a new memory chunk -CZMQ_EXPORT zchunk_t * - zconfig_chunk_save (zconfig_t *self); - -// Load a config tree from a null-terminated string -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zconfig_t * - zconfig_str_load (const char *string); - -// Save a config tree to a new null terminated string -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zconfig_str_save (zconfig_t *self); - -// Return true if a configuration tree was loaded from a file and that -// file has changed in since the tree was loaded. -CZMQ_EXPORT bool - zconfig_has_changed (zconfig_t *self); - -// Print the config file to open stream -CZMQ_EXPORT void - zconfig_fprint (zconfig_t *self, FILE *file); - -// Print properties of object -CZMQ_EXPORT void - zconfig_print (zconfig_t *self); - -// Self test of this class -CZMQ_EXPORT void - zconfig_test (bool verbose); - -// @ignore -CZMQ_EXPORT void - zconfig_putf (zconfig_t *self, const char *path, const char *format, ...) CHECK_PRINTF (3); -CZMQ_EXPORT void - zconfig_set_value (zconfig_t *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT void - zconfig_set_comment (zconfig_t *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int - zconfig_savef (zconfig_t *self, const char *format, ...) CHECK_PRINTF (2); -// @end - -// Self test of this class -CZMQ_EXPORT void - zconfig_test (bool verbose); - -// Compiler hints -CZMQ_EXPORT void zconfig_set_value (zconfig_t *self, const char *format, ...) CHECK_PRINTF (2); - -#ifdef __cplusplus -} -#endif - -// Deprecated method aliases -#define zconfig_dump(s) zconfig_print(s) -#define zconfig_resolve(s,p,d) zconfig_get((s),(p),(d)) - -#endif diff --git a/phonelibs/zmq/arm/include/zctx.h b/phonelibs/zmq/arm/include/zctx.h deleted file mode 100644 index 88898410dc..0000000000 --- a/phonelibs/zmq/arm/include/zctx.h +++ /dev/null @@ -1,107 +0,0 @@ -/* ========================================================================= - zctx - working with 0MQ contexts - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZCTX_H_INCLUDED__ -#define __ZCTX_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - - -// @interface -// Create new context, returns context object, replaces zmq_init -CZMQ_EXPORT zctx_t * - zctx_new (void); - -// Destroy context and all sockets in it, replaces zmq_term -CZMQ_EXPORT void - zctx_destroy (zctx_t **self_p); - -// Create new shadow context, returns context object -CZMQ_EXPORT zctx_t * - zctx_shadow (zctx_t *self); -// @end - -// Create a new context by shadowing a plain zmq context -CZMQ_EXPORT zctx_t * -zctx_shadow_zmq_ctx (void *zmqctx); - -// @interface -// Raise default I/O threads from 1, for crazy heavy applications -// The rule of thumb is one I/O thread per gigabyte of traffic in -// or out. Call this method before creating any sockets on the context, -// or calling zctx_shadow, or the setting will have no effect. -CZMQ_EXPORT void - zctx_set_iothreads (zctx_t *self, int iothreads); - -// Set msecs to flush sockets when closing them, see the ZMQ_LINGER -// man page section for more details. By default, set to zero, so -// any in-transit messages are discarded when you destroy a socket or -// a context. -CZMQ_EXPORT void - zctx_set_linger (zctx_t *self, int linger); - -// Set initial high-water mark for inter-thread pipe sockets. Note that -// this setting is separate from the default for normal sockets. You -// should change the default for pipe sockets *with care*. Too low values -// will cause blocked threads, and an infinite setting can cause memory -// exhaustion. The default, no matter the underlying ZeroMQ version, is -// 1,000. -CZMQ_EXPORT void - zctx_set_pipehwm (zctx_t *self, int pipehwm); - -// Set initial send HWM for all new normal sockets created in context. -// You can set this per-socket after the socket is created. -// The default, no matter the underlying ZeroMQ version, is 1,000. -CZMQ_EXPORT void - zctx_set_sndhwm (zctx_t *self, int sndhwm); - -// Set initial receive HWM for all new normal sockets created in context. -// You can set this per-socket after the socket is created. -// The default, no matter the underlying ZeroMQ version, is 1,000. -CZMQ_EXPORT void - zctx_set_rcvhwm (zctx_t *self, int rcvhwm); - -// Return low-level 0MQ context object, will be NULL before first socket -// is created. Use with care. -CZMQ_EXPORT void * - zctx_underlying (zctx_t *self); - -// Self test of this class -CZMQ_EXPORT void - zctx_test (bool verbose); -// @end - -// Create socket within this context, for CZMQ use only -void * - zctx__socket_new (zctx_t *self, int type); - -// Create pipe socket within this context, for CZMQ use only -void * - zctx__socket_pipe (zctx_t *self); - -// Destroy socket within this context, for CZMQ use only -void - zctx__socket_destroy (zctx_t *self, void *socket); - -// Initialize the low-level 0MQ context object, for CZMQ use only -void - zctx__initialize_underlying(zctx_t *self); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zdigest.h b/phonelibs/zmq/arm/include/zdigest.h deleted file mode 100644 index def9e86053..0000000000 --- a/phonelibs/zmq/arm/include/zdigest.h +++ /dev/null @@ -1,65 +0,0 @@ -/* ========================================================================= - zdigest - provides hashing functions (SHA-1 at present) - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZDIGEST_H_INCLUDED__ -#define __ZDIGEST_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zdigest.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Constructor - creates new digest object, which you use to build up a -// digest by repeatedly calling zdigest_update() on chunks of data. -CZMQ_EXPORT zdigest_t * - zdigest_new (void); - -// Destroy a digest object -CZMQ_EXPORT void - zdigest_destroy (zdigest_t **self_p); - -// Add buffer into digest calculation -CZMQ_EXPORT void - zdigest_update (zdigest_t *self, const byte *buffer, size_t length); - -// Return final digest hash data. If built without crypto support, -// returns NULL. -CZMQ_EXPORT const byte * - zdigest_data (zdigest_t *self); - -// Return final digest hash size -CZMQ_EXPORT size_t - zdigest_size (zdigest_t *self); - -// Return digest as printable hex string; caller should not modify nor -// free this string. After calling this, you may not use zdigest_update() -// on the same digest. If built without crypto support, returns NULL. -CZMQ_EXPORT char * - zdigest_string (zdigest_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zdigest_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zdir.h b/phonelibs/zmq/arm/include/zdir.h deleted file mode 100644 index 6c5551b57e..0000000000 --- a/phonelibs/zmq/arm/include/zdir.h +++ /dev/null @@ -1,149 +0,0 @@ -/* ========================================================================= - zdir - work with file-system directories - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZDIR_H_INCLUDED__ -#define __ZDIR_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zdir.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Create a new directory item that loads in the full tree of the specified -// path, optionally located under some parent path. If parent is "-", then -// loads only the top-level directory, and does not use parent as a path. -CZMQ_EXPORT zdir_t * - zdir_new (const char *path, const char *parent); - -// Destroy a directory tree and all children it contains. -CZMQ_EXPORT void - zdir_destroy (zdir_t **self_p); - -// Return directory path -CZMQ_EXPORT const char * - zdir_path (zdir_t *self); - -// Return last modification time for directory. -CZMQ_EXPORT time_t - zdir_modified (zdir_t *self); - -// Return total hierarchy size, in bytes of data contained in all files -// in the directory tree. -CZMQ_EXPORT off_t - zdir_cursize (zdir_t *self); - -// Return directory count -CZMQ_EXPORT size_t - zdir_count (zdir_t *self); - -// Returns a sorted list of zfile objects; Each entry in the list is a pointer -// to a zfile_t item already allocated in the zdir tree. Do not destroy the -// original zdir tree until you are done with this list. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlist_t * - zdir_list (zdir_t *self); - -// Remove directory, optionally including all files that it contains, at -// all levels. If force is false, will only remove the directory if empty. -// If force is true, will remove all files and all subdirectories. -CZMQ_EXPORT void - zdir_remove (zdir_t *self, bool force); - -// Calculate differences between two versions of a directory tree. -// Returns a list of zdir_patch_t patches. Either older or newer may -// be null, indicating the directory is empty/absent. If alias is set, -// generates virtual filename (minus path, plus alias). -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlist_t * - zdir_diff (zdir_t *older, zdir_t *newer, const char *alias); - -// Return full contents of directory as a zdir_patch list. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlist_t * - zdir_resync (zdir_t *self, const char *alias); - -// Load directory cache; returns a hash table containing the SHA-1 digests -// of every file in the tree. The cache is saved between runs in .cache. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zhash_t * - zdir_cache (zdir_t *self); - -// Print contents of directory to open stream -CZMQ_EXPORT void - zdir_fprint (zdir_t *self, FILE *file, int indent); - -// Print contents of directory to stdout -CZMQ_EXPORT void - zdir_print (zdir_t *self, int indent); - -// Create a new zdir_watch actor instance: -// -// zactor_t *watch = zactor_new (zdir_watch, NULL); -// -// Destroy zdir_watch instance: -// -// zactor_destroy (&watch); -// -// Enable verbose logging of commands and activity: -// -// zstr_send (watch, "VERBOSE"); -// -// Subscribe to changes to a directory path: -// -// zsock_send (watch, "ss", "SUBSCRIBE", "directory_path"); -// -// Unsubscribe from changes to a directory path: -// -// zsock_send (watch, "ss", "UNSUBSCRIBE", "directory_path"); -// -// Receive directory changes: -// zsock_recv (watch, "sp", &path, &patches); -// -// // Delete the received data. -// free (path); -// zlist_destroy (&patches); -CZMQ_EXPORT void - zdir_watch (zsock_t *pipe, void *unused); - -// Self test of this class. -CZMQ_EXPORT void - zdir_test (bool verbose); - -// @end - - -// Returns a sorted array of zfile objects; returns a single block of memory, -// that you destroy by calling zstr_free(). Each entry in the array is a pointer -// to a zfile_t item already allocated in the zdir tree. The array ends with -// a null pointer. Do not destroy the original zdir tree until you are done -// with this array. -CZMQ_EXPORT zfile_t ** - zdir_flatten (zdir_t *self); - -// Free a provided string, and nullify the parent pointer. Safe to call on -// a null pointer. -CZMQ_EXPORT void - zdir_flatten_free (zfile_t ***files_p); - -#ifdef __cplusplus -} -#endif - -// Deprecated method aliases -#define zdir_dump(s,i) zdir_print(s,i) - -#endif diff --git a/phonelibs/zmq/arm/include/zdir_patch.h b/phonelibs/zmq/arm/include/zdir_patch.h deleted file mode 100644 index 8d15b9aeb4..0000000000 --- a/phonelibs/zmq/arm/include/zdir_patch.h +++ /dev/null @@ -1,82 +0,0 @@ -/* ========================================================================= - zdir_patch - work with directory patches - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZDIR_PATCH_H_INCLUDED__ -#define __ZDIR_PATCH_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// un-namespaced enumeration values -#define patch_create ZDIR_PATCH_CREATE -#define patch_delete ZDIR_PATCH_DELETE - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zdir_patch.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -#define ZDIR_PATCH_CREATE 1 // Creates a new file -#define ZDIR_PATCH_DELETE 2 // Delete a file - -// Create new patch -CZMQ_EXPORT zdir_patch_t * - zdir_patch_new (const char *path, zfile_t *file, int op, const char *alias); - -// Destroy a patch -CZMQ_EXPORT void - zdir_patch_destroy (zdir_patch_t **self_p); - -// Create copy of a patch. If the patch is null, or memory was exhausted, -// returns null. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zdir_patch_t * - zdir_patch_dup (zdir_patch_t *self); - -// Return patch file directory path -CZMQ_EXPORT const char * - zdir_patch_path (zdir_patch_t *self); - -// Return patch file item -CZMQ_EXPORT zfile_t * - zdir_patch_file (zdir_patch_t *self); - -// Return operation -CZMQ_EXPORT int - zdir_patch_op (zdir_patch_t *self); - -// Return patch virtual file path -CZMQ_EXPORT const char * - zdir_patch_vpath (zdir_patch_t *self); - -// Calculate hash digest for file (create only) -CZMQ_EXPORT void - zdir_patch_digest_set (zdir_patch_t *self); - -// Return hash digest for patch file -CZMQ_EXPORT const char * - zdir_patch_digest (zdir_patch_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zdir_patch_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zfile.h b/phonelibs/zmq/arm/include/zfile.h deleted file mode 100644 index 75c35774b9..0000000000 --- a/phonelibs/zmq/arm/include/zfile.h +++ /dev/null @@ -1,177 +0,0 @@ -/* ========================================================================= - zfile - helper functions for working with files. - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZFILE_H_INCLUDED__ -#define __ZFILE_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zfile.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// If file exists, populates properties. CZMQ supports portable symbolic -// links, which are files with the extension ".ln". A symbolic link is a -// text file containing one line, the filename of a target file. Reading -// data from the symbolic link actually reads from the target file. Path -// may be NULL, in which case it is not used. -CZMQ_EXPORT zfile_t * - zfile_new (const char *path, const char *name); - -// Destroy a file item -CZMQ_EXPORT void - zfile_destroy (zfile_t **self_p); - -// Duplicate a file item, returns a newly constructed item. If the file -// is null, or memory was exhausted, returns null. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zfile_t * - zfile_dup (zfile_t *self); - -// Return file name, remove path if provided -CZMQ_EXPORT const char * - zfile_filename (zfile_t *self, const char *path); - -// Refresh file properties from disk; this is not done automatically -// on access methods, otherwise it is not possible to compare directory -// snapshots. -CZMQ_EXPORT void - zfile_restat (zfile_t *self); - -// Return when the file was last modified. If you want this to reflect the -// current situation, call zfile_restat before checking this property. -CZMQ_EXPORT time_t - zfile_modified (zfile_t *self); - -// Return the last-known size of the file. If you want this to reflect the -// current situation, call zfile_restat before checking this property. -CZMQ_EXPORT off_t - zfile_cursize (zfile_t *self); - -// Return true if the file is a directory. If you want this to reflect -// any external changes, call zfile_restat before checking this property. -CZMQ_EXPORT bool - zfile_is_directory (zfile_t *self); - -// Return true if the file is a regular file. If you want this to reflect -// any external changes, call zfile_restat before checking this property. -CZMQ_EXPORT bool - zfile_is_regular (zfile_t *self); - -// Return true if the file is readable by this process. If you want this to -// reflect any external changes, call zfile_restat before checking this -// property. -CZMQ_EXPORT bool - zfile_is_readable (zfile_t *self); - -// Return true if the file is writeable by this process. If you want this -// to reflect any external changes, call zfile_restat before checking this -// property. -CZMQ_EXPORT bool - zfile_is_writeable (zfile_t *self); - -// Check if file has stopped changing and can be safely processed. -// Updates the file statistics from disk at every call. -CZMQ_EXPORT bool - zfile_is_stable (zfile_t *self); - -// Return true if the file was changed on disk since the zfile_t object -// was created, or the last zfile_restat() call made on it. -CZMQ_EXPORT bool - zfile_has_changed (zfile_t *self); - -// Remove the file from disk -CZMQ_EXPORT void - zfile_remove (zfile_t *self); - -// Open file for reading -// Returns 0 if OK, -1 if not found or not accessible -CZMQ_EXPORT int - zfile_input (zfile_t *self); - -// Open file for writing, creating directory if needed -// File is created if necessary; chunks can be written to file at any -// location. Returns 0 if OK, -1 if error. -CZMQ_EXPORT int - zfile_output (zfile_t *self); - -// Read chunk from file at specified position. If this was the last chunk, -// sets the eof property. Returns a null chunk in case of error. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zchunk_t * - zfile_read (zfile_t *self, size_t bytes, off_t offset); - -// Returns true if zfile_read() just read the last chunk in the file. -CZMQ_EXPORT bool - zfile_eof (zfile_t *self); - -// Write chunk to file at specified position -// Return 0 if OK, else -1 -CZMQ_EXPORT int - zfile_write (zfile_t *self, zchunk_t *chunk, off_t offset); - -// Read next line of text from file. Returns a pointer to the text line, -// or NULL if there was nothing more to read from the file. -CZMQ_EXPORT const char * - zfile_readln (zfile_t *self); - -// Close file, if open -CZMQ_EXPORT void - zfile_close (zfile_t *self); - -// Return file handle, if opened -CZMQ_EXPORT FILE * - zfile_handle (zfile_t *self); - -// Calculate SHA1 digest for file, using zdigest class. -CZMQ_EXPORT const char * - zfile_digest (zfile_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zfile_test (bool verbose); - -// @end - - -// @interface -// These methods are deprecated, and now moved to zsys class. -CZMQ_EXPORT bool - zfile_exists (const char *filename); -CZMQ_EXPORT ssize_t - zfile_size (const char *filename); -CZMQ_EXPORT mode_t - zfile_mode (const char *filename); -CZMQ_EXPORT int - zfile_delete (const char *filename); -CZMQ_EXPORT bool - zfile_stable (const char *filename); -CZMQ_EXPORT int - zfile_mkdir (const char *pathname); -CZMQ_EXPORT int - zfile_rmdir (const char *pathname); -CZMQ_EXPORT void - zfile_mode_private (void); -CZMQ_EXPORT void - zfile_mode_default (void); -// @end - -#ifdef __cplusplus -} -#endif - - -#endif // __ZFILE_H_INCLUDED__ diff --git a/phonelibs/zmq/arm/include/zframe.h b/phonelibs/zmq/arm/include/zframe.h deleted file mode 100644 index 728093c36c..0000000000 --- a/phonelibs/zmq/arm/include/zframe.h +++ /dev/null @@ -1,176 +0,0 @@ -/* ========================================================================= - zframe - working with single message frames - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZFRAME_H_INCLUDED__ -#define __ZFRAME_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zframe.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -#define ZFRAME_MORE 1 // -#define ZFRAME_REUSE 2 // -#define ZFRAME_DONTWAIT 4 // - -// Create a new frame. If size is not null, allocates the frame data -// to the specified size. If additionally, data is not null, copies -// size octets from the specified data into the frame body. -CZMQ_EXPORT zframe_t * - zframe_new (const void *data, size_t size); - -// Create an empty (zero-sized) frame -CZMQ_EXPORT zframe_t * - zframe_new_empty (void); - -// Create a frame with a specified string content. -CZMQ_EXPORT zframe_t * - zframe_from (const char *string); - -// Receive frame from socket, returns zframe_t object or NULL if the recv -// was interrupted. Does a blocking recv, if you want to not block then use -// zpoller or zloop. -CZMQ_EXPORT zframe_t * - zframe_recv (void *source); - -// Destroy a frame -CZMQ_EXPORT void - zframe_destroy (zframe_t **self_p); - -// Send a frame to a socket, destroy frame after sending. -// Return -1 on error, 0 on success. -CZMQ_EXPORT int - zframe_send (zframe_t **self_p, void *dest, int flags); - -// Return number of bytes in frame data -CZMQ_EXPORT size_t - zframe_size (zframe_t *self); - -// Return address of frame data -CZMQ_EXPORT byte * - zframe_data (zframe_t *self); - -// Return meta data property for frame -// Caller must free string when finished with it. -CZMQ_EXPORT const char * - zframe_meta (zframe_t *self, const char *property); - -// Create a new frame that duplicates an existing frame. If frame is null, -// or memory was exhausted, returns null. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zframe_dup (zframe_t *self); - -// Return frame data encoded as printable hex string, useful for 0MQ UUIDs. -// Caller must free string when finished with it. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zframe_strhex (zframe_t *self); - -// Return frame data copied into freshly allocated string -// Caller must free string when finished with it. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zframe_strdup (zframe_t *self); - -// Return TRUE if frame body is equal to string, excluding terminator -CZMQ_EXPORT bool - zframe_streq (zframe_t *self, const char *string); - -// Return frame MORE indicator (1 or 0), set when reading frame from socket -// or by the zframe_set_more() method -CZMQ_EXPORT int - zframe_more (zframe_t *self); - -// Set frame MORE indicator (1 or 0). Note this is NOT used when sending -// frame to socket, you have to specify flag explicitly. -CZMQ_EXPORT void - zframe_set_more (zframe_t *self, int more); - -// Return TRUE if two frames have identical size and data -// If either frame is NULL, equality is always false. -CZMQ_EXPORT bool - zframe_eq (zframe_t *self, zframe_t *other); - -// Set new contents for frame -CZMQ_EXPORT void - zframe_reset (zframe_t *self, const void *data, size_t size); - -// Send message to zsys log sink (may be stdout, or system facility as -// configured by zsys_set_logstream). Prefix shows before frame, if not null. -CZMQ_EXPORT void - zframe_print (zframe_t *self, const char *prefix); - -// Probe the supplied object, and report if it looks like a zframe_t. -CZMQ_EXPORT bool - zframe_is (void *self); - -// Self test of this class. -CZMQ_EXPORT void - zframe_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Return frame routing ID, if the frame came from a ZMQ_SERVER socket. -// Else returns zero. -CZMQ_EXPORT uint32_t - zframe_routing_id (zframe_t *self); - -// *** Draft method, for development use, may change without warning *** -// Set routing ID on frame. This is used if/when the frame is sent to a -// ZMQ_SERVER socket. -CZMQ_EXPORT void - zframe_set_routing_id (zframe_t *self, uint32_t routing_id); - -// *** Draft method, for development use, may change without warning *** -// Return frame group of radio-dish pattern. -CZMQ_EXPORT const char * - zframe_group (zframe_t *self); - -// *** Draft method, for development use, may change without warning *** -// Set group on frame. This is used if/when the frame is sent to a -// ZMQ_RADIO socket. -// Return -1 on error, 0 on success. -CZMQ_EXPORT int - zframe_set_group (zframe_t *self, const char *group); - -#endif // CZMQ_BUILD_DRAFT_API -// @end - - -// DEPRECATED as poor style -- callers should use zloop or zpoller -// Receive a new frame off the socket. Returns newly allocated frame, or -// NULL if there was no input waiting, or if the read was interrupted. -CZMQ_EXPORT zframe_t * - zframe_recv_nowait (void *source); - -// DEPRECATED as inconsistent; breaks principle that logging should all go -// to a single destination. -// Print contents of the frame to FILE stream. -CZMQ_EXPORT void - zframe_fprint (zframe_t *self, const char *prefix, FILE *file); - -// Deprecated method aliases -#define zframe_print_to_stream(s,p,F) zframe_fprint(s,p,F) - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zgossip.h b/phonelibs/zmq/arm/include/zgossip.h deleted file mode 100644 index 647cb28c08..0000000000 --- a/phonelibs/zmq/arm/include/zgossip.h +++ /dev/null @@ -1,95 +0,0 @@ -/* ========================================================================= - zgossip - zgossip server - - ** WARNING ************************************************************* - THIS SOURCE FILE IS 100% GENERATED. If you edit this file, you will lose - your changes at the next build cycle. This is great for temporary printf - statements. DO NOT MAKE ANY CHANGES YOU WISH TO KEEP. The correct places - for commits are: - - * The XML model used for this code generation: zgossip.xml, or - * The code generation script that built this file: zproto_server_c - ************************************************************************ - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef ZGOSSIP_H_INCLUDED -#define ZGOSSIP_H_INCLUDED - -#include "czmq.h" - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// To work with zgossip, use the CZMQ zactor API: -// -// Create new zgossip instance, passing logging prefix: -// -// zactor_t *zgossip = zactor_new (zgossip, "myname"); -// -// Destroy zgossip instance -// -// zactor_destroy (&zgossip); -// -// Enable verbose logging of commands and activity: -// -// zstr_send (zgossip, "VERBOSE"); -// -// Bind zgossip to specified endpoint. TCP endpoints may specify -// the port number as "*" to aquire an ephemeral port: -// -// zstr_sendx (zgossip, "BIND", endpoint, NULL); -// -// Return assigned port number, specifically when BIND was done using an -// an ephemeral port: -// -// zstr_sendx (zgossip, "PORT", NULL); -// char *command, *port_str; -// zstr_recvx (zgossip, &command, &port_str, NULL); -// assert (streq (command, "PORT")); -// -// Specify configuration file to load, overwriting any previous loaded -// configuration file or options: -// -// zstr_sendx (zgossip, "LOAD", filename, NULL); -// -// Set configuration path value: -// -// zstr_sendx (zgossip, "SET", path, value, NULL); -// -// Save configuration data to config file on disk: -// -// zstr_sendx (zgossip, "SAVE", filename, NULL); -// -// Send zmsg_t instance to zgossip: -// -// zactor_send (zgossip, &msg); -// -// Receive zmsg_t instance from zgossip: -// -// zmsg_t *msg = zactor_recv (zgossip); -// -// This is the zgossip constructor as a zactor_fn: -// -CZMQ_EXPORT void - zgossip (zsock_t *pipe, void *args); - -// Self test of this class -CZMQ_EXPORT void - zgossip_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zhash.h b/phonelibs/zmq/arm/include/zhash.h deleted file mode 100644 index 929bc2683a..0000000000 --- a/phonelibs/zmq/arm/include/zhash.h +++ /dev/null @@ -1,198 +0,0 @@ -/* ========================================================================= - zhash - generic type-free hash container (simple) - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZHASH_H_INCLUDED__ -#define __ZHASH_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zhash.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has legacy methods, which will be removed over time. You -// should not use them, and migrate any code that is still using them. -// Callback function for zhash_freefn method -typedef void (zhash_free_fn) ( - void *data); - -// Callback function for zhash_foreach method. Deprecated. -typedef int (zhash_foreach_fn) ( - const char *key, void *item, void *argument); - -// Create a new, empty hash container -CZMQ_EXPORT zhash_t * - zhash_new (void); - -// Unpack binary frame into a new hash table. Packed data must follow format -// defined by zhash_pack. Hash table is set to autofree. An empty frame -// unpacks to an empty hash table. -CZMQ_EXPORT zhash_t * - zhash_unpack (zframe_t *frame); - -// Destroy a hash container and all items in it -CZMQ_EXPORT void - zhash_destroy (zhash_t **self_p); - -// Insert item into hash table with specified key and item. -// If key is already present returns -1 and leaves existing item unchanged -// Returns 0 on success. -CZMQ_EXPORT int - zhash_insert (zhash_t *self, const char *key, void *item); - -// Update item into hash table with specified key and item. -// If key is already present, destroys old item and inserts new one. -// Use free_fn method to ensure deallocator is properly called on item. -CZMQ_EXPORT void - zhash_update (zhash_t *self, const char *key, void *item); - -// Remove an item specified by key from the hash table. If there was no such -// item, this function does nothing. -CZMQ_EXPORT void - zhash_delete (zhash_t *self, const char *key); - -// Return the item at the specified key, or null -CZMQ_EXPORT void * - zhash_lookup (zhash_t *self, const char *key); - -// Reindexes an item from an old key to a new key. If there was no such -// item, does nothing. Returns 0 if successful, else -1. -CZMQ_EXPORT int - zhash_rename (zhash_t *self, const char *old_key, const char *new_key); - -// Set a free function for the specified hash table item. When the item is -// destroyed, the free function, if any, is called on that item. -// Use this when hash items are dynamically allocated, to ensure that -// you don't have memory leaks. You can pass 'free' or NULL as a free_fn. -// Returns the item, or NULL if there is no such item. -CZMQ_EXPORT void * - zhash_freefn (zhash_t *self, const char *key, zhash_free_fn free_fn); - -// Return the number of keys/items in the hash table -CZMQ_EXPORT size_t - zhash_size (zhash_t *self); - -// Make copy of hash table; if supplied table is null, returns null. -// Does not copy items themselves. Rebuilds new table so may be slow on -// very large tables. NOTE: only works with item values that are strings -// since there's no other way to know how to duplicate the item value. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zhash_t * - zhash_dup (zhash_t *self); - -// Return keys for items in table -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlist_t * - zhash_keys (zhash_t *self); - -// Simple iterator; returns first item in hash table, in no given order, -// or NULL if the table is empty. This method is simpler to use than the -// foreach() method, which is deprecated. To access the key for this item -// use zhash_cursor(). NOTE: do NOT modify the table while iterating. -CZMQ_EXPORT void * - zhash_first (zhash_t *self); - -// Simple iterator; returns next item in hash table, in no given order, -// or NULL if the last item was already returned. Use this together with -// zhash_first() to process all items in a hash table. If you need the -// items in sorted order, use zhash_keys() and then zlist_sort(). To -// access the key for this item use zhash_cursor(). NOTE: do NOT modify -// the table while iterating. -CZMQ_EXPORT void * - zhash_next (zhash_t *self); - -// After a successful first/next method, returns the key for the item that -// was returned. This is a constant string that you may not modify or -// deallocate, and which lasts as long as the item in the hash. After an -// unsuccessful first/next, returns NULL. -CZMQ_EXPORT const char * - zhash_cursor (zhash_t *self); - -// Add a comment to hash table before saving to disk. You can add as many -// comment lines as you like. These comment lines are discarded when loading -// the file. If you use a null format, all comments are deleted. -CZMQ_EXPORT void - zhash_comment (zhash_t *self, const char *format, ...); - -// Serialize hash table to a binary frame that can be sent in a message. -// The packed format is compatible with the 'dictionary' type defined in -// http://rfc.zeromq.org/spec:35/FILEMQ, and implemented by zproto: -// -// ; A list of name/value pairs -// dictionary = dict-count *( dict-name dict-value ) -// dict-count = number-4 -// dict-value = longstr -// dict-name = string -// -// ; Strings are always length + text contents -// longstr = number-4 *VCHAR -// string = number-1 *VCHAR -// -// ; Numbers are unsigned integers in network byte order -// number-1 = 1OCTET -// number-4 = 4OCTET -// -// Comments are not included in the packed data. Item values MUST be -// strings. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zhash_pack (zhash_t *self); - -// Save hash table to a text file in name=value format. Hash values must be -// printable strings; keys may not contain '=' character. Returns 0 if OK, -// else -1 if a file error occurred. -CZMQ_EXPORT int - zhash_save (zhash_t *self, const char *filename); - -// Load hash table from a text file in name=value format; hash table must -// already exist. Hash values must printable strings; keys may not contain -// '=' character. Returns 0 if OK, else -1 if a file was not readable. -CZMQ_EXPORT int - zhash_load (zhash_t *self, const char *filename); - -// When a hash table was loaded from a file by zhash_load, this method will -// reload the file if it has been modified since, and is "stable", i.e. not -// still changing. Returns 0 if OK, -1 if there was an error reloading the -// file. -CZMQ_EXPORT int - zhash_refresh (zhash_t *self); - -// Set hash for automatic value destruction -CZMQ_EXPORT void - zhash_autofree (zhash_t *self); - -// *** Deprecated method, slated for removal: avoid using it *** -// Apply function to each item in the hash table. Items are iterated in no -// defined order. Stops if callback function returns non-zero and returns -// final return code from callback function (zero = success). Deprecated. -CZMQ_EXPORT int - zhash_foreach (zhash_t *self, zhash_foreach_fn callback, void *argument); - -// Self test of this class. -CZMQ_EXPORT void - zhash_test (bool verbose); - -// @ignore -CZMQ_EXPORT void - zhash_comment (zhash_t *self, const char *format, ...) CHECK_PRINTF (2); -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zhashx.h b/phonelibs/zmq/arm/include/zhashx.h deleted file mode 100644 index 8776073156..0000000000 --- a/phonelibs/zmq/arm/include/zhashx.h +++ /dev/null @@ -1,301 +0,0 @@ -/* ========================================================================= - zhashx - extended generic type-free hash container - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZHASHX_H_INCLUDED__ -#define __ZHASHX_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zhashx.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// This class has legacy methods, which will be removed over time. You -// should not use them, and migrate any code that is still using them. -// Destroy an item -typedef void (zhashx_destructor_fn) ( - void **item); - -// Duplicate an item -typedef void * (zhashx_duplicator_fn) ( - const void *item); - -// Compare two items, for sorting -typedef int (zhashx_comparator_fn) ( - const void *item1, const void *item2); - -// compare two items, for sorting -typedef void (zhashx_free_fn) ( - void *data); - -// compare two items, for sorting -typedef size_t (zhashx_hash_fn) ( - const void *key); - -// Serializes an item to a longstr. -// The caller takes ownership of the newly created object. -typedef char * (zhashx_serializer_fn) ( - const void *item); - -// Deserializes a longstr into an item. -// The caller takes ownership of the newly created object. -typedef void * (zhashx_deserializer_fn) ( - const char *item_str); - -// Callback function for zhashx_foreach method. -// This callback is deprecated and you should use zhashx_first/_next instead. -typedef int (zhashx_foreach_fn) ( - const char *key, void *item, void *argument); - -// Create a new, empty hash container -CZMQ_EXPORT zhashx_t * - zhashx_new (void); - -// Unpack binary frame into a new hash table. Packed data must follow format -// defined by zhashx_pack. Hash table is set to autofree. An empty frame -// unpacks to an empty hash table. -CZMQ_EXPORT zhashx_t * - zhashx_unpack (zframe_t *frame); - -// Destroy a hash container and all items in it -CZMQ_EXPORT void - zhashx_destroy (zhashx_t **self_p); - -// Insert item into hash table with specified key and item. -// If key is already present returns -1 and leaves existing item unchanged -// Returns 0 on success. -CZMQ_EXPORT int - zhashx_insert (zhashx_t *self, const void *key, void *item); - -// Update or insert item into hash table with specified key and item. If the -// key is already present, destroys old item and inserts new one. If you set -// a container item destructor, this is called on the old value. If the key -// was not already present, inserts a new item. Sets the hash cursor to the -// new item. -CZMQ_EXPORT void - zhashx_update (zhashx_t *self, const void *key, void *item); - -// Remove an item specified by key from the hash table. If there was no such -// item, this function does nothing. -CZMQ_EXPORT void - zhashx_delete (zhashx_t *self, const void *key); - -// Delete all items from the hash table. If the key destructor is -// set, calls it on every key. If the item destructor is set, calls -// it on every item. -CZMQ_EXPORT void - zhashx_purge (zhashx_t *self); - -// Return the item at the specified key, or null -CZMQ_EXPORT void * - zhashx_lookup (zhashx_t *self, const void *key); - -// Reindexes an item from an old key to a new key. If there was no such -// item, does nothing. Returns 0 if successful, else -1. -CZMQ_EXPORT int - zhashx_rename (zhashx_t *self, const void *old_key, const void *new_key); - -// Set a free function for the specified hash table item. When the item is -// destroyed, the free function, if any, is called on that item. -// Use this when hash items are dynamically allocated, to ensure that -// you don't have memory leaks. You can pass 'free' or NULL as a free_fn. -// Returns the item, or NULL if there is no such item. -CZMQ_EXPORT void * - zhashx_freefn (zhashx_t *self, const void *key, zhashx_free_fn free_fn); - -// Return the number of keys/items in the hash table -CZMQ_EXPORT size_t - zhashx_size (zhashx_t *self); - -// Return a zlistx_t containing the keys for the items in the -// table. Uses the key_duplicator to duplicate all keys and sets the -// key_destructor as destructor for the list. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlistx_t * - zhashx_keys (zhashx_t *self); - -// Return a zlistx_t containing the values for the items in the -// table. Uses the duplicator to duplicate all items and sets the -// destructor as destructor for the list. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlistx_t * - zhashx_values (zhashx_t *self); - -// Simple iterator; returns first item in hash table, in no given order, -// or NULL if the table is empty. This method is simpler to use than the -// foreach() method, which is deprecated. To access the key for this item -// use zhashx_cursor(). NOTE: do NOT modify the table while iterating. -CZMQ_EXPORT void * - zhashx_first (zhashx_t *self); - -// Simple iterator; returns next item in hash table, in no given order, -// or NULL if the last item was already returned. Use this together with -// zhashx_first() to process all items in a hash table. If you need the -// items in sorted order, use zhashx_keys() and then zlistx_sort(). To -// access the key for this item use zhashx_cursor(). NOTE: do NOT modify -// the table while iterating. -CZMQ_EXPORT void * - zhashx_next (zhashx_t *self); - -// After a successful first/next method, returns the key for the item that -// was returned. This is a constant string that you may not modify or -// deallocate, and which lasts as long as the item in the hash. After an -// unsuccessful first/next, returns NULL. -CZMQ_EXPORT const void * - zhashx_cursor (zhashx_t *self); - -// Add a comment to hash table before saving to disk. You can add as many -// comment lines as you like. These comment lines are discarded when loading -// the file. If you use a null format, all comments are deleted. -CZMQ_EXPORT void - zhashx_comment (zhashx_t *self, const char *format, ...); - -// Save hash table to a text file in name=value format. Hash values must be -// printable strings; keys may not contain '=' character. Returns 0 if OK, -// else -1 if a file error occurred. -CZMQ_EXPORT int - zhashx_save (zhashx_t *self, const char *filename); - -// Load hash table from a text file in name=value format; hash table must -// already exist. Hash values must printable strings; keys may not contain -// '=' character. Returns 0 if OK, else -1 if a file was not readable. -CZMQ_EXPORT int - zhashx_load (zhashx_t *self, const char *filename); - -// When a hash table was loaded from a file by zhashx_load, this method will -// reload the file if it has been modified since, and is "stable", i.e. not -// still changing. Returns 0 if OK, -1 if there was an error reloading the -// file. -CZMQ_EXPORT int - zhashx_refresh (zhashx_t *self); - -// Serialize hash table to a binary frame that can be sent in a message. -// The packed format is compatible with the 'dictionary' type defined in -// http://rfc.zeromq.org/spec:35/FILEMQ, and implemented by zproto: -// -// ; A list of name/value pairs -// dictionary = dict-count *( dict-name dict-value ) -// dict-count = number-4 -// dict-value = longstr -// dict-name = string -// -// ; Strings are always length + text contents -// longstr = number-4 *VCHAR -// string = number-1 *VCHAR -// -// ; Numbers are unsigned integers in network byte order -// number-1 = 1OCTET -// number-4 = 4OCTET -// -// Comments are not included in the packed data. Item values MUST be -// strings. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zhashx_pack (zhashx_t *self); - -// Make a copy of the list; items are duplicated if you set a duplicator -// for the list, otherwise not. Copying a null reference returns a null -// reference. Note that this method's behavior changed slightly for CZMQ -// v3.x, as it does not set nor respect autofree. It does however let you -// duplicate any hash table safely. The old behavior is in zhashx_dup_v2. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zhashx_t * - zhashx_dup (zhashx_t *self); - -// Set a user-defined deallocator for hash items; by default items are not -// freed when the hash is destroyed. -CZMQ_EXPORT void - zhashx_set_destructor (zhashx_t *self, zhashx_destructor_fn destructor); - -// Set a user-defined duplicator for hash items; by default items are not -// copied when the hash is duplicated. -CZMQ_EXPORT void - zhashx_set_duplicator (zhashx_t *self, zhashx_duplicator_fn duplicator); - -// Set a user-defined deallocator for keys; by default keys are freed -// when the hash is destroyed using free(). -CZMQ_EXPORT void - zhashx_set_key_destructor (zhashx_t *self, zhashx_destructor_fn destructor); - -// Set a user-defined duplicator for keys; by default keys are duplicated -// using strdup. -CZMQ_EXPORT void - zhashx_set_key_duplicator (zhashx_t *self, zhashx_duplicator_fn duplicator); - -// Set a user-defined comparator for keys; by default keys are -// compared using strcmp. -CZMQ_EXPORT void - zhashx_set_key_comparator (zhashx_t *self, zhashx_comparator_fn comparator); - -// Set a user-defined comparator for keys; by default keys are -// compared using strcmp. -CZMQ_EXPORT void - zhashx_set_key_hasher (zhashx_t *self, zhashx_hash_fn hasher); - -// Make copy of hash table; if supplied table is null, returns null. -// Does not copy items themselves. Rebuilds new table so may be slow on -// very large tables. NOTE: only works with item values that are strings -// since there's no other way to know how to duplicate the item value. -CZMQ_EXPORT zhashx_t * - zhashx_dup_v2 (zhashx_t *self); - -// *** Deprecated method, slated for removal: avoid using it *** -// Set hash for automatic value destruction. This method is deprecated -// and you should use set_destructor instead. -CZMQ_EXPORT void - zhashx_autofree (zhashx_t *self); - -// *** Deprecated method, slated for removal: avoid using it *** -// Apply function to each item in the hash table. Items are iterated in no -// defined order. Stops if callback function returns non-zero and returns -// final return code from callback function (zero = success). This method -// is deprecated and you should use zhashx_first/_next instead. -CZMQ_EXPORT int - zhashx_foreach (zhashx_t *self, zhashx_foreach_fn callback, void *argument); - -// Self test of this class. -CZMQ_EXPORT void - zhashx_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Same as unpack but uses a user-defined deserializer function to convert -// a longstr back into item format. -CZMQ_EXPORT zhashx_t * - zhashx_unpack_own (zframe_t *frame, zhashx_deserializer_fn deserializer); - -// *** Draft method, for development use, may change without warning *** -// Same as pack but uses a user-defined serializer function to convert items -// into longstr. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zhashx_pack_own (zhashx_t *self, zhashx_serializer_fn serializer); - -#endif // CZMQ_BUILD_DRAFT_API -// @ignore -CZMQ_EXPORT void - zhashx_comment (zhashx_t *self, const char *format, ...) CHECK_PRINTF (2); -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/ziflist.h b/phonelibs/zmq/arm/include/ziflist.h deleted file mode 100644 index cb2b144802..0000000000 --- a/phonelibs/zmq/arm/include/ziflist.h +++ /dev/null @@ -1,77 +0,0 @@ -/* ========================================================================= - ziflist - List of network interfaces available on system - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZIFLIST_H_INCLUDED__ -#define __ZIFLIST_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/ziflist.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Get a list of network interfaces currently defined on the system -CZMQ_EXPORT ziflist_t * - ziflist_new (void); - -// Destroy a ziflist instance -CZMQ_EXPORT void - ziflist_destroy (ziflist_t **self_p); - -// Reload network interfaces from system -CZMQ_EXPORT void - ziflist_reload (ziflist_t *self); - -// Return the number of network interfaces on system -CZMQ_EXPORT size_t - ziflist_size (ziflist_t *self); - -// Get first network interface, return NULL if there are none -CZMQ_EXPORT const char * - ziflist_first (ziflist_t *self); - -// Get next network interface, return NULL if we hit the last one -CZMQ_EXPORT const char * - ziflist_next (ziflist_t *self); - -// Return the current interface IP address as a printable string -CZMQ_EXPORT const char * - ziflist_address (ziflist_t *self); - -// Return the current interface broadcast address as a printable string -CZMQ_EXPORT const char * - ziflist_broadcast (ziflist_t *self); - -// Return the current interface network mask as a printable string -CZMQ_EXPORT const char * - ziflist_netmask (ziflist_t *self); - -// Return the list of interfaces. -CZMQ_EXPORT void - ziflist_print (ziflist_t *self); - -// Self test of this class. -CZMQ_EXPORT void - ziflist_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zlist.h b/phonelibs/zmq/arm/include/zlist.h deleted file mode 100644 index 1dcd39b995..0000000000 --- a/phonelibs/zmq/arm/include/zlist.h +++ /dev/null @@ -1,158 +0,0 @@ -/* ========================================================================= - zlist - simple generic list container - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZLIST_H_INCLUDED__ -#define __ZLIST_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zlist.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Comparison function e.g. for sorting and removing. -typedef int (zlist_compare_fn) ( - void *item1, void *item2); - -// Callback function for zlist_freefn method -typedef void (zlist_free_fn) ( - void *data); - -// Create a new list container -CZMQ_EXPORT zlist_t * - zlist_new (void); - -// Destroy a list container -CZMQ_EXPORT void - zlist_destroy (zlist_t **self_p); - -// Return the item at the head of list. If the list is empty, returns NULL. -// Leaves cursor pointing at the head item, or NULL if the list is empty. -CZMQ_EXPORT void * - zlist_first (zlist_t *self); - -// Return the next item. If the list is empty, returns NULL. To move to -// the start of the list call zlist_first (). Advances the cursor. -CZMQ_EXPORT void * - zlist_next (zlist_t *self); - -// Return the item at the tail of list. If the list is empty, returns NULL. -// Leaves cursor pointing at the tail item, or NULL if the list is empty. -CZMQ_EXPORT void * - zlist_last (zlist_t *self); - -// Return first item in the list, or null, leaves the cursor -CZMQ_EXPORT void * - zlist_head (zlist_t *self); - -// Return last item in the list, or null, leaves the cursor -CZMQ_EXPORT void * - zlist_tail (zlist_t *self); - -// Return the current item of list. If the list is empty, returns NULL. -// Leaves cursor pointing at the current item, or NULL if the list is empty. -CZMQ_EXPORT void * - zlist_item (zlist_t *self); - -// Append an item to the end of the list, return 0 if OK or -1 if this -// failed for some reason (out of memory). Note that if a duplicator has -// been set, this method will also duplicate the item. -CZMQ_EXPORT int - zlist_append (zlist_t *self, void *item); - -// Push an item to the start of the list, return 0 if OK or -1 if this -// failed for some reason (out of memory). Note that if a duplicator has -// been set, this method will also duplicate the item. -CZMQ_EXPORT int - zlist_push (zlist_t *self, void *item); - -// Pop the item off the start of the list, if any -CZMQ_EXPORT void * - zlist_pop (zlist_t *self); - -// Checks if an item already is present. Uses compare method to determine if -// items are equal. If the compare method is NULL the check will only compare -// pointers. Returns true if item is present else false. -CZMQ_EXPORT bool - zlist_exists (zlist_t *self, void *item); - -// Remove the specified item from the list if present -CZMQ_EXPORT void - zlist_remove (zlist_t *self, void *item); - -// Make a copy of list. If the list has autofree set, the copied list will -// duplicate all items, which must be strings. Otherwise, the list will hold -// pointers back to the items in the original list. If list is null, returns -// NULL. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zlist_t * - zlist_dup (zlist_t *self); - -// Purge all items from list -CZMQ_EXPORT void - zlist_purge (zlist_t *self); - -// Return number of items in the list -CZMQ_EXPORT size_t - zlist_size (zlist_t *self); - -// Sort the list. If the compare function is null, sorts the list by -// ascending key value using a straight ASCII comparison. If you specify -// a compare function, this decides how items are sorted. The sort is not -// stable, so may reorder items with the same keys. The algorithm used is -// combsort, a compromise between performance and simplicity. -CZMQ_EXPORT void - zlist_sort (zlist_t *self, zlist_compare_fn compare); - -// Set list for automatic item destruction; item values MUST be strings. -// By default a list item refers to a value held elsewhere. When you set -// this, each time you append or push a list item, zlist will take a copy -// of the string value. Then, when you destroy the list, it will free all -// item values automatically. If you use any other technique to allocate -// list values, you must free them explicitly before destroying the list. -// The usual technique is to pop list items and destroy them, until the -// list is empty. -CZMQ_EXPORT void - zlist_autofree (zlist_t *self); - -// Sets a compare function for this list. The function compares two items. -// It returns an integer less than, equal to, or greater than zero if the -// first item is found, respectively, to be less than, to match, or be -// greater than the second item. -// This function is used for sorting, removal and exists checking. -CZMQ_EXPORT void - zlist_comparefn (zlist_t *self, zlist_compare_fn fn); - -// Set a free function for the specified list item. When the item is -// destroyed, the free function, if any, is called on that item. -// Use this when list items are dynamically allocated, to ensure that -// you don't have memory leaks. You can pass 'free' or NULL as a free_fn. -// Returns the item, or NULL if there is no such item. -CZMQ_EXPORT void * - zlist_freefn (zlist_t *self, void *item, zlist_free_fn fn, bool at_tail); - -// Self test of this class. -CZMQ_EXPORT void - zlist_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zlistx.h b/phonelibs/zmq/arm/include/zlistx.h deleted file mode 100644 index 512637cef3..0000000000 --- a/phonelibs/zmq/arm/include/zlistx.h +++ /dev/null @@ -1,205 +0,0 @@ -/* ========================================================================= - zlistx - extended generic list container - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZLISTX_H_INCLUDED__ -#define __ZLISTX_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zlistx.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Destroy an item -typedef void (zlistx_destructor_fn) ( - void **item); - -// Duplicate an item -typedef void * (zlistx_duplicator_fn) ( - const void *item); - -// Compare two items, for sorting -typedef int (zlistx_comparator_fn) ( - const void *item1, const void *item2); - -// Create a new, empty list. -CZMQ_EXPORT zlistx_t * - zlistx_new (void); - -// Destroy a list. If an item destructor was specified, all items in the -// list are automatically destroyed as well. -CZMQ_EXPORT void - zlistx_destroy (zlistx_t **self_p); - -// Add an item to the head of the list. Calls the item duplicator, if any, -// on the item. Resets cursor to list head. Returns an item handle on -// success, NULL if memory was exhausted. -CZMQ_EXPORT void * - zlistx_add_start (zlistx_t *self, void *item); - -// Add an item to the tail of the list. Calls the item duplicator, if any, -// on the item. Resets cursor to list head. Returns an item handle on -// success, NULL if memory was exhausted. -CZMQ_EXPORT void * - zlistx_add_end (zlistx_t *self, void *item); - -// Return the number of items in the list -CZMQ_EXPORT size_t - zlistx_size (zlistx_t *self); - -// Return first item in the list, or null, leaves the cursor -CZMQ_EXPORT void * - zlistx_head (zlistx_t *self); - -// Return last item in the list, or null, leaves the cursor -CZMQ_EXPORT void * - zlistx_tail (zlistx_t *self); - -// Return the item at the head of list. If the list is empty, returns NULL. -// Leaves cursor pointing at the head item, or NULL if the list is empty. -CZMQ_EXPORT void * - zlistx_first (zlistx_t *self); - -// Return the next item. At the end of the list (or in an empty list), -// returns NULL. Use repeated zlistx_next () calls to work through the list -// from zlistx_first (). First time, acts as zlistx_first(). -CZMQ_EXPORT void * - zlistx_next (zlistx_t *self); - -// Return the previous item. At the start of the list (or in an empty list), -// returns NULL. Use repeated zlistx_prev () calls to work through the list -// backwards from zlistx_last (). First time, acts as zlistx_last(). -CZMQ_EXPORT void * - zlistx_prev (zlistx_t *self); - -// Return the item at the tail of list. If the list is empty, returns NULL. -// Leaves cursor pointing at the tail item, or NULL if the list is empty. -CZMQ_EXPORT void * - zlistx_last (zlistx_t *self); - -// Returns the value of the item at the cursor, or NULL if the cursor is -// not pointing to an item. -CZMQ_EXPORT void * - zlistx_item (zlistx_t *self); - -// Returns the handle of the item at the cursor, or NULL if the cursor is -// not pointing to an item. -CZMQ_EXPORT void * - zlistx_cursor (zlistx_t *self); - -// Returns the item associated with the given list handle, or NULL if passed -// in handle is NULL. Asserts that the passed in handle points to a list element. -CZMQ_EXPORT void * - zlistx_handle_item (void *handle); - -// Find an item in the list, searching from the start. Uses the item -// comparator, if any, else compares item values directly. Returns the -// item handle found, or NULL. Sets the cursor to the found item, if any. -CZMQ_EXPORT void * - zlistx_find (zlistx_t *self, void *item); - -// Detach an item from the list, using its handle. The item is not modified, -// and the caller is responsible for destroying it if necessary. If handle is -// null, detaches the first item on the list. Returns item that was detached, -// or null if none was. If cursor was at item, moves cursor to previous item, -// so you can detach items while iterating forwards through a list. -CZMQ_EXPORT void * - zlistx_detach (zlistx_t *self, void *handle); - -// Detach item at the cursor, if any, from the list. The item is not modified, -// and the caller is responsible for destroying it as necessary. Returns item -// that was detached, or null if none was. Moves cursor to previous item, so -// you can detach items while iterating forwards through a list. -CZMQ_EXPORT void * - zlistx_detach_cur (zlistx_t *self); - -// Delete an item, using its handle. Calls the item destructor is any is -// set. If handle is null, deletes the first item on the list. Returns 0 -// if an item was deleted, -1 if not. If cursor was at item, moves cursor -// to previous item, so you can delete items while iterating forwards -// through a list. -CZMQ_EXPORT int - zlistx_delete (zlistx_t *self, void *handle); - -// Move an item to the start of the list, via its handle. -CZMQ_EXPORT void - zlistx_move_start (zlistx_t *self, void *handle); - -// Move an item to the end of the list, via its handle. -CZMQ_EXPORT void - zlistx_move_end (zlistx_t *self, void *handle); - -// Remove all items from the list, and destroy them if the item destructor -// is set. -CZMQ_EXPORT void - zlistx_purge (zlistx_t *self); - -// Sort the list. If an item comparator was set, calls that to compare -// items, otherwise compares on item value. The sort is not stable, so may -// reorder equal items. -CZMQ_EXPORT void - zlistx_sort (zlistx_t *self); - -// Create a new node and insert it into a sorted list. Calls the item -// duplicator, if any, on the item. If low_value is true, starts searching -// from the start of the list, otherwise searches from the end. Use the item -// comparator, if any, to find where to place the new node. Returns a handle -// to the new node, or NULL if memory was exhausted. Resets the cursor to the -// list head. -CZMQ_EXPORT void * - zlistx_insert (zlistx_t *self, void *item, bool low_value); - -// Move an item, specified by handle, into position in a sorted list. Uses -// the item comparator, if any, to determine the new location. If low_value -// is true, starts searching from the start of the list, otherwise searches -// from the end. -CZMQ_EXPORT void - zlistx_reorder (zlistx_t *self, void *handle, bool low_value); - -// Make a copy of the list; items are duplicated if you set a duplicator -// for the list, otherwise not. Copying a null reference returns a null -// reference. -CZMQ_EXPORT zlistx_t * - zlistx_dup (zlistx_t *self); - -// Set a user-defined deallocator for list items; by default items are not -// freed when the list is destroyed. -CZMQ_EXPORT void - zlistx_set_destructor (zlistx_t *self, zlistx_destructor_fn destructor); - -// Set a user-defined duplicator for list items; by default items are not -// copied when the list is duplicated. -CZMQ_EXPORT void - zlistx_set_duplicator (zlistx_t *self, zlistx_duplicator_fn duplicator); - -// Set a user-defined comparator for zlistx_find and zlistx_sort; the method -// must return -1, 0, or 1 depending on whether item1 is less than, equal to, -// or greater than, item2. -CZMQ_EXPORT void - zlistx_set_comparator (zlistx_t *self, zlistx_comparator_fn comparator); - -// Self test of this class. -CZMQ_EXPORT void - zlistx_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zloop.h b/phonelibs/zmq/arm/include/zloop.h deleted file mode 100644 index bc58ea0530..0000000000 --- a/phonelibs/zmq/arm/include/zloop.h +++ /dev/null @@ -1,168 +0,0 @@ -/* ========================================================================= - zloop - event-driven reactor - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZLOOP_H_INCLUDED__ -#define __ZLOOP_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zloop.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// Callback function for reactor socket activity -typedef int (zloop_reader_fn) ( - zloop_t *loop, zsock_t *reader, void *arg); - -// Callback function for reactor events (low-level) -typedef int (zloop_fn) ( - zloop_t *loop, zmq_pollitem_t *item, void *arg); - -// Callback for reactor timer events -typedef int (zloop_timer_fn) ( - zloop_t *loop, int timer_id, void *arg); - -// Create a new zloop reactor -CZMQ_EXPORT zloop_t * - zloop_new (void); - -// Destroy a reactor -CZMQ_EXPORT void - zloop_destroy (zloop_t **self_p); - -// Register socket reader with the reactor. When the reader has messages, -// the reactor will call the handler, passing the arg. Returns 0 if OK, -1 -// if there was an error. If you register the same socket more than once, -// each instance will invoke its corresponding handler. -CZMQ_EXPORT int - zloop_reader (zloop_t *self, zsock_t *sock, zloop_reader_fn handler, void *arg); - -// Cancel a socket reader from the reactor. If multiple readers exist for -// same socket, cancels ALL of them. -CZMQ_EXPORT void - zloop_reader_end (zloop_t *self, zsock_t *sock); - -// Configure a registered reader to ignore errors. If you do not set this, -// then readers that have errors are removed from the reactor silently. -CZMQ_EXPORT void - zloop_reader_set_tolerant (zloop_t *self, zsock_t *sock); - -// Register low-level libzmq pollitem with the reactor. When the pollitem -// is ready, will call the handler, passing the arg. Returns 0 if OK, -1 -// if there was an error. If you register the pollitem more than once, each -// instance will invoke its corresponding handler. A pollitem with -// socket=NULL and fd=0 means 'poll on FD zero'. -CZMQ_EXPORT int - zloop_poller (zloop_t *self, zmq_pollitem_t *item, zloop_fn handler, void *arg); - -// Cancel a pollitem from the reactor, specified by socket or FD. If both -// are specified, uses only socket. If multiple poll items exist for same -// socket/FD, cancels ALL of them. -CZMQ_EXPORT void - zloop_poller_end (zloop_t *self, zmq_pollitem_t *item); - -// Configure a registered poller to ignore errors. If you do not set this, -// then poller that have errors are removed from the reactor silently. -CZMQ_EXPORT void - zloop_poller_set_tolerant (zloop_t *self, zmq_pollitem_t *item); - -// Register a timer that expires after some delay and repeats some number of -// times. At each expiry, will call the handler, passing the arg. To run a -// timer forever, use 0 times. Returns a timer_id that is used to cancel the -// timer in the future. Returns -1 if there was an error. -CZMQ_EXPORT int - zloop_timer (zloop_t *self, size_t delay, size_t times, zloop_timer_fn handler, void *arg); - -// Cancel a specific timer identified by a specific timer_id (as returned by -// zloop_timer). -CZMQ_EXPORT int - zloop_timer_end (zloop_t *self, int timer_id); - -// Register a ticket timer. Ticket timers are very fast in the case where -// you use a lot of timers (thousands), and frequently remove and add them. -// The main use case is expiry timers for servers that handle many clients, -// and which reset the expiry timer for each message received from a client. -// Whereas normal timers perform poorly as the number of clients grows, the -// cost of ticket timers is constant, no matter the number of clients. You -// must set the ticket delay using zloop_set_ticket_delay before creating a -// ticket. Returns a handle to the timer that you should use in -// zloop_ticket_reset and zloop_ticket_delete. -CZMQ_EXPORT void * - zloop_ticket (zloop_t *self, zloop_timer_fn handler, void *arg); - -// Reset a ticket timer, which moves it to the end of the ticket list and -// resets its execution time. This is a very fast operation. -CZMQ_EXPORT void - zloop_ticket_reset (zloop_t *self, void *handle); - -// Delete a ticket timer. We do not actually delete the ticket here, as -// other code may still refer to the ticket. We mark as deleted, and remove -// later and safely. -CZMQ_EXPORT void - zloop_ticket_delete (zloop_t *self, void *handle); - -// Set the ticket delay, which applies to all tickets. If you lower the -// delay and there are already tickets created, the results are undefined. -CZMQ_EXPORT void - zloop_set_ticket_delay (zloop_t *self, size_t ticket_delay); - -// Set hard limit on number of timers allowed. Setting more than a small -// number of timers (10-100) can have a dramatic impact on the performance -// of the reactor. For high-volume cases, use ticket timers. If the hard -// limit is reached, the reactor stops creating new timers and logs an -// error. -CZMQ_EXPORT void - zloop_set_max_timers (zloop_t *self, size_t max_timers); - -// Set verbose tracing of reactor on/off. The default verbose setting is -// off (false). -CZMQ_EXPORT void - zloop_set_verbose (zloop_t *self, bool verbose); - -// Start the reactor. Takes control of the thread and returns when the 0MQ -// context is terminated or the process is interrupted, or any event handler -// returns -1. Event handlers may register new sockets and timers, and -// cancel sockets. Returns 0 if interrupted, -1 if canceled by a handler. -CZMQ_EXPORT int - zloop_start (zloop_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zloop_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// By default the reactor stops if the process receives a SIGINT or SIGTERM -// signal. This makes it impossible to shut-down message based architectures -// like zactors. This method lets you switch off break handling. The default -// nonstop setting is off (false). -CZMQ_EXPORT void - zloop_set_nonstop (zloop_t *self, bool nonstop); - -#endif // CZMQ_BUILD_DRAFT_API -// @end - - -// Deprecated method aliases -#define zloop_set_tolerant(s,i) zloop_poller_set_tolerant(s,i) - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zmonitor.h b/phonelibs/zmq/arm/include/zmonitor.h deleted file mode 100644 index b490bcb1a0..0000000000 --- a/phonelibs/zmq/arm/include/zmonitor.h +++ /dev/null @@ -1,73 +0,0 @@ -/* ========================================================================= - zmonitor - socket event monitor - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZMONITOR_H_INCLUDED__ -#define __ZMONITOR_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// Create new zmonitor actor instance to monitor a zsock_t socket: -// -// zactor_t *monitor = zactor_new (zmonitor, mysocket); -// -// Destroy zmonitor instance. -// -// zactor_destroy (&monitor); -// -// Enable verbose logging of commands and activity. -// -// zstr_send (monitor, "VERBOSE"); -// -// Listen to monitor event type (zero or types, ending in NULL): -// zstr_sendx (monitor, "LISTEN", type, ..., NULL); -// -// Events: -// CONNECTED -// CONNECT_DELAYED -// CONNECT_RETRIED -// LISTENING -// BIND_FAILED -// ACCEPTED -// ACCEPT_FAILED -// CLOSED -// CLOSE_FAILED -// DISCONNECTED -// MONITOR_STOPPED -// ALL -// -// Start monitor; after this, any further LISTEN commands are ignored. -// -// zstr_send (monitor, "START"); -// zsock_wait (monitor); -// -// Receive next monitor event: -// -// zmsg_t *msg = zmsg_recv (monitor); -// -// This is the zmonitor constructor as a zactor_fn; the argument can be -// a zactor_t, zsock_t, or libzmq void * socket: -CZMQ_EXPORT void - zmonitor (zsock_t *pipe, void *sock); - -// Selftest -CZMQ_EXPORT void - zmonitor_test (bool verbose); -// @end -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zmonitor_v2.h b/phonelibs/zmq/arm/include/zmonitor_v2.h deleted file mode 100644 index 5780e0bcb7..0000000000 --- a/phonelibs/zmq/arm/include/zmonitor_v2.h +++ /dev/null @@ -1,56 +0,0 @@ -/* ========================================================================= - zmonitor_v2 - socket event monitor (deprecated) - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZMONITOR_V2_H_INCLUDED__ -#define __ZMONITOR_V2_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// This code needs backporting to work with ZMQ v3.2 -#if (ZMQ_VERSION_MAJOR == 4) - -// Create a new socket monitor -CZMQ_EXPORT zmonitor_t * - zmonitor_new (zctx_t *ctx, void *socket, int events); - -// Destroy a socket monitor -CZMQ_EXPORT void - zmonitor_destroy (zmonitor_t **self_p); - -// Receive a status message from the monitor; if no message arrives within -// 500 msec, or the call was interrupted, returns NULL. -CZMQ_EXPORT zmsg_t * - zmonitor_recv (zmonitor_t *self); - -// Get the ZeroMQ socket, for polling -CZMQ_EXPORT void * - zmonitor_socket (zmonitor_t *self); - -// Enable verbose tracing of commands and activity -CZMQ_EXPORT void - zmonitor_set_verbose (zmonitor_t *self, bool verbose); -#endif // ZeroMQ 4.0 or later - -// Self test of this class -CZMQ_EXPORT void - zmonitor_v2_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zmq.h b/phonelibs/zmq/arm/include/zmq.h deleted file mode 100644 index 5f35d1915f..0000000000 --- a/phonelibs/zmq/arm/include/zmq.h +++ /dev/null @@ -1,617 +0,0 @@ -/* - Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file - - This file is part of libzmq, the ZeroMQ core engine in C++. - - libzmq is free software; you can redistribute it and/or modify it under - the terms of the GNU Lesser General Public License (LGPL) as published - by the Free Software Foundation; either version 3 of the License, or - (at your option) any later version. - - As a special exception, the Contributors give you permission to link - this library with independent modules to produce an executable, - regardless of the license terms of these independent modules, and to - copy and distribute the resulting executable under terms of your choice, - provided that you also meet, for each linked independent module, the - terms and conditions of the license of that module. An independent - module is a module which is not derived from or based on this library. - If you modify this library, you must extend this exception to your - version of the library. - - libzmq is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public - License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . - - ************************************************************************* - NOTE to contributors. This file comprises the principal public contract - for ZeroMQ API users. Any change to this file supplied in a stable - release SHOULD not break existing applications. - In practice this means that the value of constants must not change, and - that old values may not be reused for new constants. - ************************************************************************* -*/ - -#ifndef __ZMQ_H_INCLUDED__ -#define __ZMQ_H_INCLUDED__ - -/* Version macros for compile-time API version detection */ -#define ZMQ_VERSION_MAJOR 4 -#define ZMQ_VERSION_MINOR 2 -#define ZMQ_VERSION_PATCH 0 - -#define ZMQ_MAKE_VERSION(major, minor, patch) \ - ((major) * 10000 + (minor) * 100 + (patch)) -#define ZMQ_VERSION \ - ZMQ_MAKE_VERSION(ZMQ_VERSION_MAJOR, ZMQ_VERSION_MINOR, ZMQ_VERSION_PATCH) - -#ifdef __cplusplus -extern "C" { -#endif - -#if !defined _WIN32_WCE -#include -#endif -#include -#include -#if defined _WIN32 -// Set target version to Windows Server 2008, Windows Vista or higher. -// Windows XP (0x0501) is supported but without client & server socket types. -#ifndef _WIN32_WINNT -#define _WIN32_WINNT 0x0600 -#endif - -#ifdef __MINGW32__ -// Require Windows XP or higher with MinGW for getaddrinfo(). -#if(_WIN32_WINNT >= 0x0600) -#else -#undef _WIN32_WINNT -#define _WIN32_WINNT 0x0600 -#endif -#endif -#include -#endif - -/* Handle DSO symbol visibility */ -#if defined _WIN32 -# if defined ZMQ_STATIC -# define ZMQ_EXPORT -# elif defined DLL_EXPORT -# define ZMQ_EXPORT __declspec(dllexport) -# else -# define ZMQ_EXPORT __declspec(dllimport) -# endif -#else -# if defined __SUNPRO_C || defined __SUNPRO_CC -# define ZMQ_EXPORT __global -# elif (defined __GNUC__ && __GNUC__ >= 4) || defined __INTEL_COMPILER -# define ZMQ_EXPORT __attribute__ ((visibility("default"))) -# else -# define ZMQ_EXPORT -# endif -#endif - -/* Define integer types needed for event interface */ -#define ZMQ_DEFINED_STDINT 1 -#if defined ZMQ_HAVE_SOLARIS || defined ZMQ_HAVE_OPENVMS -# include -#elif defined _MSC_VER && _MSC_VER < 1600 -# ifndef int32_t - typedef __int32 int32_t; -# endif -# ifndef uint16_t - typedef unsigned __int16 uint16_t; -# endif -# ifndef uint8_t - typedef unsigned __int8 uint8_t; -# endif -#else -# include -#endif - - -/******************************************************************************/ -/* 0MQ errors. */ -/******************************************************************************/ - -/* A number random enough not to collide with different errno ranges on */ -/* different OSes. The assumption is that error_t is at least 32-bit type. */ -#define ZMQ_HAUSNUMERO 156384712 - -/* On Windows platform some of the standard POSIX errnos are not defined. */ -#ifndef ENOTSUP -#define ENOTSUP (ZMQ_HAUSNUMERO + 1) -#endif -#ifndef EPROTONOSUPPORT -#define EPROTONOSUPPORT (ZMQ_HAUSNUMERO + 2) -#endif -#ifndef ENOBUFS -#define ENOBUFS (ZMQ_HAUSNUMERO + 3) -#endif -#ifndef ENETDOWN -#define ENETDOWN (ZMQ_HAUSNUMERO + 4) -#endif -#ifndef EADDRINUSE -#define EADDRINUSE (ZMQ_HAUSNUMERO + 5) -#endif -#ifndef EADDRNOTAVAIL -#define EADDRNOTAVAIL (ZMQ_HAUSNUMERO + 6) -#endif -#ifndef ECONNREFUSED -#define ECONNREFUSED (ZMQ_HAUSNUMERO + 7) -#endif -#ifndef EINPROGRESS -#define EINPROGRESS (ZMQ_HAUSNUMERO + 8) -#endif -#ifndef ENOTSOCK -#define ENOTSOCK (ZMQ_HAUSNUMERO + 9) -#endif -#ifndef EMSGSIZE -#define EMSGSIZE (ZMQ_HAUSNUMERO + 10) -#endif -#ifndef EAFNOSUPPORT -#define EAFNOSUPPORT (ZMQ_HAUSNUMERO + 11) -#endif -#ifndef ENETUNREACH -#define ENETUNREACH (ZMQ_HAUSNUMERO + 12) -#endif -#ifndef ECONNABORTED -#define ECONNABORTED (ZMQ_HAUSNUMERO + 13) -#endif -#ifndef ECONNRESET -#define ECONNRESET (ZMQ_HAUSNUMERO + 14) -#endif -#ifndef ENOTCONN -#define ENOTCONN (ZMQ_HAUSNUMERO + 15) -#endif -#ifndef ETIMEDOUT -#define ETIMEDOUT (ZMQ_HAUSNUMERO + 16) -#endif -#ifndef EHOSTUNREACH -#define EHOSTUNREACH (ZMQ_HAUSNUMERO + 17) -#endif -#ifndef ENETRESET -#define ENETRESET (ZMQ_HAUSNUMERO + 18) -#endif - -/* Native 0MQ error codes. */ -#define EFSM (ZMQ_HAUSNUMERO + 51) -#define ENOCOMPATPROTO (ZMQ_HAUSNUMERO + 52) -#define ETERM (ZMQ_HAUSNUMERO + 53) -#define EMTHREAD (ZMQ_HAUSNUMERO + 54) - -/* This function retrieves the errno as it is known to 0MQ library. The goal */ -/* of this function is to make the code 100% portable, including where 0MQ */ -/* compiled with certain CRT library (on Windows) is linked to an */ -/* application that uses different CRT library. */ -ZMQ_EXPORT int zmq_errno (void); - -/* Resolves system errors and 0MQ errors to human-readable string. */ -ZMQ_EXPORT const char *zmq_strerror (int errnum); - -/* Run-time API version detection */ -ZMQ_EXPORT void zmq_version (int *major, int *minor, int *patch); - -/******************************************************************************/ -/* 0MQ infrastructure (a.k.a. context) initialisation & termination. */ -/******************************************************************************/ - -/* Context options */ -#define ZMQ_IO_THREADS 1 -#define ZMQ_MAX_SOCKETS 2 -#define ZMQ_SOCKET_LIMIT 3 -#define ZMQ_THREAD_PRIORITY 3 -#define ZMQ_THREAD_SCHED_POLICY 4 -#define ZMQ_MAX_MSGSZ 5 - -/* Default for new contexts */ -#define ZMQ_IO_THREADS_DFLT 1 -#define ZMQ_MAX_SOCKETS_DFLT 1023 -#define ZMQ_THREAD_PRIORITY_DFLT -1 -#define ZMQ_THREAD_SCHED_POLICY_DFLT -1 - -ZMQ_EXPORT void *zmq_ctx_new (void); -ZMQ_EXPORT int zmq_ctx_term (void *context); -ZMQ_EXPORT int zmq_ctx_shutdown (void *context); -ZMQ_EXPORT int zmq_ctx_set (void *context, int option, int optval); -ZMQ_EXPORT int zmq_ctx_get (void *context, int option); - -/* Old (legacy) API */ -ZMQ_EXPORT void *zmq_init (int io_threads); -ZMQ_EXPORT int zmq_term (void *context); -ZMQ_EXPORT int zmq_ctx_destroy (void *context); - - -/******************************************************************************/ -/* 0MQ message definition. */ -/******************************************************************************/ - -/* union here ensures correct alignment on architectures that require it, e.g. - * SPARC - */ -typedef union zmq_msg_t {unsigned char _ [64]; void *p; } zmq_msg_t; - -typedef void (zmq_free_fn) (void *data, void *hint); - -ZMQ_EXPORT int zmq_msg_init (zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_init_size (zmq_msg_t *msg, size_t size); -ZMQ_EXPORT int zmq_msg_init_data (zmq_msg_t *msg, void *data, - size_t size, zmq_free_fn *ffn, void *hint); -ZMQ_EXPORT int zmq_msg_send (zmq_msg_t *msg, void *s, int flags); -ZMQ_EXPORT int zmq_msg_recv (zmq_msg_t *msg, void *s, int flags); -ZMQ_EXPORT int zmq_msg_close (zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_move (zmq_msg_t *dest, zmq_msg_t *src); -ZMQ_EXPORT int zmq_msg_copy (zmq_msg_t *dest, zmq_msg_t *src); -ZMQ_EXPORT void *zmq_msg_data (zmq_msg_t *msg); -ZMQ_EXPORT size_t zmq_msg_size (zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_more (zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_get (zmq_msg_t *msg, int property); -ZMQ_EXPORT int zmq_msg_set (zmq_msg_t *msg, int property, int optval); -ZMQ_EXPORT const char *zmq_msg_gets (zmq_msg_t *msg, const char *property); - -/******************************************************************************/ -/* 0MQ socket definition. */ -/******************************************************************************/ - -/* Socket types. */ -#define ZMQ_PAIR 0 -#define ZMQ_PUB 1 -#define ZMQ_SUB 2 -#define ZMQ_REQ 3 -#define ZMQ_REP 4 -#define ZMQ_DEALER 5 -#define ZMQ_ROUTER 6 -#define ZMQ_PULL 7 -#define ZMQ_PUSH 8 -#define ZMQ_XPUB 9 -#define ZMQ_XSUB 10 -#define ZMQ_STREAM 11 - -/* Deprecated aliases */ -#define ZMQ_XREQ ZMQ_DEALER -#define ZMQ_XREP ZMQ_ROUTER - -/* Socket options. */ -#define ZMQ_AFFINITY 4 -#define ZMQ_IDENTITY 5 -#define ZMQ_SUBSCRIBE 6 -#define ZMQ_UNSUBSCRIBE 7 -#define ZMQ_RATE 8 -#define ZMQ_RECOVERY_IVL 9 -#define ZMQ_SNDBUF 11 -#define ZMQ_RCVBUF 12 -#define ZMQ_RCVMORE 13 -#define ZMQ_FD 14 -#define ZMQ_EVENTS 15 -#define ZMQ_TYPE 16 -#define ZMQ_LINGER 17 -#define ZMQ_RECONNECT_IVL 18 -#define ZMQ_BACKLOG 19 -#define ZMQ_RECONNECT_IVL_MAX 21 -#define ZMQ_MAXMSGSIZE 22 -#define ZMQ_SNDHWM 23 -#define ZMQ_RCVHWM 24 -#define ZMQ_MULTICAST_HOPS 25 -#define ZMQ_RCVTIMEO 27 -#define ZMQ_SNDTIMEO 28 -#define ZMQ_LAST_ENDPOINT 32 -#define ZMQ_ROUTER_MANDATORY 33 -#define ZMQ_TCP_KEEPALIVE 34 -#define ZMQ_TCP_KEEPALIVE_CNT 35 -#define ZMQ_TCP_KEEPALIVE_IDLE 36 -#define ZMQ_TCP_KEEPALIVE_INTVL 37 -#define ZMQ_IMMEDIATE 39 -#define ZMQ_XPUB_VERBOSE 40 -#define ZMQ_ROUTER_RAW 41 -#define ZMQ_IPV6 42 -#define ZMQ_MECHANISM 43 -#define ZMQ_PLAIN_SERVER 44 -#define ZMQ_PLAIN_USERNAME 45 -#define ZMQ_PLAIN_PASSWORD 46 -#define ZMQ_CURVE_SERVER 47 -#define ZMQ_CURVE_PUBLICKEY 48 -#define ZMQ_CURVE_SECRETKEY 49 -#define ZMQ_CURVE_SERVERKEY 50 -#define ZMQ_PROBE_ROUTER 51 -#define ZMQ_REQ_CORRELATE 52 -#define ZMQ_REQ_RELAXED 53 -#define ZMQ_CONFLATE 54 -#define ZMQ_ZAP_DOMAIN 55 -#define ZMQ_ROUTER_HANDOVER 56 -#define ZMQ_TOS 57 -#define ZMQ_CONNECT_RID 61 -#define ZMQ_GSSAPI_SERVER 62 -#define ZMQ_GSSAPI_PRINCIPAL 63 -#define ZMQ_GSSAPI_SERVICE_PRINCIPAL 64 -#define ZMQ_GSSAPI_PLAINTEXT 65 -#define ZMQ_HANDSHAKE_IVL 66 -#define ZMQ_SOCKS_PROXY 68 -#define ZMQ_XPUB_NODROP 69 -// All options after this is for version 4.2 and still *draft* -// Subject to arbitrary change without notice -#define ZMQ_BLOCKY 70 -#define ZMQ_XPUB_MANUAL 71 -#define ZMQ_XPUB_WELCOME_MSG 72 -#define ZMQ_STREAM_NOTIFY 73 -#define ZMQ_INVERT_MATCHING 74 -#define ZMQ_HEARTBEAT_IVL 75 -#define ZMQ_HEARTBEAT_TTL 76 -#define ZMQ_HEARTBEAT_TIMEOUT 77 -#define ZMQ_XPUB_VERBOSER 78 -#define ZMQ_CONNECT_TIMEOUT 79 -#define ZMQ_TCP_MAXRT 80 -#define ZMQ_THREAD_SAFE 81 -#define ZMQ_MULTICAST_MAXTPDU 84 -#define ZMQ_VMCI_BUFFER_SIZE 85 -#define ZMQ_VMCI_BUFFER_MIN_SIZE 86 -#define ZMQ_VMCI_BUFFER_MAX_SIZE 87 -#define ZMQ_VMCI_CONNECT_TIMEOUT 88 -#define ZMQ_USE_FD 89 - -/* Message options */ -#define ZMQ_MORE 1 -#define ZMQ_SHARED 3 - -/* Send/recv options. */ -#define ZMQ_DONTWAIT 1 -#define ZMQ_SNDMORE 2 - -/* Security mechanisms */ -#define ZMQ_NULL 0 -#define ZMQ_PLAIN 1 -#define ZMQ_CURVE 2 -#define ZMQ_GSSAPI 3 - -/* RADIO-DISH protocol */ -#define ZMQ_GROUP_MAX_LENGTH 15 - -/* Deprecated options and aliases */ -#define ZMQ_TCP_ACCEPT_FILTER 38 -#define ZMQ_IPC_FILTER_PID 58 -#define ZMQ_IPC_FILTER_UID 59 -#define ZMQ_IPC_FILTER_GID 60 -#define ZMQ_IPV4ONLY 31 -#define ZMQ_DELAY_ATTACH_ON_CONNECT ZMQ_IMMEDIATE -#define ZMQ_NOBLOCK ZMQ_DONTWAIT -#define ZMQ_FAIL_UNROUTABLE ZMQ_ROUTER_MANDATORY -#define ZMQ_ROUTER_BEHAVIOR ZMQ_ROUTER_MANDATORY - -/* Deprecated Message options */ -#define ZMQ_SRCFD 2 - -/******************************************************************************/ -/* 0MQ socket events and monitoring */ -/******************************************************************************/ - -/* Socket transport events (TCP, IPC and TIPC only) */ - -#define ZMQ_EVENT_CONNECTED 0x0001 -#define ZMQ_EVENT_CONNECT_DELAYED 0x0002 -#define ZMQ_EVENT_CONNECT_RETRIED 0x0004 -#define ZMQ_EVENT_LISTENING 0x0008 -#define ZMQ_EVENT_BIND_FAILED 0x0010 -#define ZMQ_EVENT_ACCEPTED 0x0020 -#define ZMQ_EVENT_ACCEPT_FAILED 0x0040 -#define ZMQ_EVENT_CLOSED 0x0080 -#define ZMQ_EVENT_CLOSE_FAILED 0x0100 -#define ZMQ_EVENT_DISCONNECTED 0x0200 -#define ZMQ_EVENT_MONITOR_STOPPED 0x0400 -#define ZMQ_EVENT_ALL 0xFFFF - -ZMQ_EXPORT void *zmq_socket (void *, int type); -ZMQ_EXPORT int zmq_close (void *s); -ZMQ_EXPORT int zmq_setsockopt (void *s, int option, const void *optval, - size_t optvallen); -ZMQ_EXPORT int zmq_getsockopt (void *s, int option, void *optval, - size_t *optvallen); -ZMQ_EXPORT int zmq_bind (void *s, const char *addr); -ZMQ_EXPORT int zmq_connect (void *s, const char *addr); -ZMQ_EXPORT int zmq_unbind (void *s, const char *addr); -ZMQ_EXPORT int zmq_disconnect (void *s, const char *addr); -ZMQ_EXPORT int zmq_send (void *s, const void *buf, size_t len, int flags); -ZMQ_EXPORT int zmq_send_const (void *s, const void *buf, size_t len, int flags); -ZMQ_EXPORT int zmq_recv (void *s, void *buf, size_t len, int flags); -ZMQ_EXPORT int zmq_socket_monitor (void *s, const char *addr, int events); - - -/******************************************************************************/ -/* I/O multiplexing. */ -/******************************************************************************/ - -#define ZMQ_POLLIN 1 -#define ZMQ_POLLOUT 2 -#define ZMQ_POLLERR 4 -#define ZMQ_POLLPRI 8 - -typedef struct zmq_pollitem_t -{ - void *socket; -#if defined _WIN32 - SOCKET fd; -#else - int fd; -#endif - short events; - short revents; -} zmq_pollitem_t; - -#define ZMQ_POLLITEMS_DFLT 16 - -ZMQ_EXPORT int zmq_poll (zmq_pollitem_t *items, int nitems, long timeout); - -/******************************************************************************/ -/* Message proxying */ -/******************************************************************************/ - -ZMQ_EXPORT int zmq_proxy (void *frontend, void *backend, void *capture); -ZMQ_EXPORT int zmq_proxy_steerable (void *frontend, void *backend, void *capture, void *control); - -/******************************************************************************/ -/* Probe library capabilities */ -/******************************************************************************/ - -#define ZMQ_HAS_CAPABILITIES 1 -ZMQ_EXPORT int zmq_has (const char *capability); - -/* Deprecated aliases */ -#define ZMQ_STREAMER 1 -#define ZMQ_FORWARDER 2 -#define ZMQ_QUEUE 3 - -/* Deprecated methods */ -ZMQ_EXPORT int zmq_device (int type, void *frontend, void *backend); -ZMQ_EXPORT int zmq_sendmsg (void *s, zmq_msg_t *msg, int flags); -ZMQ_EXPORT int zmq_recvmsg (void *s, zmq_msg_t *msg, int flags); -struct iovec; -ZMQ_EXPORT int zmq_sendiov (void *s, struct iovec *iov, size_t count, int flags); -ZMQ_EXPORT int zmq_recviov (void *s, struct iovec *iov, size_t *count, int flags); - -/******************************************************************************/ -/* Encryption functions */ -/******************************************************************************/ - -/* Encode data with Z85 encoding. Returns encoded data */ -ZMQ_EXPORT char *zmq_z85_encode (char *dest, const uint8_t *data, size_t size); - -/* Decode data with Z85 encoding. Returns decoded data */ -ZMQ_EXPORT uint8_t *zmq_z85_decode (uint8_t *dest, const char *string); - -/* Generate z85-encoded public and private keypair with tweetnacl/libsodium. */ -/* Returns 0 on success. */ -ZMQ_EXPORT int zmq_curve_keypair (char *z85_public_key, char *z85_secret_key); - -/* Derive the z85-encoded public key from the z85-encoded secret key. */ -/* Returns 0 on success. */ -ZMQ_EXPORT int zmq_curve_public (char *z85_public_key, const char *z85_secret_key); - -/******************************************************************************/ -/* Atomic utility methods */ -/******************************************************************************/ - -ZMQ_EXPORT void *zmq_atomic_counter_new (void); -ZMQ_EXPORT void zmq_atomic_counter_set (void *counter, int value); -ZMQ_EXPORT int zmq_atomic_counter_inc (void *counter); -ZMQ_EXPORT int zmq_atomic_counter_dec (void *counter); -ZMQ_EXPORT int zmq_atomic_counter_value (void *counter); -ZMQ_EXPORT void zmq_atomic_counter_destroy (void **counter_p); - - -/******************************************************************************/ -/* These functions are not documented by man pages -- use at your own risk. */ -/* If you need these to be part of the formal ZMQ API, then (a) write a man */ -/* page, and (b) write a test case in tests. */ -/******************************************************************************/ - -/* Helper functions are used by perf tests so that they don't have to care */ -/* about minutiae of time-related functions on different OS platforms. */ - -/* Starts the stopwatch. Returns the handle to the watch. */ -ZMQ_EXPORT void *zmq_stopwatch_start (void); - -/* Stops the stopwatch. Returns the number of microseconds elapsed since */ -/* the stopwatch was started. */ -ZMQ_EXPORT unsigned long zmq_stopwatch_stop (void *watch_); - -/* Sleeps for specified number of seconds. */ -ZMQ_EXPORT void zmq_sleep (int seconds_); - -typedef void (zmq_thread_fn) (void*); - -/* Start a thread. Returns a handle to the thread. */ -ZMQ_EXPORT void *zmq_threadstart (zmq_thread_fn* func, void* arg); - -/* Wait for thread to complete then free up resources. */ -ZMQ_EXPORT void zmq_threadclose (void* thread); - - -/******************************************************************************/ -/* These functions are DRAFT and disabled in stable releases, and subject to */ -/* change at ANY time until declared stable. */ -/******************************************************************************/ - -#ifdef ZMQ_BUILD_DRAFT_API - -/* DRAFT Socket types. */ -#define ZMQ_SERVER 12 -#define ZMQ_CLIENT 13 -#define ZMQ_RADIO 14 -#define ZMQ_DISH 15 -#define ZMQ_GATHER 16 -#define ZMQ_SCATTER 17 -#define ZMQ_DGRAM 18 - -/* DRAFT Socket methods. */ -ZMQ_EXPORT int zmq_join (void *s, const char *group); -ZMQ_EXPORT int zmq_leave (void *s, const char *group); - -/* DRAFT Msg methods. */ -ZMQ_EXPORT int zmq_msg_set_routing_id(zmq_msg_t *msg, uint32_t routing_id); -ZMQ_EXPORT uint32_t zmq_msg_routing_id(zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_set_group(zmq_msg_t *msg, const char *group); -ZMQ_EXPORT const char *zmq_msg_group(zmq_msg_t *msg); - -/******************************************************************************/ -/* Poller polling on sockets,fd and thread-safe sockets */ -/******************************************************************************/ - -#define ZMQ_HAVE_POLLER - -typedef struct zmq_poller_event_t -{ - void *socket; -#if defined _WIN32 - SOCKET fd; -#else - int fd; -#endif - void *user_data; - short events; -} zmq_poller_event_t; - -ZMQ_EXPORT void *zmq_poller_new (void); -ZMQ_EXPORT int zmq_poller_destroy (void **poller_p); -ZMQ_EXPORT int zmq_poller_add (void *poller, void *socket, void *user_data, short events); -ZMQ_EXPORT int zmq_poller_modify (void *poller, void *socket, short events); -ZMQ_EXPORT int zmq_poller_remove (void *poller, void *socket); -ZMQ_EXPORT int zmq_poller_wait (void *poller, zmq_poller_event_t *event, long timeout); - -#if defined _WIN32 -ZMQ_EXPORT int zmq_poller_add_fd (void *poller, SOCKET fd, void *user_data, short events); -ZMQ_EXPORT int zmq_poller_modify_fd (void *poller, SOCKET fd, short events); -ZMQ_EXPORT int zmq_poller_remove_fd (void *poller, SOCKET fd); -#else -ZMQ_EXPORT int zmq_poller_add_fd (void *poller, int fd, void *user_data, short events); -ZMQ_EXPORT int zmq_poller_modify_fd (void *poller, int fd, short events); -ZMQ_EXPORT int zmq_poller_remove_fd (void *poller, int fd); -#endif - -/******************************************************************************/ -/* Scheduling timers */ -/******************************************************************************/ - -#define ZMQ_HAVE_TIMERS - -typedef void (zmq_timer_fn)(int timer_id, void *arg); - -ZMQ_EXPORT void *zmq_timers_new (void); -ZMQ_EXPORT int zmq_timers_destroy (void **timers_p); -ZMQ_EXPORT int zmq_timers_add (void *timers, size_t interval, zmq_timer_fn handler, void *arg); -ZMQ_EXPORT int zmq_timers_cancel (void *timers, int timer_id); -ZMQ_EXPORT int zmq_timers_set_interval (void *timers, int timer_id, size_t interval); -ZMQ_EXPORT int zmq_timers_reset (void *timers, int timer_id); -ZMQ_EXPORT long zmq_timers_timeout (void *timers); -ZMQ_EXPORT int zmq_timers_execute (void *timers); - -#endif // ZMQ_BUILD_DRAFT_API - - -#undef ZMQ_EXPORT - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zmq_utils.h b/phonelibs/zmq/arm/include/zmq_utils.h deleted file mode 100644 index f29638d553..0000000000 --- a/phonelibs/zmq/arm/include/zmq_utils.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file - - This file is part of libzmq, the ZeroMQ core engine in C++. - - libzmq is free software; you can redistribute it and/or modify it under - the terms of the GNU Lesser General Public License (LGPL) as published - by the Free Software Foundation; either version 3 of the License, or - (at your option) any later version. - - As a special exception, the Contributors give you permission to link - this library with independent modules to produce an executable, - regardless of the license terms of these independent modules, and to - copy and distribute the resulting executable under terms of your choice, - provided that you also meet, for each linked independent module, the - terms and conditions of the license of that module. An independent - module is a module which is not derived from or based on this library. - If you modify this library, you must extend this exception to your - version of the library. - - libzmq is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public - License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . -*/ - -/* This file is deprecated, and all its functionality provided by zmq.h */ -/* Note that -Wpedantic compilation requires GCC to avoid using its custom - extensions such as #warning, hence the trick below. Also, pragmas for - warnings or other messages are not standard, not portable, and not all - compilers even have an equivalent concept. - So in the worst case, this include file is treated as silently empty. */ - -#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) || defined(_MSC_VER) -#if defined(__GNUC__) || defined(__GNUG__) -#pragma GCC diagnostic push -#pragma GCC diagnostic warning "-Wcpp" -#pragma GCC diagnostic ignored "-Werror" -#pragma GCC diagnostic ignored "-Wall" -#endif -#pragma message("Warning: zmq_utils.h is deprecated. All its functionality is provided by zmq.h.") -#if defined(__GNUC__) || defined(__GNUG__) -#pragma GCC diagnostic pop -#endif -#endif diff --git a/phonelibs/zmq/arm/include/zmsg.h b/phonelibs/zmq/arm/include/zmsg.h deleted file mode 100644 index c6ab16c66e..0000000000 --- a/phonelibs/zmq/arm/include/zmsg.h +++ /dev/null @@ -1,285 +0,0 @@ -/* ========================================================================= - zmsg - working with multipart messages - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZMSG_H_INCLUDED__ -#define __ZMSG_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zmsg.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// Create a new empty message object -CZMQ_EXPORT zmsg_t * - zmsg_new (void); - -// Receive message from socket, returns zmsg_t object or NULL if the recv -// was interrupted. Does a blocking recv. If you want to not block then use -// the zloop class or zmsg_recv_nowait or zmq_poll to check for socket input -// before receiving. -CZMQ_EXPORT zmsg_t * - zmsg_recv (void *source); - -// Load/append an open file into new message, return the message. -// Returns NULL if the message could not be loaded. -CZMQ_EXPORT zmsg_t * - zmsg_load (FILE *file); - -// Decodes a serialized message frame created by zmsg_encode () and returns -// a new zmsg_t object. Returns NULL if the frame was badly formatted or -// there was insufficient memory to work. -CZMQ_EXPORT zmsg_t * - zmsg_decode (zframe_t *frame); - -// Generate a signal message encoding the given status. A signal is a short -// message carrying a 1-byte success/failure code (by convention, 0 means -// OK). Signals are encoded to be distinguishable from "normal" messages. -CZMQ_EXPORT zmsg_t * - zmsg_new_signal (byte status); - -// Destroy a message object and all frames it contains -CZMQ_EXPORT void - zmsg_destroy (zmsg_t **self_p); - -// Send message to destination socket, and destroy the message after sending -// it successfully. If the message has no frames, sends nothing but destroys -// the message anyhow. Nullifies the caller's reference to the message (as -// it is a destructor). -CZMQ_EXPORT int - zmsg_send (zmsg_t **self_p, void *dest); - -// Send message to destination socket as part of a multipart sequence, and -// destroy the message after sending it successfully. Note that after a -// zmsg_sendm, you must call zmsg_send or another method that sends a final -// message part. If the message has no frames, sends nothing but destroys -// the message anyhow. Nullifies the caller's reference to the message (as -// it is a destructor). -CZMQ_EXPORT int - zmsg_sendm (zmsg_t **self_p, void *dest); - -// Return size of message, i.e. number of frames (0 or more). -CZMQ_EXPORT size_t - zmsg_size (zmsg_t *self); - -// Return total size of all frames in message. -CZMQ_EXPORT size_t - zmsg_content_size (zmsg_t *self); - -// Push frame to the front of the message, i.e. before all other frames. -// Message takes ownership of frame, will destroy it when message is sent. -// Returns 0 on success, -1 on error. Deprecates zmsg_push, which did not -// nullify the caller's frame reference. -CZMQ_EXPORT int - zmsg_prepend (zmsg_t *self, zframe_t **frame_p); - -// Add frame to the end of the message, i.e. after all other frames. -// Message takes ownership of frame, will destroy it when message is sent. -// Returns 0 on success. Deprecates zmsg_add, which did not nullify the -// caller's frame reference. -CZMQ_EXPORT int - zmsg_append (zmsg_t *self, zframe_t **frame_p); - -// Remove first frame from message, if any. Returns frame, or NULL. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zmsg_pop (zmsg_t *self); - -// Push block of memory to front of message, as a new frame. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_pushmem (zmsg_t *self, const void *data, size_t size); - -// Add block of memory to the end of the message, as a new frame. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_addmem (zmsg_t *self, const void *data, size_t size); - -// Push string as new frame to front of message. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_pushstr (zmsg_t *self, const char *string); - -// Push string as new frame to end of message. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_addstr (zmsg_t *self, const char *string); - -// Push formatted string as new frame to front of message. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_pushstrf (zmsg_t *self, const char *format, ...); - -// Push formatted string as new frame to end of message. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_addstrf (zmsg_t *self, const char *format, ...); - -// Pop frame off front of message, return as fresh string. If there were -// no more frames in the message, returns NULL. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zmsg_popstr (zmsg_t *self); - -// Push encoded message as a new frame. Message takes ownership of -// submessage, so the original is destroyed in this call. Returns 0 on -// success, -1 on error. -CZMQ_EXPORT int - zmsg_addmsg (zmsg_t *self, zmsg_t **msg_p); - -// Remove first submessage from message, if any. Returns zmsg_t, or NULL if -// decoding was not successful. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zmsg_t * - zmsg_popmsg (zmsg_t *self); - -// Remove specified frame from list, if present. Does not destroy frame. -CZMQ_EXPORT void - zmsg_remove (zmsg_t *self, zframe_t *frame); - -// Set cursor to first frame in message. Returns frame, or NULL, if the -// message is empty. Use this to navigate the frames as a list. -CZMQ_EXPORT zframe_t * - zmsg_first (zmsg_t *self); - -// Return the next frame. If there are no more frames, returns NULL. To move -// to the first frame call zmsg_first(). Advances the cursor. -CZMQ_EXPORT zframe_t * - zmsg_next (zmsg_t *self); - -// Return the last frame. If there are no frames, returns NULL. -CZMQ_EXPORT zframe_t * - zmsg_last (zmsg_t *self); - -// Save message to an open file, return 0 if OK, else -1. The message is -// saved as a series of frames, each with length and data. Note that the -// file is NOT guaranteed to be portable between operating systems, not -// versions of CZMQ. The file format is at present undocumented and liable -// to arbitrary change. -CZMQ_EXPORT int - zmsg_save (zmsg_t *self, FILE *file); - -// Serialize multipart message to a single message frame. Use this method -// to send structured messages across transports that do not support -// multipart data. Allocates and returns a new frame containing the -// serialized message. To decode a serialized message frame, use -// zmsg_decode (). -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zframe_t * - zmsg_encode (zmsg_t *self); - -// Create copy of message, as new message object. Returns a fresh zmsg_t -// object. If message is null, or memory was exhausted, returns null. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT zmsg_t * - zmsg_dup (zmsg_t *self); - -// Send message to zsys log sink (may be stdout, or system facility as -// configured by zsys_set_logstream). -CZMQ_EXPORT void - zmsg_print (zmsg_t *self); - -// Return true if the two messages have the same number of frames and each -// frame in the first message is identical to the corresponding frame in the -// other message. As with zframe_eq, return false if either message is NULL. -CZMQ_EXPORT bool - zmsg_eq (zmsg_t *self, zmsg_t *other); - -// Return signal value, 0 or greater, if message is a signal, -1 if not. -CZMQ_EXPORT int - zmsg_signal (zmsg_t *self); - -// Probe the supplied object, and report if it looks like a zmsg_t. -CZMQ_EXPORT bool - zmsg_is (void *self); - -// Self test of this class. -CZMQ_EXPORT void - zmsg_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Return message routing ID, if the message came from a ZMQ_SERVER socket. -// Else returns zero. -CZMQ_EXPORT uint32_t - zmsg_routing_id (zmsg_t *self); - -// *** Draft method, for development use, may change without warning *** -// Set routing ID on message. This is used if/when the message is sent to a -// ZMQ_SERVER socket. -CZMQ_EXPORT void - zmsg_set_routing_id (zmsg_t *self, uint32_t routing_id); - -#endif // CZMQ_BUILD_DRAFT_API -// @ignore -CZMQ_EXPORT int - zmsg_pushstrf (zmsg_t *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int - zmsg_addstrf (zmsg_t *self, const char *format, ...) CHECK_PRINTF (2); -// @end - - -// DEPRECATED as over-engineered, poor style -// Pop frame off front of message, caller now owns frame -// If next frame is empty, pops and destroys that empty frame. -CZMQ_EXPORT zframe_t * - zmsg_unwrap (zmsg_t *self); - -// DEPRECATED as poor style -- callers should use zloop or zpoller -// Receive message from socket, returns zmsg_t object, or NULL either if -// there was no input waiting, or the recv was interrupted. -CZMQ_EXPORT zmsg_t * - zmsg_recv_nowait (void *source); - -// DEPRECATED as unsafe -- does not nullify frame reference. -// Push frame plus empty frame to front of message, before first frame. -// Message takes ownership of frame, will destroy it when message is sent. -CZMQ_EXPORT void - zmsg_wrap (zmsg_t *self, zframe_t *frame); - -// DEPRECATED - will be removed for next + 1 stable release -// Add frame to the front of the message, i.e. before all other frames. -// Message takes ownership of frame, will destroy it when message is sent. -// Returns 0 on success, -1 on error. -CZMQ_EXPORT int - zmsg_push (zmsg_t *self, zframe_t *frame); - -// DEPRECATED - will be removed for next stable release -CZMQ_EXPORT int - zmsg_add (zmsg_t *self, zframe_t *frame); - -// DEPRECATED as inconsistent; breaks principle that logging should all go -// to a single destination. -// Print message to open stream -// Truncates to first 10 frames, for readability. -CZMQ_EXPORT void - zmsg_fprint (zmsg_t *self, FILE *file); - -// Compiler hints -CZMQ_EXPORT int zmsg_addstrf (zmsg_t *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int zmsg_pushstrf (zmsg_t *self, const char *format, ...) CHECK_PRINTF (2); - -#ifdef __cplusplus -} -#endif - -// Deprecated method aliases -#define zmsg_dump(s) zmsg_print(s) -#define zmsg_dump_to_stream(s,F) zmsg_fprint(s,F) - -#endif diff --git a/phonelibs/zmq/arm/include/zmutex.h b/phonelibs/zmq/arm/include/zmutex.h deleted file mode 100644 index cba315999b..0000000000 --- a/phonelibs/zmq/arm/include/zmutex.h +++ /dev/null @@ -1,55 +0,0 @@ -/* ========================================================================= - zmutex - working with mutexes - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZMUTEX_H_INCLUDED__ -#define __ZMUTEX_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// This is a deprecated class, and will be removed over time. It is -// provided in stable builds to support old applications. You should -// stop using this class, and migrate any code that is still using it. - -// Create a new mutex container -CZMQ_EXPORT zmutex_t * - zmutex_new (void); - -// Destroy a mutex container -CZMQ_EXPORT void - zmutex_destroy (zmutex_t **self_p); - -// Lock mutex -CZMQ_EXPORT void - zmutex_lock (zmutex_t *self); - -// Unlock mutex -CZMQ_EXPORT void - zmutex_unlock (zmutex_t *self); - -// Try to lock mutex -CZMQ_EXPORT int - zmutex_try_lock (zmutex_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zmutex_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zpoller.h b/phonelibs/zmq/arm/include/zpoller.h deleted file mode 100644 index 3756a935a6..0000000000 --- a/phonelibs/zmq/arm/include/zpoller.h +++ /dev/null @@ -1,92 +0,0 @@ -/* ========================================================================= - zpoller - trivial socket poller class - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __zpoller_H_INCLUDED__ -#define __zpoller_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zpoller.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// Create new poller, specifying zero or more readers. The list of -// readers ends in a NULL. Each reader can be a zsock_t instance, a -// zactor_t instance, a libzmq socket (void *), or a file handle. -CZMQ_EXPORT zpoller_t * - zpoller_new (void *reader, ...); - -// Destroy a poller -CZMQ_EXPORT void - zpoller_destroy (zpoller_t **self_p); - -// Add a reader to be polled. Returns 0 if OK, -1 on failure. The reader may -// be a libzmq void * socket, a zsock_t instance, or a zactor_t instance. -CZMQ_EXPORT int - zpoller_add (zpoller_t *self, void *reader); - -// Remove a reader from the poller; returns 0 if OK, -1 on failure. The reader -// must have been passed during construction, or in an zpoller_add () call. -CZMQ_EXPORT int - zpoller_remove (zpoller_t *self, void *reader); - -// Poll the registered readers for I/O, return first reader that has input. -// The reader will be a libzmq void * socket, or a zsock_t or zactor_t -// instance as specified in zpoller_new/zpoller_add. The timeout should be -// zero or greater, or -1 to wait indefinitely. Socket priority is defined -// by their order in the poll list. If you need a balanced poll, use the low -// level zmq_poll method directly. If the poll call was interrupted (SIGINT), -// or the ZMQ context was destroyed, or the timeout expired, returns NULL. -// You can test the actual exit condition by calling zpoller_expired () and -// zpoller_terminated (). The timeout is in msec. -CZMQ_EXPORT void * - zpoller_wait (zpoller_t *self, int timeout); - -// Return true if the last zpoller_wait () call ended because the timeout -// expired, without any error. -CZMQ_EXPORT bool - zpoller_expired (zpoller_t *self); - -// Return true if the last zpoller_wait () call ended because the process -// was interrupted, or the parent context was destroyed. -CZMQ_EXPORT bool - zpoller_terminated (zpoller_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zpoller_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// By default the poller stops if the process receives a SIGINT or SIGTERM -// signal. This makes it impossible to shut-down message based architectures -// like zactors. This method lets you switch off break handling. The default -// nonstop setting is off (false). -CZMQ_EXPORT void - zpoller_set_nonstop (zpoller_t *self, bool nonstop); - -#endif // CZMQ_BUILD_DRAFT_API -// @end - - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/phonelibs/zmq/arm/include/zproc.h b/phonelibs/zmq/arm/include/zproc.h deleted file mode 100644 index a2e1b3dd99..0000000000 --- a/phonelibs/zmq/arm/include/zproc.h +++ /dev/null @@ -1,179 +0,0 @@ -/* ========================================================================= - zproc - process configuration and status - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef ZPROC_H_INCLUDED -#define ZPROC_H_INCLUDED - -#ifdef __cplusplus -extern "C" { -#endif - - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zproc.api" to make changes. -// @interface -// This is a draft class, and may change without notice. It is disabled in -// stable builds by default. If you use this in applications, please ask -// for it to be pushed to stable state. Use --enable-drafts to enable. -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Returns CZMQ version as a single 6-digit integer encoding the major -// version (x 10000), the minor version (x 100) and the patch. -CZMQ_EXPORT int - zproc_czmq_version (void); - -// *** Draft method, for development use, may change without warning *** -// Returns true if the process received a SIGINT or SIGTERM signal. -// It is good practice to use this method to exit any infinite loop -// processing messages. -CZMQ_EXPORT bool - zproc_interrupted (void); - -// *** Draft method, for development use, may change without warning *** -// Returns true if the underlying libzmq supports CURVE security. -CZMQ_EXPORT bool - zproc_has_curve (void); - -// *** Draft method, for development use, may change without warning *** -// Return current host name, for use in public tcp:// endpoints. -// If the host name is not resolvable, returns NULL. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zproc_hostname (void); - -// *** Draft method, for development use, may change without warning *** -// Move the current process into the background. The precise effect -// depends on the operating system. On POSIX boxes, moves to a specified -// working directory (if specified), closes all file handles, reopens -// stdin, stdout, and stderr to the null device, and sets the process to -// ignore SIGHUP. On Windows, does nothing. Returns 0 if OK, -1 if there -// was an error. -CZMQ_EXPORT void - zproc_daemonize (const char *workdir); - -// *** Draft method, for development use, may change without warning *** -// Drop the process ID into the lockfile, with exclusive lock, and -// switch the process to the specified group and/or user. Any of the -// arguments may be null, indicating a no-op. Returns 0 on success, -// -1 on failure. Note if you combine this with zsys_daemonize, run -// after, not before that method, or the lockfile will hold the wrong -// process ID. -CZMQ_EXPORT void - zproc_run_as (const char *lockfile, const char *group, const char *user); - -// *** Draft method, for development use, may change without warning *** -// Configure the number of I/O threads that ZeroMQ will use. A good -// rule of thumb is one thread per gigabit of traffic in or out. The -// default is 1, sufficient for most applications. If the environment -// variable ZSYS_IO_THREADS is defined, that provides the default. -// Note that this method is valid only before any socket is created. -CZMQ_EXPORT void - zproc_set_io_threads (size_t io_threads); - -// *** Draft method, for development use, may change without warning *** -// Configure the number of sockets that ZeroMQ will allow. The default -// is 1024. The actual limit depends on the system, and you can query it -// by using zsys_socket_limit (). A value of zero means "maximum". -// Note that this method is valid only before any socket is created. -CZMQ_EXPORT void - zproc_set_max_sockets (size_t max_sockets); - -// *** Draft method, for development use, may change without warning *** -// Set network interface name to use for broadcasts, particularly zbeacon. -// This lets the interface be configured for test environments where required. -// For example, on Mac OS X, zbeacon cannot bind to 255.255.255.255 which is -// the default when there is no specified interface. If the environment -// variable ZSYS_INTERFACE is set, use that as the default interface name. -// Setting the interface to "*" means "use all available interfaces". -CZMQ_EXPORT void - zproc_set_biface (const char *value); - -// *** Draft method, for development use, may change without warning *** -// Return network interface to use for broadcasts, or "" if none was set. -CZMQ_EXPORT const char * - zproc_biface (void); - -// *** Draft method, for development use, may change without warning *** -// Set log identity, which is a string that prefixes all log messages sent -// by this process. The log identity defaults to the environment variable -// ZSYS_LOGIDENT, if that is set. -CZMQ_EXPORT void - zproc_set_log_ident (const char *value); - -// *** Draft method, for development use, may change without warning *** -// Sends log output to a PUB socket bound to the specified endpoint. To -// collect such log output, create a SUB socket, subscribe to the traffic -// you care about, and connect to the endpoint. Log traffic is sent as a -// single string frame, in the same format as when sent to stdout. The -// log system supports a single sender; multiple calls to this method will -// bind the same sender to multiple endpoints. To disable the sender, call -// this method with a null argument. -CZMQ_EXPORT void - zproc_set_log_sender (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Enable or disable logging to the system facility (syslog on POSIX boxes, -// event log on Windows). By default this is disabled. -CZMQ_EXPORT void - zproc_set_log_system (bool logsystem); - -// *** Draft method, for development use, may change without warning *** -// Log error condition - highest priority -CZMQ_EXPORT void - zproc_log_error (const char *format, ...); - -// *** Draft method, for development use, may change without warning *** -// Log warning condition - high priority -CZMQ_EXPORT void - zproc_log_warning (const char *format, ...); - -// *** Draft method, for development use, may change without warning *** -// Log normal, but significant, condition - normal priority -CZMQ_EXPORT void - zproc_log_notice (const char *format, ...); - -// *** Draft method, for development use, may change without warning *** -// Log informational message - low priority -CZMQ_EXPORT void - zproc_log_info (const char *format, ...); - -// *** Draft method, for development use, may change without warning *** -// Log debug-level message - lowest priority -CZMQ_EXPORT void - zproc_log_debug (const char *format, ...); - -// *** Draft method, for development use, may change without warning *** -// Self test of this class. -CZMQ_EXPORT void - zproc_test (bool verbose); - -#endif // CZMQ_BUILD_DRAFT_API -// @ignore -CZMQ_EXPORT void - zproc_log_error (const char *format, ...) CHECK_PRINTF (1); -CZMQ_EXPORT void - zproc_log_warning (const char *format, ...) CHECK_PRINTF (1); -CZMQ_EXPORT void - zproc_log_notice (const char *format, ...) CHECK_PRINTF (1); -CZMQ_EXPORT void - zproc_log_info (const char *format, ...) CHECK_PRINTF (1); -CZMQ_EXPORT void - zproc_log_debug (const char *format, ...) CHECK_PRINTF (1); -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zproxy.h b/phonelibs/zmq/arm/include/zproxy.h deleted file mode 100644 index f672c5e724..0000000000 --- a/phonelibs/zmq/arm/include/zproxy.h +++ /dev/null @@ -1,111 +0,0 @@ -/* ========================================================================= - zproxy - run a steerable proxy in the background - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZPROXY_H_INCLUDED__ -#define __ZPROXY_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// Create new zproxy actor instance. The proxy switches messages between -// a frontend socket and a backend socket; use the FRONTEND and BACKEND -// commands to configure these: -// -// zactor_t *proxy = zactor_new (zproxy, NULL); -// -// Destroy zproxy instance. This destroys the two sockets and stops any -// message flow between them: -// -// zactor_destroy (&proxy); -// -// Note that all zproxy commands are synchronous, so your application always -// waits for a signal from the actor after each command. -// -// Enable verbose logging of commands and activity: -// -// zstr_send (proxy, "VERBOSE"); -// zsock_wait (proxy); -// -// Specify frontend socket type -- see zsock_type_str () -- and attach to -// endpoints, see zsock_attach (). Note that a proxy socket is always -// serverish: -// -// zstr_sendx (proxy, "FRONTEND", "XSUB", endpoints, NULL); -// zsock_wait (proxy); -// -// Specify backend socket type -- see zsock_type_str () -- and attach to -// endpoints, see zsock_attach (). Note that a proxy socket is always -// serverish: -// -// zstr_sendx (proxy, "BACKEND", "XPUB", endpoints, NULL); -// zsock_wait (proxy); -// -// Capture all proxied messages; these are delivered to the application -// via an inproc PULL socket that you have already bound to the specified -// endpoint: -// -// zstr_sendx (proxy, "CAPTURE", endpoint, NULL); -// zsock_wait (proxy); -// -// Pause the proxy. A paused proxy will cease processing messages, causing -// them to be queued up and potentially hit the high-water mark on the -// frontend or backend socket, causing messages to be dropped, or writing -// applications to block: -// -// zstr_sendx (proxy, "PAUSE", NULL); -// zsock_wait (proxy); -// -// Resume the proxy. Note that the proxy starts automatically as soon as it -// has a properly attached frontend and backend socket: -// -// zstr_sendx (proxy, "RESUME", NULL); -// zsock_wait (proxy); -// -// Configure an authentication domain for the "FRONTEND" or "BACKEND" proxy -// socket -- see zsock_set_zap_domain (). Call before binding socket: -// -// zstr_sendx (proxy, "DOMAIN", "FRONTEND", "global", NULL); -// zsock_wait (proxy); -// -// Configure PLAIN authentication for the "FRONTEND" or "BACKEND" proxy -// socket -- see zsock_set_plain_server (). Call before binding socket: -// -// zstr_sendx (proxy, "PLAIN", "BACKEND", NULL); -// zsock_wait (proxy); -// -// Configure CURVE authentication for the "FRONTEND" or "BACKEND" proxy -// socket -- see zsock_set_curve_server () -- specifying both the public and -// secret keys of a certificate as Z85 armored strings -- see -// zcert_public_txt () and zcert_secret_txt (). Call before binding socket: -// -// zstr_sendx (proxy, "CURVE", "FRONTEND", public_txt, secret_txt, NULL); -// zsock_wait (proxy); -// -// This is the zproxy constructor as a zactor_fn; the argument is a -// character string specifying frontend and backend socket types as two -// uppercase strings separated by a hyphen: -CZMQ_EXPORT void - zproxy (zsock_t *pipe, void *unused); - -// Selftest -CZMQ_EXPORT void - zproxy_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zproxy_v2.h b/phonelibs/zmq/arm/include/zproxy_v2.h deleted file mode 100644 index 4bde951591..0000000000 --- a/phonelibs/zmq/arm/include/zproxy_v2.h +++ /dev/null @@ -1,62 +0,0 @@ -/* ========================================================================= - zproxy_v2 - run a steerable proxy in the background (deprecated) - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZPROXY_V2_H_INCLUDED__ -#define __ZPROXY_V2_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface - -// Constructor -// Create a new zproxy object. You must create the frontend and backend -// sockets, configure them, and connect or bind them, before you pass them -// to the constructor. Do NOT use the sockets again, after passing them to -// this method. -CZMQ_EXPORT zproxy_t * - zproxy_new (zctx_t *ctx, void *frontend, void *backend); - -// Destructor -// Destroy a zproxy object; note this first stops the proxy. -CZMQ_EXPORT void - zproxy_destroy (zproxy_t **self_p); - -// Copy all proxied messages to specified endpoint; if this is NULL, any -// in-progress capturing will be stopped. You must already have bound the -// endpoint to a PULL socket. -CZMQ_EXPORT void - zproxy_capture (zproxy_t *self, const char *endpoint); - -// Pauses a zproxy object; a paused proxy will cease processing messages, -// causing them to be queued up and potentially hit the high-water mark on -// the frontend socket, causing messages to be dropped, or writing -// applications to block. -CZMQ_EXPORT void - zproxy_pause (zproxy_t *self); - -// Resume a zproxy object -CZMQ_EXPORT void - zproxy_resume (zproxy_t *self); - -// Self test of this class -CZMQ_EXPORT void - zproxy_v2_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zrex.h b/phonelibs/zmq/arm/include/zrex.h deleted file mode 100644 index 8b50618a34..0000000000 --- a/phonelibs/zmq/arm/include/zrex.h +++ /dev/null @@ -1,82 +0,0 @@ -/* ========================================================================= - zrex - work with regular expressions - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZREX_H_INCLUDED__ -#define __ZREX_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// Constructor. Optionally, sets an expression against which we can match -// text and capture hits. If there is an error in the expression, reports -// zrex_valid() as false and provides the error in zrex_strerror(). If you -// set a pattern, you can call zrex_matches() to test it against text. -CZMQ_EXPORT zrex_t * - zrex_new (const char *expression); - -// Destructor -CZMQ_EXPORT void - zrex_destroy (zrex_t **self_p); - -// Return true if the expression was valid and compiled without errors. -CZMQ_EXPORT bool - zrex_valid (zrex_t *self); - -// Return the error message generated during compilation of the expression. -CZMQ_EXPORT const char * - zrex_strerror (zrex_t *self); - -// Returns true if the text matches the previously compiled expression. -// Use this method to compare one expression against many strings. -CZMQ_EXPORT bool - zrex_matches (zrex_t *self, const char *text); - -// Returns true if the text matches the supplied expression. Use this -// method to compare one string against several expressions. -CZMQ_EXPORT bool - zrex_eq (zrex_t *self, const char *text, const char *expression); - -// Returns number of hits from last zrex_matches or zrex_eq. If the text -// matched, returns 1 plus the number of capture groups. If the text did -// not match, returns zero. To retrieve individual capture groups, call -// zrex_hit (). -CZMQ_EXPORT int - zrex_hits (zrex_t *self); - -// Returns the Nth capture group from the last expression match, where -// N is 0 to the value returned by zrex_hits(). Capture group 0 is the -// whole matching string. Sequence 1 is the first capture group, if any, -// and so on. -CZMQ_EXPORT const char * - zrex_hit (zrex_t *self, uint index); - -// Fetches hits into string variables provided by caller; this makes for -// nicer code than accessing hits by index. Caller should not modify nor -// free the returned values. Returns number of strings returned. This -// method starts at hit 1, i.e. first capture group, as hit 0 is always -// the original matched string. -CZMQ_EXPORT int - zrex_fetch (zrex_t *self, const char **string_p, ...); - -// Self test of this class -CZMQ_EXPORT void - zrex_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zsock.h b/phonelibs/zmq/arm/include/zsock.h deleted file mode 100644 index fc5c46e45e..0000000000 --- a/phonelibs/zmq/arm/include/zsock.h +++ /dev/null @@ -1,921 +0,0 @@ -/* ========================================================================= - zsock - high-level socket API that hides libzmq contexts and sockets - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZSOCK_H_INCLUDED__ -#define __ZSOCK_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// This interface includes some smart constructors, which create sockets with -// additional set-up. In all of these, the endpoint is NULL, or starts with -// '@' (bind) or '>' (connect). Multiple endpoints are allowed, separated by -// commas. If endpoint does not start with '@' or '>', default action depends -// on socket type. - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zsock.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// Create a new socket. Returns the new socket, or NULL if the new socket -// could not be created. Note that the symbol zsock_new (and other -// constructors/destructors for zsock) are redirected to the *_checked -// variant, enabling intelligent socket leak detection. This can have -// performance implications if you use a LOT of sockets. To turn off this -// redirection behaviour, define ZSOCK_NOCHECK. -CZMQ_EXPORT zsock_t * - zsock_new (int type); - -// Create a PUB socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_pub (const char *endpoint); - -// Create a SUB socket, and optionally subscribe to some prefix string. Default -// action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_sub (const char *endpoint, const char *subscribe); - -// Create a REQ socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_req (const char *endpoint); - -// Create a REP socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_rep (const char *endpoint); - -// Create a DEALER socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_dealer (const char *endpoint); - -// Create a ROUTER socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_router (const char *endpoint); - -// Create a PUSH socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_push (const char *endpoint); - -// Create a PULL socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_pull (const char *endpoint); - -// Create an XPUB socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_xpub (const char *endpoint); - -// Create an XSUB socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_xsub (const char *endpoint); - -// Create a PAIR socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_pair (const char *endpoint); - -// Create a STREAM socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_stream (const char *endpoint); - -// Destroy the socket. You must use this for any socket created via the -// zsock_new method. -CZMQ_EXPORT void - zsock_destroy (zsock_t **self_p); - -// Bind a socket to a formatted endpoint. For tcp:// endpoints, supports -// ephemeral ports, if you specify the port number as "*". By default -// zsock uses the IANA designated range from C000 (49152) to FFFF (65535). -// To override this range, follow the "*" with "[first-last]". Either or -// both first and last may be empty. To bind to a random port within the -// range, use "!" in place of "*". -// -// Examples: -// tcp://127.0.0.1:* bind to first free port from C000 up -// tcp://127.0.0.1:! bind to random port from C000 to FFFF -// tcp://127.0.0.1:*[60000-] bind to first free port from 60000 up -// tcp://127.0.0.1:![-60000] bind to random port from C000 to 60000 -// tcp://127.0.0.1:![55000-55999] -// bind to random port from 55000 to 55999 -// -// On success, returns the actual port number used, for tcp:// endpoints, -// and 0 for other transports. On failure, returns -1. Note that when using -// ephemeral ports, a port may be reused by different services without -// clients being aware. Protocols that run on ephemeral ports should take -// this into account. -CZMQ_EXPORT int - zsock_bind (zsock_t *self, const char *format, ...); - -// Returns last bound endpoint, if any. -CZMQ_EXPORT const char * - zsock_endpoint (zsock_t *self); - -// Unbind a socket from a formatted endpoint. -// Returns 0 if OK, -1 if the endpoint was invalid or the function -// isn't supported. -CZMQ_EXPORT int - zsock_unbind (zsock_t *self, const char *format, ...); - -// Connect a socket to a formatted endpoint -// Returns 0 if OK, -1 if the endpoint was invalid. -CZMQ_EXPORT int - zsock_connect (zsock_t *self, const char *format, ...); - -// Disconnect a socket from a formatted endpoint -// Returns 0 if OK, -1 if the endpoint was invalid or the function -// isn't supported. -CZMQ_EXPORT int - zsock_disconnect (zsock_t *self, const char *format, ...); - -// Attach a socket to zero or more endpoints. If endpoints is not null, -// parses as list of ZeroMQ endpoints, separated by commas, and prefixed by -// '@' (to bind the socket) or '>' (to connect the socket). Returns 0 if all -// endpoints were valid, or -1 if there was a syntax error. If the endpoint -// does not start with '@' or '>', the serverish argument defines whether -// it is used to bind (serverish = true) or connect (serverish = false). -CZMQ_EXPORT int - zsock_attach (zsock_t *self, const char *endpoints, bool serverish); - -// Returns socket type as printable constant string. -CZMQ_EXPORT const char * - zsock_type_str (zsock_t *self); - -// Send a 'picture' message to the socket (or actor). The picture is a -// string that defines the type of each frame. This makes it easy to send -// a complex multiframe message in one call. The picture can contain any -// of these characters, each corresponding to one or two arguments: -// -// i = int (signed) -// 1 = uint8_t -// 2 = uint16_t -// 4 = uint32_t -// 8 = uint64_t -// s = char * -// b = byte *, size_t (2 arguments) -// c = zchunk_t * -// f = zframe_t * -// h = zhashx_t * -// U = zuuid_t * -// p = void * (sends the pointer value, only meaningful over inproc) -// m = zmsg_t * (sends all frames in the zmsg) -// z = sends zero-sized frame (0 arguments) -// u = uint (deprecated) -// -// Note that s, b, c, and f are encoded the same way and the choice is -// offered as a convenience to the sender, which may or may not already -// have data in a zchunk or zframe. Does not change or take ownership of -// any arguments. Returns 0 if successful, -1 if sending failed for any -// reason. -CZMQ_EXPORT int - zsock_send (void *self, const char *picture, ...); - -// Send a 'picture' message to the socket (or actor). This is a va_list -// version of zsock_send (), so please consult its documentation for the -// details. -CZMQ_EXPORT int - zsock_vsend (void *self, const char *picture, va_list argptr); - -// Receive a 'picture' message to the socket (or actor). See zsock_send for -// the format and meaning of the picture. Returns the picture elements into -// a series of pointers as provided by the caller: -// -// i = int * (stores signed integer) -// 4 = uint32_t * (stores 32-bit unsigned integer) -// 8 = uint64_t * (stores 64-bit unsigned integer) -// s = char ** (allocates new string) -// b = byte **, size_t * (2 arguments) (allocates memory) -// c = zchunk_t ** (creates zchunk) -// f = zframe_t ** (creates zframe) -// U = zuuid_t * (creates a zuuid with the data) -// h = zhashx_t ** (creates zhashx) -// p = void ** (stores pointer) -// m = zmsg_t ** (creates a zmsg with the remaing frames) -// z = null, asserts empty frame (0 arguments) -// u = uint * (stores unsigned integer, deprecated) -// -// Note that zsock_recv creates the returned objects, and the caller must -// destroy them when finished with them. The supplied pointers do not need -// to be initialized. Returns 0 if successful, or -1 if it failed to recv -// a message, in which case the pointers are not modified. When message -// frames are truncated (a short message), sets return values to zero/null. -// If an argument pointer is NULL, does not store any value (skips it). -// An 'n' picture matches an empty frame; if the message does not match, -// the method will return -1. -CZMQ_EXPORT int - zsock_recv (void *self, const char *picture, ...); - -// Receive a 'picture' message from the socket (or actor). This is a -// va_list version of zsock_recv (), so please consult its documentation -// for the details. -CZMQ_EXPORT int - zsock_vrecv (void *self, const char *picture, va_list argptr); - -// Send a binary encoded 'picture' message to the socket (or actor). This -// method is similar to zsock_send, except the arguments are encoded in a -// binary format that is compatible with zproto, and is designed to reduce -// memory allocations. The pattern argument is a string that defines the -// type of each argument. Supports these argument types: -// -// pattern C type zproto type: -// 1 uint8_t type = "number" size = "1" -// 2 uint16_t type = "number" size = "2" -// 4 uint32_t type = "number" size = "3" -// 8 uint64_t type = "number" size = "4" -// s char *, 0-255 chars type = "string" -// S char *, 0-2^32-1 chars type = "longstr" -// c zchunk_t * type = "chunk" -// f zframe_t * type = "frame" -// u zuuid_t * type = "uuid" -// m zmsg_t * type = "msg" -// p void *, sends pointer value, only over inproc -// -// Does not change or take ownership of any arguments. Returns 0 if -// successful, -1 if sending failed for any reason. -CZMQ_EXPORT int - zsock_bsend (void *self, const char *picture, ...); - -// Receive a binary encoded 'picture' message from the socket (or actor). -// This method is similar to zsock_recv, except the arguments are encoded -// in a binary format that is compatible with zproto, and is designed to -// reduce memory allocations. The pattern argument is a string that defines -// the type of each argument. See zsock_bsend for the supported argument -// types. All arguments must be pointers; this call sets them to point to -// values held on a per-socket basis. -// Note that zsock_brecv creates the returned objects, and the caller must -// destroy them when finished with them. The supplied pointers do not need -// to be initialized. Returns 0 if successful, or -1 if it failed to read -// a message. -CZMQ_EXPORT int - zsock_brecv (void *self, const char *picture, ...); - -// Set socket to use unbounded pipes (HWM=0); use this in cases when you are -// totally certain the message volume can fit in memory. This method works -// across all versions of ZeroMQ. Takes a polymorphic socket reference. -CZMQ_EXPORT void - zsock_set_unbounded (void *self); - -// Send a signal over a socket. A signal is a short message carrying a -// success/failure code (by convention, 0 means OK). Signals are encoded -// to be distinguishable from "normal" messages. Accepts a zsock_t or a -// zactor_t argument, and returns 0 if successful, -1 if the signal could -// not be sent. Takes a polymorphic socket reference. -CZMQ_EXPORT int - zsock_signal (void *self, byte status); - -// Wait on a signal. Use this to coordinate between threads, over pipe -// pairs. Blocks until the signal is received. Returns -1 on error, 0 or -// greater on success. Accepts a zsock_t or a zactor_t as argument. -// Takes a polymorphic socket reference. -CZMQ_EXPORT int - zsock_wait (void *self); - -// If there is a partial message still waiting on the socket, remove and -// discard it. This is useful when reading partial messages, to get specific -// message types. -CZMQ_EXPORT void - zsock_flush (void *self); - -// Probe the supplied object, and report if it looks like a zsock_t. -// Takes a polymorphic socket reference. -CZMQ_EXPORT bool - zsock_is (void *self); - -// Probe the supplied reference. If it looks like a zsock_t instance, return -// the underlying libzmq socket handle; else if it looks like a file -// descriptor, return NULL; else if it looks like a libzmq socket handle, -// return the supplied value. Takes a polymorphic socket reference. -CZMQ_EXPORT void * - zsock_resolve (void *self); - -// Get socket option `tos`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_tos (void *self); - -// Set socket option `tos`. -CZMQ_EXPORT void - zsock_set_tos (void *self, int tos); - -// Set socket option `router_handover`. -CZMQ_EXPORT void - zsock_set_router_handover (void *self, int router_handover); - -// Set socket option `router_mandatory`. -CZMQ_EXPORT void - zsock_set_router_mandatory (void *self, int router_mandatory); - -// Set socket option `probe_router`. -CZMQ_EXPORT void - zsock_set_probe_router (void *self, int probe_router); - -// Set socket option `req_relaxed`. -CZMQ_EXPORT void - zsock_set_req_relaxed (void *self, int req_relaxed); - -// Set socket option `req_correlate`. -CZMQ_EXPORT void - zsock_set_req_correlate (void *self, int req_correlate); - -// Set socket option `conflate`. -CZMQ_EXPORT void - zsock_set_conflate (void *self, int conflate); - -// Get socket option `zap_domain`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_zap_domain (void *self); - -// Set socket option `zap_domain`. -CZMQ_EXPORT void - zsock_set_zap_domain (void *self, const char *zap_domain); - -// Get socket option `mechanism`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_mechanism (void *self); - -// Get socket option `plain_server`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_plain_server (void *self); - -// Set socket option `plain_server`. -CZMQ_EXPORT void - zsock_set_plain_server (void *self, int plain_server); - -// Get socket option `plain_username`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_plain_username (void *self); - -// Set socket option `plain_username`. -CZMQ_EXPORT void - zsock_set_plain_username (void *self, const char *plain_username); - -// Get socket option `plain_password`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_plain_password (void *self); - -// Set socket option `plain_password`. -CZMQ_EXPORT void - zsock_set_plain_password (void *self, const char *plain_password); - -// Get socket option `curve_server`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_curve_server (void *self); - -// Set socket option `curve_server`. -CZMQ_EXPORT void - zsock_set_curve_server (void *self, int curve_server); - -// Get socket option `curve_publickey`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_curve_publickey (void *self); - -// Set socket option `curve_publickey`. -CZMQ_EXPORT void - zsock_set_curve_publickey (void *self, const char *curve_publickey); - -// Set socket option `curve_publickey` from 32-octet binary -CZMQ_EXPORT void - zsock_set_curve_publickey_bin (void *self, const byte *curve_publickey); - -// Get socket option `curve_secretkey`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_curve_secretkey (void *self); - -// Set socket option `curve_secretkey`. -CZMQ_EXPORT void - zsock_set_curve_secretkey (void *self, const char *curve_secretkey); - -// Set socket option `curve_secretkey` from 32-octet binary -CZMQ_EXPORT void - zsock_set_curve_secretkey_bin (void *self, const byte *curve_secretkey); - -// Get socket option `curve_serverkey`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_curve_serverkey (void *self); - -// Set socket option `curve_serverkey`. -CZMQ_EXPORT void - zsock_set_curve_serverkey (void *self, const char *curve_serverkey); - -// Set socket option `curve_serverkey` from 32-octet binary -CZMQ_EXPORT void - zsock_set_curve_serverkey_bin (void *self, const byte *curve_serverkey); - -// Get socket option `gssapi_server`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_gssapi_server (void *self); - -// Set socket option `gssapi_server`. -CZMQ_EXPORT void - zsock_set_gssapi_server (void *self, int gssapi_server); - -// Get socket option `gssapi_plaintext`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_gssapi_plaintext (void *self); - -// Set socket option `gssapi_plaintext`. -CZMQ_EXPORT void - zsock_set_gssapi_plaintext (void *self, int gssapi_plaintext); - -// Get socket option `gssapi_principal`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_gssapi_principal (void *self); - -// Set socket option `gssapi_principal`. -CZMQ_EXPORT void - zsock_set_gssapi_principal (void *self, const char *gssapi_principal); - -// Get socket option `gssapi_service_principal`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_gssapi_service_principal (void *self); - -// Set socket option `gssapi_service_principal`. -CZMQ_EXPORT void - zsock_set_gssapi_service_principal (void *self, const char *gssapi_service_principal); - -// Get socket option `ipv6`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_ipv6 (void *self); - -// Set socket option `ipv6`. -CZMQ_EXPORT void - zsock_set_ipv6 (void *self, int ipv6); - -// Get socket option `immediate`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_immediate (void *self); - -// Set socket option `immediate`. -CZMQ_EXPORT void - zsock_set_immediate (void *self, int immediate); - -// Set socket option `router_raw`. -CZMQ_EXPORT void - zsock_set_router_raw (void *self, int router_raw); - -// Get socket option `ipv4only`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_ipv4only (void *self); - -// Set socket option `ipv4only`. -CZMQ_EXPORT void - zsock_set_ipv4only (void *self, int ipv4only); - -// Set socket option `delay_attach_on_connect`. -CZMQ_EXPORT void - zsock_set_delay_attach_on_connect (void *self, int delay_attach_on_connect); - -// Get socket option `type`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_type (void *self); - -// Get socket option `sndhwm`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_sndhwm (void *self); - -// Set socket option `sndhwm`. -CZMQ_EXPORT void - zsock_set_sndhwm (void *self, int sndhwm); - -// Get socket option `rcvhwm`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_rcvhwm (void *self); - -// Set socket option `rcvhwm`. -CZMQ_EXPORT void - zsock_set_rcvhwm (void *self, int rcvhwm); - -// Get socket option `affinity`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_affinity (void *self); - -// Set socket option `affinity`. -CZMQ_EXPORT void - zsock_set_affinity (void *self, int affinity); - -// Set socket option `subscribe`. -CZMQ_EXPORT void - zsock_set_subscribe (void *self, const char *subscribe); - -// Set socket option `unsubscribe`. -CZMQ_EXPORT void - zsock_set_unsubscribe (void *self, const char *unsubscribe); - -// Get socket option `identity`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_identity (void *self); - -// Set socket option `identity`. -CZMQ_EXPORT void - zsock_set_identity (void *self, const char *identity); - -// Get socket option `rate`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_rate (void *self); - -// Set socket option `rate`. -CZMQ_EXPORT void - zsock_set_rate (void *self, int rate); - -// Get socket option `recovery_ivl`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_recovery_ivl (void *self); - -// Set socket option `recovery_ivl`. -CZMQ_EXPORT void - zsock_set_recovery_ivl (void *self, int recovery_ivl); - -// Get socket option `sndbuf`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_sndbuf (void *self); - -// Set socket option `sndbuf`. -CZMQ_EXPORT void - zsock_set_sndbuf (void *self, int sndbuf); - -// Get socket option `rcvbuf`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_rcvbuf (void *self); - -// Set socket option `rcvbuf`. -CZMQ_EXPORT void - zsock_set_rcvbuf (void *self, int rcvbuf); - -// Get socket option `linger`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_linger (void *self); - -// Set socket option `linger`. -CZMQ_EXPORT void - zsock_set_linger (void *self, int linger); - -// Get socket option `reconnect_ivl`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_reconnect_ivl (void *self); - -// Set socket option `reconnect_ivl`. -CZMQ_EXPORT void - zsock_set_reconnect_ivl (void *self, int reconnect_ivl); - -// Get socket option `reconnect_ivl_max`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_reconnect_ivl_max (void *self); - -// Set socket option `reconnect_ivl_max`. -CZMQ_EXPORT void - zsock_set_reconnect_ivl_max (void *self, int reconnect_ivl_max); - -// Get socket option `backlog`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_backlog (void *self); - -// Set socket option `backlog`. -CZMQ_EXPORT void - zsock_set_backlog (void *self, int backlog); - -// Get socket option `maxmsgsize`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_maxmsgsize (void *self); - -// Set socket option `maxmsgsize`. -CZMQ_EXPORT void - zsock_set_maxmsgsize (void *self, int maxmsgsize); - -// Get socket option `multicast_hops`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_multicast_hops (void *self); - -// Set socket option `multicast_hops`. -CZMQ_EXPORT void - zsock_set_multicast_hops (void *self, int multicast_hops); - -// Get socket option `rcvtimeo`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_rcvtimeo (void *self); - -// Set socket option `rcvtimeo`. -CZMQ_EXPORT void - zsock_set_rcvtimeo (void *self, int rcvtimeo); - -// Get socket option `sndtimeo`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_sndtimeo (void *self); - -// Set socket option `sndtimeo`. -CZMQ_EXPORT void - zsock_set_sndtimeo (void *self, int sndtimeo); - -// Set socket option `xpub_verbose`. -CZMQ_EXPORT void - zsock_set_xpub_verbose (void *self, int xpub_verbose); - -// Get socket option `tcp_keepalive`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_tcp_keepalive (void *self); - -// Set socket option `tcp_keepalive`. -CZMQ_EXPORT void - zsock_set_tcp_keepalive (void *self, int tcp_keepalive); - -// Get socket option `tcp_keepalive_idle`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_tcp_keepalive_idle (void *self); - -// Set socket option `tcp_keepalive_idle`. -CZMQ_EXPORT void - zsock_set_tcp_keepalive_idle (void *self, int tcp_keepalive_idle); - -// Get socket option `tcp_keepalive_cnt`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_tcp_keepalive_cnt (void *self); - -// Set socket option `tcp_keepalive_cnt`. -CZMQ_EXPORT void - zsock_set_tcp_keepalive_cnt (void *self, int tcp_keepalive_cnt); - -// Get socket option `tcp_keepalive_intvl`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_tcp_keepalive_intvl (void *self); - -// Set socket option `tcp_keepalive_intvl`. -CZMQ_EXPORT void - zsock_set_tcp_keepalive_intvl (void *self, int tcp_keepalive_intvl); - -// Get socket option `tcp_accept_filter`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_tcp_accept_filter (void *self); - -// Set socket option `tcp_accept_filter`. -CZMQ_EXPORT void - zsock_set_tcp_accept_filter (void *self, const char *tcp_accept_filter); - -// Get socket option `rcvmore`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_rcvmore (void *self); - -// Get socket option `fd`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT SOCKET - zsock_fd (void *self); - -// Get socket option `events`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_events (void *self); - -// Get socket option `last_endpoint`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zsock_last_endpoint (void *self); - -// Self test of this class. -CZMQ_EXPORT void - zsock_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Create a SERVER socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_server (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a CLIENT socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_client (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a RADIO socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_radio (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a DISH socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_dish (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a GATHER socket. Default action is bind. -CZMQ_EXPORT zsock_t * - zsock_new_gather (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Create a SCATTER socket. Default action is connect. -CZMQ_EXPORT zsock_t * - zsock_new_scatter (const char *endpoint); - -// *** Draft method, for development use, may change without warning *** -// Return socket routing ID if any. This returns 0 if the socket is not -// of type ZMQ_SERVER or if no request was already received on it. -CZMQ_EXPORT uint32_t - zsock_routing_id (zsock_t *self); - -// *** Draft method, for development use, may change without warning *** -// Set routing ID on socket. The socket MUST be of type ZMQ_SERVER. -// This will be used when sending messages on the socket via the zsock API. -CZMQ_EXPORT void - zsock_set_routing_id (zsock_t *self, uint32_t routing_id); - -// *** Draft method, for development use, may change without warning *** -// Join a group for the RADIO-DISH pattern. Call only on ZMQ_DISH. -// Returns 0 if OK, -1 if failed. -CZMQ_EXPORT int - zsock_join (void *self, const char *group); - -// *** Draft method, for development use, may change without warning *** -// Leave a group for the RADIO-DISH pattern. Call only on ZMQ_DISH. -// Returns 0 if OK, -1 if failed. -CZMQ_EXPORT int - zsock_leave (void *self, const char *group); - -// *** Draft method, for development use, may change without warning *** -// Get socket option `heartbeat_ivl`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_heartbeat_ivl (void *self); - -// *** Draft method, for development use, may change without warning *** -// Set socket option `heartbeat_ivl`. -CZMQ_EXPORT void - zsock_set_heartbeat_ivl (void *self, int heartbeat_ivl); - -// *** Draft method, for development use, may change without warning *** -// Get socket option `heartbeat_ttl`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_heartbeat_ttl (void *self); - -// *** Draft method, for development use, may change without warning *** -// Set socket option `heartbeat_ttl`. -CZMQ_EXPORT void - zsock_set_heartbeat_ttl (void *self, int heartbeat_ttl); - -// *** Draft method, for development use, may change without warning *** -// Get socket option `heartbeat_timeout`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_heartbeat_timeout (void *self); - -// *** Draft method, for development use, may change without warning *** -// Set socket option `heartbeat_timeout`. -CZMQ_EXPORT void - zsock_set_heartbeat_timeout (void *self, int heartbeat_timeout); - -// *** Draft method, for development use, may change without warning *** -// Get socket option `use_fd`. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT int - zsock_use_fd (void *self); - -// *** Draft method, for development use, may change without warning *** -// Set socket option `use_fd`. -CZMQ_EXPORT void - zsock_set_use_fd (void *self, int use_fd); - -#endif // CZMQ_BUILD_DRAFT_API -// @ignore -CZMQ_EXPORT int - zsock_bind (zsock_t *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int - zsock_unbind (zsock_t *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int - zsock_connect (zsock_t *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int - zsock_disconnect (zsock_t *self, const char *format, ...) CHECK_PRINTF (2); -// @end - - -// zsock leak detection - not a part of the official interface to zsock. This -// enables CZMQ to report socket leaks intelligently. -#if defined ZSOCK_NOCHECK - // no checking active - use the above interface methods directly. -#else -# define zsock_new(t) zsock_new_checked((t), __FILE__, __LINE__) -# define zsock_new_pub(e) zsock_new_pub_checked((e), __FILE__, __LINE__) -# define zsock_new_sub(e,s) zsock_new_sub_checked((e), (s), __FILE__, __LINE__) -# define zsock_new_req(e) zsock_new_req_checked((e), __FILE__, __LINE__) -# define zsock_new_rep(e) zsock_new_rep_checked((e), __FILE__, __LINE__) -# define zsock_new_dealer(e) zsock_new_dealer_checked((e), __FILE__, __LINE__) -# define zsock_new_router(e) zsock_new_router_checked((e), __FILE__, __LINE__) -# define zsock_new_pull(e) zsock_new_pull_checked((e), __FILE__, __LINE__) -# define zsock_new_push(e) zsock_new_push_checked((e), __FILE__, __LINE__) -# define zsock_new_xpub(e) zsock_new_xpub_checked((e), __FILE__, __LINE__) -# define zsock_new_xsub(e) zsock_new_xsub_checked((e), __FILE__, __LINE__) -# define zsock_new_pair(e) zsock_new_pair_checked((e), __FILE__, __LINE__) -# define zsock_new_stream(e) zsock_new_stream_checked((e), __FILE__, __LINE__) -# define zsock_destroy(t) zsock_destroy_checked((t), __FILE__, __LINE__) -#endif - -CZMQ_EXPORT zsock_t * - zsock_new_checked (int type, const char *filename, size_t line_nbr); - -CZMQ_EXPORT void - zsock_destroy_checked (zsock_t **self_p, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_pub_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_sub_checked (const char *endpoint, const char *subscribe, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_req_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_rep_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_dealer_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_router_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_push_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_pull_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_xpub_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_xsub_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_pair_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_stream_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_server_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_client_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_radio_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_dish_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_gather_checked (const char *endpoint, const char *filename, size_t line_nbr); - -CZMQ_EXPORT zsock_t * - zsock_new_scatter_checked (const char *endpoint, const char *filename, size_t line_nbr); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zsocket.h b/phonelibs/zmq/arm/include/zsocket.h deleted file mode 100644 index a60a0d9db3..0000000000 --- a/phonelibs/zmq/arm/include/zsocket.h +++ /dev/null @@ -1,110 +0,0 @@ -/* ========================================================================= - zsocket - working with 0MQ sockets - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZSOCKET_H_INCLUDED__ -#define __ZSOCKET_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// This port range is defined by IANA for dynamic or private ports -// We use this when choosing a port for dynamic binding. -#define ZSOCKET_DYNFROM 0xc000 -#define ZSOCKET_DYNTO 0xffff - -// Callback function for zero-copy methods -typedef void (zsocket_free_fn) (void *data, void *arg); - -// Create a new socket within our CZMQ context, replaces zmq_socket. -// Use this to get automatic management of the socket at shutdown. -// Note: SUB sockets do not automatically subscribe to everything; you -// must set filters explicitly. -CZMQ_EXPORT void * - zsocket_new (zctx_t *self, int type); - -// Destroy a socket within our CZMQ context, replaces zmq_close. -CZMQ_EXPORT void - zsocket_destroy (zctx_t *ctx, void *self); - -// Bind a socket to a formatted endpoint. If the port is specified as -// '*', binds to any free port from ZSOCKET_DYNFROM to ZSOCKET_DYNTO -// and returns the actual port number used. Otherwise asserts that the -// bind succeeded with the specified port number. Always returns the -// port number if successful. -CZMQ_EXPORT int - zsocket_bind (void *self, const char *format, ...); - -// Unbind a socket from a formatted endpoint. -// Returns 0 if OK, -1 if the endpoint was invalid or the function -// isn't supported. -CZMQ_EXPORT int - zsocket_unbind (void *self, const char *format, ...); - -// Connect a socket to a formatted endpoint -// Returns 0 if OK, -1 if the endpoint was invalid. -CZMQ_EXPORT int - zsocket_connect (void *self, const char *format, ...); - -// Disconnect a socket from a formatted endpoint -// Returns 0 if OK, -1 if the endpoint was invalid or the function -// isn't supported. -CZMQ_EXPORT int - zsocket_disconnect (void *self, const char *format, ...); - -// Poll for input events on the socket. Returns TRUE if there is input -// ready on the socket, else FALSE. -CZMQ_EXPORT bool - zsocket_poll (void *self, int msecs); - -// Returns socket type as printable constant string -CZMQ_EXPORT const char * - zsocket_type_str (void *self); - -// Send data over a socket as a single message frame. -// Accepts these flags: ZFRAME_MORE and ZFRAME_DONTWAIT. -// Returns -1 on error, 0 on success -CZMQ_EXPORT int - zsocket_sendmem (void *self, const void *data, size_t size, int flags); - -// Send a signal over a socket. A signal is a zero-byte message. -// Signals are used primarily between threads, over pipe sockets. -// Returns -1 if there was an error sending the signal. -CZMQ_EXPORT int - zsocket_signal (void *self); - -// Wait on a signal. Use this to coordinate between threads, over -// pipe pairs. Returns -1 on error, 0 on success. -CZMQ_EXPORT int - zsocket_wait (void *self); - -// Self test of this class -CZMQ_EXPORT void - zsocket_test (bool verbose); -// @end - -// Compiler hints -CZMQ_EXPORT int zsocket_bind (void *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int zsocket_unbind (void *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int zsocket_connect (void *self, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int zsocket_disconnect (void *self, const char *format, ...) CHECK_PRINTF (2); - -// Emulation of widely-used 2.x socket options -CZMQ_EXPORT void zsocket_set_hwm (void *self, int hwm); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zsockopt.h b/phonelibs/zmq/arm/include/zsockopt.h deleted file mode 100644 index 5246986dd0..0000000000 --- a/phonelibs/zmq/arm/include/zsockopt.h +++ /dev/null @@ -1,256 +0,0 @@ -/* ========================================================================= - zsockopt - get/set 0MQ socket options (deprecated) - - **************************************************** - * GENERATED SOURCE CODE, DO NOT EDIT!! * - * TO CHANGE THIS, EDIT src/zsockopt.gsl * - * AND RUN `gsl sockopts` in src/. * - **************************************************** - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZSOCKOPT_H_INCLUDED__ -#define __ZSOCKOPT_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -#if (ZMQ_VERSION_MAJOR == 4) -// Get socket options -CZMQ_EXPORT int zsocket_heartbeat_ivl (void *zocket); -CZMQ_EXPORT int zsocket_heartbeat_ttl (void *zocket); -CZMQ_EXPORT int zsocket_heartbeat_timeout (void *zocket); -CZMQ_EXPORT int zsocket_use_fd (void *zocket); -CZMQ_EXPORT int zsocket_tos (void *zocket); -CZMQ_EXPORT char * zsocket_zap_domain (void *zocket); -CZMQ_EXPORT int zsocket_mechanism (void *zocket); -CZMQ_EXPORT int zsocket_plain_server (void *zocket); -CZMQ_EXPORT char * zsocket_plain_username (void *zocket); -CZMQ_EXPORT char * zsocket_plain_password (void *zocket); -CZMQ_EXPORT int zsocket_curve_server (void *zocket); -CZMQ_EXPORT char * zsocket_curve_publickey (void *zocket); -CZMQ_EXPORT char * zsocket_curve_secretkey (void *zocket); -CZMQ_EXPORT char * zsocket_curve_serverkey (void *zocket); -CZMQ_EXPORT int zsocket_gssapi_server (void *zocket); -CZMQ_EXPORT int zsocket_gssapi_plaintext (void *zocket); -CZMQ_EXPORT char * zsocket_gssapi_principal (void *zocket); -CZMQ_EXPORT char * zsocket_gssapi_service_principal (void *zocket); -CZMQ_EXPORT int zsocket_ipv6 (void *zocket); -CZMQ_EXPORT int zsocket_immediate (void *zocket); -CZMQ_EXPORT int zsocket_ipv4only (void *zocket); -CZMQ_EXPORT int zsocket_type (void *zocket); -CZMQ_EXPORT int zsocket_sndhwm (void *zocket); -CZMQ_EXPORT int zsocket_rcvhwm (void *zocket); -CZMQ_EXPORT int zsocket_affinity (void *zocket); -CZMQ_EXPORT char * zsocket_identity (void *zocket); -CZMQ_EXPORT int zsocket_rate (void *zocket); -CZMQ_EXPORT int zsocket_recovery_ivl (void *zocket); -CZMQ_EXPORT int zsocket_sndbuf (void *zocket); -CZMQ_EXPORT int zsocket_rcvbuf (void *zocket); -CZMQ_EXPORT int zsocket_linger (void *zocket); -CZMQ_EXPORT int zsocket_reconnect_ivl (void *zocket); -CZMQ_EXPORT int zsocket_reconnect_ivl_max (void *zocket); -CZMQ_EXPORT int zsocket_backlog (void *zocket); -CZMQ_EXPORT int zsocket_maxmsgsize (void *zocket); -CZMQ_EXPORT int zsocket_multicast_hops (void *zocket); -CZMQ_EXPORT int zsocket_rcvtimeo (void *zocket); -CZMQ_EXPORT int zsocket_sndtimeo (void *zocket); -CZMQ_EXPORT int zsocket_tcp_keepalive (void *zocket); -CZMQ_EXPORT int zsocket_tcp_keepalive_idle (void *zocket); -CZMQ_EXPORT int zsocket_tcp_keepalive_cnt (void *zocket); -CZMQ_EXPORT int zsocket_tcp_keepalive_intvl (void *zocket); -CZMQ_EXPORT char * zsocket_tcp_accept_filter (void *zocket); -CZMQ_EXPORT int zsocket_rcvmore (void *zocket); -CZMQ_EXPORT SOCKET zsocket_fd (void *zocket); -CZMQ_EXPORT int zsocket_events (void *zocket); -CZMQ_EXPORT char * zsocket_last_endpoint (void *zocket); - -// Set socket options -CZMQ_EXPORT void zsocket_set_heartbeat_ivl (void *zocket, int heartbeat_ivl); -CZMQ_EXPORT void zsocket_set_heartbeat_ttl (void *zocket, int heartbeat_ttl); -CZMQ_EXPORT void zsocket_set_heartbeat_timeout (void *zocket, int heartbeat_timeout); -CZMQ_EXPORT void zsocket_set_use_fd (void *zocket, int use_fd); -CZMQ_EXPORT void zsocket_set_tos (void *zocket, int tos); -CZMQ_EXPORT void zsocket_set_router_handover (void *zocket, int router_handover); -CZMQ_EXPORT void zsocket_set_router_mandatory (void *zocket, int router_mandatory); -CZMQ_EXPORT void zsocket_set_probe_router (void *zocket, int probe_router); -CZMQ_EXPORT void zsocket_set_req_relaxed (void *zocket, int req_relaxed); -CZMQ_EXPORT void zsocket_set_req_correlate (void *zocket, int req_correlate); -CZMQ_EXPORT void zsocket_set_conflate (void *zocket, int conflate); -CZMQ_EXPORT void zsocket_set_zap_domain (void *zocket, const char * zap_domain); -CZMQ_EXPORT void zsocket_set_plain_server (void *zocket, int plain_server); -CZMQ_EXPORT void zsocket_set_plain_username (void *zocket, const char * plain_username); -CZMQ_EXPORT void zsocket_set_plain_password (void *zocket, const char * plain_password); -CZMQ_EXPORT void zsocket_set_curve_server (void *zocket, int curve_server); -CZMQ_EXPORT void zsocket_set_curve_publickey (void *zocket, const char * curve_publickey); -CZMQ_EXPORT void zsocket_set_curve_publickey_bin (void *zocket, const byte *curve_publickey); -CZMQ_EXPORT void zsocket_set_curve_secretkey (void *zocket, const char * curve_secretkey); -CZMQ_EXPORT void zsocket_set_curve_secretkey_bin (void *zocket, const byte *curve_secretkey); -CZMQ_EXPORT void zsocket_set_curve_serverkey (void *zocket, const char * curve_serverkey); -CZMQ_EXPORT void zsocket_set_curve_serverkey_bin (void *zocket, const byte *curve_serverkey); -CZMQ_EXPORT void zsocket_set_gssapi_server (void *zocket, int gssapi_server); -CZMQ_EXPORT void zsocket_set_gssapi_plaintext (void *zocket, int gssapi_plaintext); -CZMQ_EXPORT void zsocket_set_gssapi_principal (void *zocket, const char * gssapi_principal); -CZMQ_EXPORT void zsocket_set_gssapi_service_principal (void *zocket, const char * gssapi_service_principal); -CZMQ_EXPORT void zsocket_set_ipv6 (void *zocket, int ipv6); -CZMQ_EXPORT void zsocket_set_immediate (void *zocket, int immediate); -CZMQ_EXPORT void zsocket_set_router_raw (void *zocket, int router_raw); -CZMQ_EXPORT void zsocket_set_ipv4only (void *zocket, int ipv4only); -CZMQ_EXPORT void zsocket_set_delay_attach_on_connect (void *zocket, int delay_attach_on_connect); -CZMQ_EXPORT void zsocket_set_sndhwm (void *zocket, int sndhwm); -CZMQ_EXPORT void zsocket_set_rcvhwm (void *zocket, int rcvhwm); -CZMQ_EXPORT void zsocket_set_affinity (void *zocket, int affinity); -CZMQ_EXPORT void zsocket_set_subscribe (void *zocket, const char * subscribe); -CZMQ_EXPORT void zsocket_set_unsubscribe (void *zocket, const char * unsubscribe); -CZMQ_EXPORT void zsocket_set_identity (void *zocket, const char * identity); -CZMQ_EXPORT void zsocket_set_rate (void *zocket, int rate); -CZMQ_EXPORT void zsocket_set_recovery_ivl (void *zocket, int recovery_ivl); -CZMQ_EXPORT void zsocket_set_sndbuf (void *zocket, int sndbuf); -CZMQ_EXPORT void zsocket_set_rcvbuf (void *zocket, int rcvbuf); -CZMQ_EXPORT void zsocket_set_linger (void *zocket, int linger); -CZMQ_EXPORT void zsocket_set_reconnect_ivl (void *zocket, int reconnect_ivl); -CZMQ_EXPORT void zsocket_set_reconnect_ivl_max (void *zocket, int reconnect_ivl_max); -CZMQ_EXPORT void zsocket_set_backlog (void *zocket, int backlog); -CZMQ_EXPORT void zsocket_set_maxmsgsize (void *zocket, int maxmsgsize); -CZMQ_EXPORT void zsocket_set_multicast_hops (void *zocket, int multicast_hops); -CZMQ_EXPORT void zsocket_set_rcvtimeo (void *zocket, int rcvtimeo); -CZMQ_EXPORT void zsocket_set_sndtimeo (void *zocket, int sndtimeo); -CZMQ_EXPORT void zsocket_set_xpub_verbose (void *zocket, int xpub_verbose); -CZMQ_EXPORT void zsocket_set_tcp_keepalive (void *zocket, int tcp_keepalive); -CZMQ_EXPORT void zsocket_set_tcp_keepalive_idle (void *zocket, int tcp_keepalive_idle); -CZMQ_EXPORT void zsocket_set_tcp_keepalive_cnt (void *zocket, int tcp_keepalive_cnt); -CZMQ_EXPORT void zsocket_set_tcp_keepalive_intvl (void *zocket, int tcp_keepalive_intvl); -CZMQ_EXPORT void zsocket_set_tcp_accept_filter (void *zocket, const char * tcp_accept_filter); -#endif - -#if (ZMQ_VERSION_MAJOR == 3) -// Get socket options -CZMQ_EXPORT int zsocket_ipv4only (void *zocket); -CZMQ_EXPORT int zsocket_type (void *zocket); -CZMQ_EXPORT int zsocket_sndhwm (void *zocket); -CZMQ_EXPORT int zsocket_rcvhwm (void *zocket); -CZMQ_EXPORT int zsocket_affinity (void *zocket); -CZMQ_EXPORT char * zsocket_identity (void *zocket); -CZMQ_EXPORT int zsocket_rate (void *zocket); -CZMQ_EXPORT int zsocket_recovery_ivl (void *zocket); -CZMQ_EXPORT int zsocket_sndbuf (void *zocket); -CZMQ_EXPORT int zsocket_rcvbuf (void *zocket); -CZMQ_EXPORT int zsocket_linger (void *zocket); -CZMQ_EXPORT int zsocket_reconnect_ivl (void *zocket); -CZMQ_EXPORT int zsocket_reconnect_ivl_max (void *zocket); -CZMQ_EXPORT int zsocket_backlog (void *zocket); -CZMQ_EXPORT int zsocket_maxmsgsize (void *zocket); -CZMQ_EXPORT int zsocket_multicast_hops (void *zocket); -CZMQ_EXPORT int zsocket_rcvtimeo (void *zocket); -CZMQ_EXPORT int zsocket_sndtimeo (void *zocket); -CZMQ_EXPORT int zsocket_tcp_keepalive (void *zocket); -CZMQ_EXPORT int zsocket_tcp_keepalive_idle (void *zocket); -CZMQ_EXPORT int zsocket_tcp_keepalive_cnt (void *zocket); -CZMQ_EXPORT int zsocket_tcp_keepalive_intvl (void *zocket); -CZMQ_EXPORT char * zsocket_tcp_accept_filter (void *zocket); -CZMQ_EXPORT int zsocket_rcvmore (void *zocket); -CZMQ_EXPORT SOCKET zsocket_fd (void *zocket); -CZMQ_EXPORT int zsocket_events (void *zocket); -CZMQ_EXPORT char * zsocket_last_endpoint (void *zocket); - -// Set socket options -CZMQ_EXPORT void zsocket_set_router_raw (void *zocket, int router_raw); -CZMQ_EXPORT void zsocket_set_ipv4only (void *zocket, int ipv4only); -CZMQ_EXPORT void zsocket_set_delay_attach_on_connect (void *zocket, int delay_attach_on_connect); -CZMQ_EXPORT void zsocket_set_sndhwm (void *zocket, int sndhwm); -CZMQ_EXPORT void zsocket_set_rcvhwm (void *zocket, int rcvhwm); -CZMQ_EXPORT void zsocket_set_affinity (void *zocket, int affinity); -CZMQ_EXPORT void zsocket_set_subscribe (void *zocket, const char * subscribe); -CZMQ_EXPORT void zsocket_set_unsubscribe (void *zocket, const char * unsubscribe); -CZMQ_EXPORT void zsocket_set_identity (void *zocket, const char * identity); -CZMQ_EXPORT void zsocket_set_rate (void *zocket, int rate); -CZMQ_EXPORT void zsocket_set_recovery_ivl (void *zocket, int recovery_ivl); -CZMQ_EXPORT void zsocket_set_sndbuf (void *zocket, int sndbuf); -CZMQ_EXPORT void zsocket_set_rcvbuf (void *zocket, int rcvbuf); -CZMQ_EXPORT void zsocket_set_linger (void *zocket, int linger); -CZMQ_EXPORT void zsocket_set_reconnect_ivl (void *zocket, int reconnect_ivl); -CZMQ_EXPORT void zsocket_set_reconnect_ivl_max (void *zocket, int reconnect_ivl_max); -CZMQ_EXPORT void zsocket_set_backlog (void *zocket, int backlog); -CZMQ_EXPORT void zsocket_set_maxmsgsize (void *zocket, int maxmsgsize); -CZMQ_EXPORT void zsocket_set_multicast_hops (void *zocket, int multicast_hops); -CZMQ_EXPORT void zsocket_set_rcvtimeo (void *zocket, int rcvtimeo); -CZMQ_EXPORT void zsocket_set_sndtimeo (void *zocket, int sndtimeo); -CZMQ_EXPORT void zsocket_set_xpub_verbose (void *zocket, int xpub_verbose); -CZMQ_EXPORT void zsocket_set_tcp_keepalive (void *zocket, int tcp_keepalive); -CZMQ_EXPORT void zsocket_set_tcp_keepalive_idle (void *zocket, int tcp_keepalive_idle); -CZMQ_EXPORT void zsocket_set_tcp_keepalive_cnt (void *zocket, int tcp_keepalive_cnt); -CZMQ_EXPORT void zsocket_set_tcp_keepalive_intvl (void *zocket, int tcp_keepalive_intvl); -CZMQ_EXPORT void zsocket_set_tcp_accept_filter (void *zocket, const char * tcp_accept_filter); -#endif - -#if (ZMQ_VERSION_MAJOR == 2) -// Get socket options -CZMQ_EXPORT int zsocket_hwm (void *zocket); -CZMQ_EXPORT int zsocket_swap (void *zocket); -CZMQ_EXPORT int zsocket_affinity (void *zocket); -CZMQ_EXPORT char * zsocket_identity (void *zocket); -CZMQ_EXPORT int zsocket_rate (void *zocket); -CZMQ_EXPORT int zsocket_recovery_ivl (void *zocket); -CZMQ_EXPORT int zsocket_recovery_ivl_msec (void *zocket); -CZMQ_EXPORT int zsocket_mcast_loop (void *zocket); -# if (ZMQ_VERSION_MINOR == 2) -CZMQ_EXPORT int zsocket_rcvtimeo (void *zocket); -# endif -# if (ZMQ_VERSION_MINOR == 2) -CZMQ_EXPORT int zsocket_sndtimeo (void *zocket); -# endif -CZMQ_EXPORT int zsocket_sndbuf (void *zocket); -CZMQ_EXPORT int zsocket_rcvbuf (void *zocket); -CZMQ_EXPORT int zsocket_linger (void *zocket); -CZMQ_EXPORT int zsocket_reconnect_ivl (void *zocket); -CZMQ_EXPORT int zsocket_reconnect_ivl_max (void *zocket); -CZMQ_EXPORT int zsocket_backlog (void *zocket); -CZMQ_EXPORT int zsocket_type (void *zocket); -CZMQ_EXPORT int zsocket_rcvmore (void *zocket); -CZMQ_EXPORT SOCKET zsocket_fd (void *zocket); -CZMQ_EXPORT int zsocket_events (void *zocket); - -// Set socket options -CZMQ_EXPORT void zsocket_set_hwm (void *zocket, int hwm); -CZMQ_EXPORT void zsocket_set_swap (void *zocket, int swap); -CZMQ_EXPORT void zsocket_set_affinity (void *zocket, int affinity); -CZMQ_EXPORT void zsocket_set_identity (void *zocket, const char * identity); -CZMQ_EXPORT void zsocket_set_rate (void *zocket, int rate); -CZMQ_EXPORT void zsocket_set_recovery_ivl (void *zocket, int recovery_ivl); -CZMQ_EXPORT void zsocket_set_recovery_ivl_msec (void *zocket, int recovery_ivl_msec); -CZMQ_EXPORT void zsocket_set_mcast_loop (void *zocket, int mcast_loop); -# if (ZMQ_VERSION_MINOR == 2) -CZMQ_EXPORT void zsocket_set_rcvtimeo (void *zocket, int rcvtimeo); -# endif -# if (ZMQ_VERSION_MINOR == 2) -CZMQ_EXPORT void zsocket_set_sndtimeo (void *zocket, int sndtimeo); -# endif -CZMQ_EXPORT void zsocket_set_sndbuf (void *zocket, int sndbuf); -CZMQ_EXPORT void zsocket_set_rcvbuf (void *zocket, int rcvbuf); -CZMQ_EXPORT void zsocket_set_linger (void *zocket, int linger); -CZMQ_EXPORT void zsocket_set_reconnect_ivl (void *zocket, int reconnect_ivl); -CZMQ_EXPORT void zsocket_set_reconnect_ivl_max (void *zocket, int reconnect_ivl_max); -CZMQ_EXPORT void zsocket_set_backlog (void *zocket, int backlog); -CZMQ_EXPORT void zsocket_set_subscribe (void *zocket, const char * subscribe); -CZMQ_EXPORT void zsocket_set_unsubscribe (void *zocket, const char * unsubscribe); -#endif - -// Self test of this class -CZMQ_EXPORT void zsockopt_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zstr.h b/phonelibs/zmq/arm/include/zstr.h deleted file mode 100644 index 3d3f1a862a..0000000000 --- a/phonelibs/zmq/arm/include/zstr.h +++ /dev/null @@ -1,115 +0,0 @@ -/* ========================================================================= - zstr - sending and receiving strings - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZSTR_H_INCLUDED__ -#define __ZSTR_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zstr.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// This class has draft methods, which may change over time. They are not -// in stable releases, by default. Use --enable-drafts to enable. -// Receive C string from socket. Caller must free returned string using -// zstr_free(). Returns NULL if the context is being terminated or the -// process was interrupted. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zstr_recv (void *source); - -// Receive a series of strings (until NULL) from multipart data. -// Each string is allocated and filled with string data; if there -// are not enough frames, unallocated strings are set to NULL. -// Returns -1 if the message could not be read, else returns the -// number of strings filled, zero or more. Free each returned string -// using zstr_free(). If not enough strings are provided, remaining -// multipart frames in the message are dropped. -CZMQ_EXPORT int - zstr_recvx (void *source, char **string_p, ...); - -// Send a C string to a socket, as a frame. The string is sent without -// trailing null byte; to read this you can use zstr_recv, or a similar -// method that adds a null terminator on the received string. String -// may be NULL, which is sent as "". -CZMQ_EXPORT int - zstr_send (void *dest, const char *string); - -// Send a C string to a socket, as zstr_send(), with a MORE flag, so that -// you can send further strings in the same multi-part message. -CZMQ_EXPORT int - zstr_sendm (void *dest, const char *string); - -// Send a formatted string to a socket. Note that you should NOT use -// user-supplied strings in the format (they may contain '%' which -// will create security holes). -CZMQ_EXPORT int - zstr_sendf (void *dest, const char *format, ...); - -// Send a formatted string to a socket, as for zstr_sendf(), with a -// MORE flag, so that you can send further strings in the same multi-part -// message. -CZMQ_EXPORT int - zstr_sendfm (void *dest, const char *format, ...); - -// Send a series of strings (until NULL) as multipart data -// Returns 0 if the strings could be sent OK, or -1 on error. -CZMQ_EXPORT int - zstr_sendx (void *dest, const char *string, ...); - -// Free a provided string, and nullify the parent pointer. Safe to call on -// a null pointer. -CZMQ_EXPORT void - zstr_free (char **string_p); - -// Self test of this class. -CZMQ_EXPORT void - zstr_test (bool verbose); - -#ifdef CZMQ_BUILD_DRAFT_API -// *** Draft method, for development use, may change without warning *** -// Accepts a void pointer and returns a fresh character string. If source -// is null, returns an empty string. -// Caller owns return value and must destroy it when done. -CZMQ_EXPORT char * - zstr_str (void *source); - -#endif // CZMQ_BUILD_DRAFT_API -// @ignore -CZMQ_EXPORT int - zstr_sendf (void *dest, const char *format, ...) CHECK_PRINTF (2); -CZMQ_EXPORT int - zstr_sendfm (void *dest, const char *format, ...) CHECK_PRINTF (2); -// @end - - -// DEPRECATED as poor style -- callers should use zloop or zpoller -// Receive C string from socket, if socket had input ready. Caller must -// free returned string using zstr_free. Returns NULL if there was no input -// waiting, or if the context was terminated. Use zctx_interrupted to exit -// any loop that relies on this method. -CZMQ_EXPORT char * - zstr_recv_nowait (void *source); - -// Compiler hints -CZMQ_EXPORT int zstr_sendf (void *dest, const char *format, ...) CHECK_PRINTF (2); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zsys.h b/phonelibs/zmq/arm/include/zsys.h deleted file mode 100644 index 97f88a9555..0000000000 --- a/phonelibs/zmq/arm/include/zsys.h +++ /dev/null @@ -1,386 +0,0 @@ -/* ========================================================================= - zsys - system-level methods - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZSYS_H_INCLUDED__ -#define __ZSYS_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -#define UDP_FRAME_MAX 255 // Max size of UDP frame - -// Callback for interrupt signal handler -typedef void (zsys_handler_fn) (int signal_value); - -// Initialize CZMQ zsys layer; this happens automatically when you create -// a socket or an actor; however this call lets you force initialization -// earlier, so e.g. logging is properly set-up before you start working. -// Not threadsafe, so call only from main thread. Safe to call multiple -// times. Returns global CZMQ context. -CZMQ_EXPORT void * - zsys_init (void); - -// Optionally shut down the CZMQ zsys layer; this normally happens automatically -// when the process exits; however this call lets you force a shutdown -// earlier, avoiding any potential problems with atexit() ordering, especially -// with Windows dlls. -CZMQ_EXPORT void - zsys_shutdown (void); - -// Get a new ZMQ socket, automagically creating a ZMQ context if this is -// the first time. Caller is responsible for destroying the ZMQ socket -// before process exits, to avoid a ZMQ deadlock. Note: you should not use -// this method in CZMQ apps, use zsock_new() instead. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT void * - zsys_socket (int type, const char *filename, size_t line_nbr); - -// Destroy/close a ZMQ socket. You should call this for every socket you -// create using zsys_socket(). -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT int - zsys_close (void *handle, const char *filename, size_t line_nbr); - -// Return ZMQ socket name for socket type -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT char * - zsys_sockname (int socktype); - -// Create a pipe, which consists of two PAIR sockets connected over inproc. -// The pipe is configured to use the zsys_pipehwm setting. Returns the -// frontend socket successful, NULL if failed. -CZMQ_EXPORT zsock_t * - zsys_create_pipe (zsock_t **backend_p); - -// Set interrupt handler; this saves the default handlers so that a -// zsys_handler_reset () can restore them. If you call this multiple times -// then the last handler will take affect. If handler_fn is NULL, disables -// default SIGINT/SIGTERM handling in CZMQ. -CZMQ_EXPORT void - zsys_handler_set (zsys_handler_fn *handler_fn); - -// Reset interrupt handler, call this at exit if needed -CZMQ_EXPORT void - zsys_handler_reset (void); - -// Set default interrupt handler, so Ctrl-C or SIGTERM will set -// zsys_interrupted. Idempotent; safe to call multiple times. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT void - zsys_catch_interrupts (void); - -// Return 1 if file exists, else zero -CZMQ_EXPORT bool - zsys_file_exists (const char *filename); - -// Return size of file, or -1 if not found -CZMQ_EXPORT ssize_t - zsys_file_size (const char *filename); - -// Return file modification time. Returns 0 if the file does not exist. -CZMQ_EXPORT time_t - zsys_file_modified (const char *filename); - -// Return file mode; provides at least support for the POSIX S_ISREG(m) -// and S_ISDIR(m) macros and the S_IRUSR and S_IWUSR bits, on all boxes. -// Returns a mode_t cast to int, or -1 in case of error. -CZMQ_EXPORT int - zsys_file_mode (const char *filename); - -// Delete file. Does not complain if the file is absent -CZMQ_EXPORT int - zsys_file_delete (const char *filename); - -// Check if file is 'stable' -CZMQ_EXPORT bool - zsys_file_stable (const char *filename); - -// Create a file path if it doesn't exist. The file path is treated as a -// printf format. -CZMQ_EXPORT int - zsys_dir_create (const char *pathname, ...); - -// Remove a file path if empty; the pathname is treated as printf format. -CZMQ_EXPORT int - zsys_dir_delete (const char *pathname, ...); - -// Move to a specified working directory. Returns 0 if OK, -1 if this failed. -CZMQ_EXPORT int - zsys_dir_change (const char *pathname); - -// Set private file creation mode; all files created from here will be -// readable/writable by the owner only. -CZMQ_EXPORT void - zsys_file_mode_private (void); - -// Reset default file creation mode; all files created from here will use -// process file mode defaults. -CZMQ_EXPORT void - zsys_file_mode_default (void); - -// Return the CZMQ version for run-time API detection; returns version -// number into provided fields, providing reference isn't null in each case. -CZMQ_EXPORT void - zsys_version (int *major, int *minor, int *patch); - -// Format a string using printf formatting, returning a freshly allocated -// buffer. If there was insufficient memory, returns NULL. Free the returned -// string using zstr_free(). -CZMQ_EXPORT char * - zsys_sprintf (const char *format, ...); - -// Format a string with a va_list argument, returning a freshly allocated -// buffer. If there was insufficient memory, returns NULL. Free the returned -// string using zstr_free(). -CZMQ_EXPORT char * - zsys_vprintf (const char *format, va_list argptr); - -// Create UDP beacon socket; if the routable option is true, uses -// multicast (not yet implemented), else uses broadcast. This method -// and related ones might _eventually_ be moved to a zudp class. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT SOCKET - zsys_udp_new (bool routable); - -// Close a UDP socket -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT int - zsys_udp_close (SOCKET handle); - -// Send zframe to UDP socket, return -1 if sending failed due to -// interface having disappeared (happens easily with WiFi) -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT int - zsys_udp_send (SOCKET udpsock, zframe_t *frame, inaddr_t *address, int addrlen); - -// Receive zframe from UDP socket, and set address of peer that sent it -// The peername must be a char [INET_ADDRSTRLEN] array. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT zframe_t * - zsys_udp_recv (SOCKET udpsock, char *peername, int peerlen); - -// Handle an I/O error on some socket operation; will report and die on -// fatal errors, and continue silently on "try again" errors. -// *** This is for CZMQ internal use only and may change arbitrarily *** -CZMQ_EXPORT void - zsys_socket_error (const char *reason); - -// Return current host name, for use in public tcp:// endpoints. Caller gets -// a freshly allocated string, should free it using zstr_free(). If the host -// name is not resolvable, returns NULL. -CZMQ_EXPORT char * - zsys_hostname (void); - -// Move the current process into the background. The precise effect depends -// on the operating system. On POSIX boxes, moves to a specified working -// directory (if specified), closes all file handles, reopens stdin, stdout, -// and stderr to the null device, and sets the process to ignore SIGHUP. On -// Windows, does nothing. Returns 0 if OK, -1 if there was an error. -CZMQ_EXPORT int - zsys_daemonize (const char *workdir); - -// Drop the process ID into the lockfile, with exclusive lock, and switch -// the process to the specified group and/or user. Any of the arguments -// may be null, indicating a no-op. Returns 0 on success, -1 on failure. -// Note if you combine this with zsys_daemonize, run after, not before -// that method, or the lockfile will hold the wrong process ID. -CZMQ_EXPORT int - zsys_run_as (const char *lockfile, const char *group, const char *user); - -// Returns true if the underlying libzmq supports CURVE security. -// Uses a heuristic probe according to the version of libzmq being used. -CZMQ_EXPORT bool - zsys_has_curve (void); - -// Configure the number of I/O threads that ZeroMQ will use. A good -// rule of thumb is one thread per gigabit of traffic in or out. The -// default is 1, sufficient for most applications. If the environment -// variable ZSYS_IO_THREADS is defined, that provides the default. -// Note that this method is valid only before any socket is created. -CZMQ_EXPORT void - zsys_set_io_threads (size_t io_threads); - -// Configure the number of sockets that ZeroMQ will allow. The default -// is 1024. The actual limit depends on the system, and you can query it -// by using zsys_socket_limit (). A value of zero means "maximum". -// Note that this method is valid only before any socket is created. -CZMQ_EXPORT void - zsys_set_max_sockets (size_t max_sockets); - -// Return maximum number of ZeroMQ sockets that the system will support. -CZMQ_EXPORT size_t - zsys_socket_limit (void); - -// Configure the default linger timeout in msecs for new zsock instances. -// You can also set this separately on each zsock_t instance. The default -// linger time is zero, i.e. any pending messages will be dropped. If the -// environment variable ZSYS_LINGER is defined, that provides the default. -// Note that process exit will typically be delayed by the linger time. -CZMQ_EXPORT void - zsys_set_linger (size_t linger); - -// Configure the default outgoing pipe limit (HWM) for new zsock instances. -// You can also set this separately on each zsock_t instance. The default -// HWM is 1,000, on all versions of ZeroMQ. If the environment variable -// ZSYS_SNDHWM is defined, that provides the default. Note that a value of -// zero means no limit, i.e. infinite memory consumption. -CZMQ_EXPORT void - zsys_set_sndhwm (size_t sndhwm); - -// Configure the default incoming pipe limit (HWM) for new zsock instances. -// You can also set this separately on each zsock_t instance. The default -// HWM is 1,000, on all versions of ZeroMQ. If the environment variable -// ZSYS_RCVHWM is defined, that provides the default. Note that a value of -// zero means no limit, i.e. infinite memory consumption. -CZMQ_EXPORT void - zsys_set_rcvhwm (size_t rcvhwm); - -// Configure the default HWM for zactor internal pipes; this is set on both -// ends of the pipe, for outgoing messages only (sndhwm). The default HWM is -// 1,000, on all versions of ZeroMQ. If the environment var ZSYS_ACTORHWM is -// defined, that provides the default. Note that a value of zero means no -// limit, i.e. infinite memory consumption. -CZMQ_EXPORT void - zsys_set_pipehwm (size_t pipehwm); - -// Return the HWM for zactor internal pipes. -CZMQ_EXPORT size_t - zsys_pipehwm (void); - -// Configure use of IPv6 for new zsock instances. By default sockets accept -// and make only IPv4 connections. When you enable IPv6, sockets will accept -// and connect to both IPv4 and IPv6 peers. You can override the setting on -// each zsock_t instance. The default is IPv4 only (ipv6 set to 0). If the -// environment variable ZSYS_IPV6 is defined (as 1 or 0), this provides the -// default. Note: has no effect on ZMQ v2. -CZMQ_EXPORT void - zsys_set_ipv6 (int ipv6); - -// Return use of IPv6 for zsock instances. -CZMQ_EXPORT int - zsys_ipv6 (void); - -// Set network interface name to use for broadcasts, particularly zbeacon. -// This lets the interface be configured for test environments where required. -// For example, on Mac OS X, zbeacon cannot bind to 255.255.255.255 which is -// the default when there is no specified interface. If the environment -// variable ZSYS_INTERFACE is set, use that as the default interface name. -// Setting the interface to "*" means "use all available interfaces". -CZMQ_EXPORT void - zsys_set_interface (const char *value); - -// Return network interface to use for broadcasts, or "" if none was set. -CZMQ_EXPORT const char * - zsys_interface (void); - -// Set IPv6 address to use zbeacon socket, particularly for receiving zbeacon. -// This needs to be set IPv6 is enabled as IPv6 can have multiple addresses -// on a given interface. If the environment variable ZSYS_IPV6_ADDRESS is set, -// use that as the default IPv6 address. -CZMQ_EXPORT void - zsys_set_ipv6_address (const char *value); - -// Return IPv6 address to use for zbeacon reception, or "" if none was set. -CZMQ_EXPORT const char * - zsys_ipv6_address (void); - -// Set IPv6 milticast address to use for sending zbeacon messages. This needs -// to be set if IPv6 is enabled. If the environment variable -// ZSYS_IPV6_MCAST_ADDRESS is set, use that as the default IPv6 multicast -// address. -CZMQ_EXPORT void - zsys_set_ipv6_mcast_address (const char *value); - -// Return IPv6 multicast address to use for sending zbeacon, or "" if none was -// set. -CZMQ_EXPORT const char * - zsys_ipv6_mcast_address (void); - -// Configure the automatic use of pre-allocated FDs when creating new sockets. -// If 0 (default), nothing will happen. Else, when a new socket is bound, the -// system API will be used to check if an existing pre-allocated FD with a -// matching port (if TCP) or path (if IPC) exists, and if it does it will be -// set via the ZMQ_USE_FD socket option so that the library will use it -// instead of creating a new socket. -CZMQ_EXPORT void - zsys_set_auto_use_fd (int auto_use_fd); - -// Return use of automatic pre-allocated FDs for zsock instances. -CZMQ_EXPORT int - zsys_auto_use_fd (void); - -// Set log identity, which is a string that prefixes all log messages sent -// by this process. The log identity defaults to the environment variable -// ZSYS_LOGIDENT, if that is set. -CZMQ_EXPORT void - zsys_set_logident (const char *value); - -// Set stream to receive log traffic. By default, log traffic is sent to -// stdout. If you set the stream to NULL, no stream will receive the log -// traffic (it may still be sent to the system facility). -CZMQ_EXPORT void - zsys_set_logstream (FILE *stream); - -// Sends log output to a PUB socket bound to the specified endpoint. To -// collect such log output, create a SUB socket, subscribe to the traffic -// you care about, and connect to the endpoint. Log traffic is sent as a -// single string frame, in the same format as when sent to stdout. The -// log system supports a single sender; multiple calls to this method will -// bind the same sender to multiple endpoints. To disable the sender, call -// this method with a null argument. -CZMQ_EXPORT void - zsys_set_logsender (const char *endpoint); - -// Enable or disable logging to the system facility (syslog on POSIX boxes, -// event log on Windows). By default this is disabled. -CZMQ_EXPORT void - zsys_set_logsystem (bool logsystem); - -// Log error condition - highest priority -CZMQ_EXPORT void - zsys_error (const char *format, ...); - -// Log warning condition - high priority -CZMQ_EXPORT void - zsys_warning (const char *format, ...); - -// Log normal, but significant, condition - normal priority -CZMQ_EXPORT void - zsys_notice (const char *format, ...); - -// Log informational message - low priority -CZMQ_EXPORT void - zsys_info (const char *format, ...); - -// Log debug-level message - lowest priority -CZMQ_EXPORT void - zsys_debug (const char *format, ...); - -// Self test of this class -CZMQ_EXPORT void - zsys_test (bool verbose); - -// Global signal indicator, TRUE when user presses Ctrl-C or the process -// gets a SIGTERM signal. -CZMQ_EXPORT extern volatile int zsys_interrupted; -// Deprecated name for this variable -CZMQ_EXPORT extern volatile int zctx_interrupted; -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zthread.h b/phonelibs/zmq/arm/include/zthread.h deleted file mode 100644 index fc0602dd9f..0000000000 --- a/phonelibs/zmq/arm/include/zthread.h +++ /dev/null @@ -1,50 +0,0 @@ -/* ========================================================================= - zthread - working with system threads (deprecated) - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZTHREAD_H_INCLUDED__ -#define __ZTHREAD_H_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -// @interface -// Detached threads follow POSIX pthreads API -typedef void *(zthread_detached_fn) (void *args); - -// Attached threads get context and pipe from parent -typedef void (zthread_attached_fn) (void *args, zctx_t *ctx, void *pipe); - -// Create a detached thread. A detached thread operates autonomously -// and is used to simulate a separate process. It gets no ctx, and no -// pipe. -CZMQ_EXPORT int - zthread_new (zthread_detached_fn *thread_fn, void *args); - -// Create an attached thread. An attached thread gets a ctx and a PAIR -// pipe back to its parent. It must monitor its pipe, and exit if the -// pipe becomes unreadable. Do not destroy the ctx, the thread does this -// automatically when it ends. -CZMQ_EXPORT void * - zthread_fork (zctx_t *ctx, zthread_attached_fn *thread_fn, void *args); - -// Self test of this class -CZMQ_EXPORT void - zthread_test (bool verbose); -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/ztimerset.h b/phonelibs/zmq/arm/include/ztimerset.h deleted file mode 100644 index 29633fafdb..0000000000 --- a/phonelibs/zmq/arm/include/ztimerset.h +++ /dev/null @@ -1,90 +0,0 @@ -/* ========================================================================= - ztimerset - timer set - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef ZTIMERSET_H_INCLUDED -#define ZTIMERSET_H_INCLUDED - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/ztimerset.api" to make changes. -// @interface -// This is a draft class, and may change without notice. It is disabled in -// stable builds by default. If you use this in applications, please ask -// for it to be pushed to stable state. Use --enable-drafts to enable. -#ifdef CZMQ_BUILD_DRAFT_API -// Callback function for timer event. -typedef void (ztimerset_fn) ( - int timer_id, void *arg); - -// *** Draft method, for development use, may change without warning *** -// Create new timer set. -CZMQ_EXPORT ztimerset_t * - ztimerset_new (void); - -// *** Draft method, for development use, may change without warning *** -// Destroy a timer set -CZMQ_EXPORT void - ztimerset_destroy (ztimerset_t **self_p); - -// *** Draft method, for development use, may change without warning *** -// Add a timer to the set. Returns timer id if OK, -1 on failure. -CZMQ_EXPORT int - ztimerset_add (ztimerset_t *self, size_t interval, ztimerset_fn handler, void *arg); - -// *** Draft method, for development use, may change without warning *** -// Cancel a timer. Returns 0 if OK, -1 on failure. -CZMQ_EXPORT int - ztimerset_cancel (ztimerset_t *self, int timer_id); - -// *** Draft method, for development use, may change without warning *** -// Set timer interval. Returns 0 if OK, -1 on failure. -// This method is slow, canceling the timer and adding a new one yield better performance. -CZMQ_EXPORT int - ztimerset_set_interval (ztimerset_t *self, int timer_id, size_t interval); - -// *** Draft method, for development use, may change without warning *** -// Reset timer to start interval counting from current time. Returns 0 if OK, -1 on failure. -// This method is slow, canceling the timer and adding a new one yield better performance. -CZMQ_EXPORT int - ztimerset_reset (ztimerset_t *self, int timer_id); - -// *** Draft method, for development use, may change without warning *** -// Return the time until the next interval. -// Should be used as timeout parameter for the zpoller wait method. -// The timeout is in msec. -CZMQ_EXPORT int - ztimerset_timeout (ztimerset_t *self); - -// *** Draft method, for development use, may change without warning *** -// Invoke callback function of all timers which their interval has elapsed. -// Should be call after zpoller wait method. -// Returns 0 if OK, -1 on failure. -CZMQ_EXPORT int - ztimerset_execute (ztimerset_t *self); - -// *** Draft method, for development use, may change without warning *** -// Self test of this class. -CZMQ_EXPORT void - ztimerset_test (bool verbose); - -#endif // CZMQ_BUILD_DRAFT_API -// @end - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/ztrie.h b/phonelibs/zmq/arm/include/ztrie.h deleted file mode 100644 index 6fd53234b1..0000000000 --- a/phonelibs/zmq/arm/include/ztrie.h +++ /dev/null @@ -1,106 +0,0 @@ -/* ========================================================================= - ztrie - simple trie for tokenizable strings - - Copyright (c) 1991-2012 iMatix Corporation -- http://www.imatix.com - Copyright other contributors as noted in the AUTHORS file. - - This file is part of CZMQ, the high-level C binding for 0MQ: http://czmq.zeromq.org - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef ZTRIE_H_INCLUDED -#define ZTRIE_H_INCLUDED - -#ifdef __cplusplus -extern "C" { -#endif - - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/ztrie.api" to make changes. -// @interface -// This is a draft class, and may change without notice. It is disabled in -// stable builds by default. If you use this in applications, please ask -// for it to be pushed to stable state. Use --enable-drafts to enable. -#ifdef CZMQ_BUILD_DRAFT_API -// Callback function for ztrie_node to destroy node data. -typedef void (ztrie_destroy_data_fn) ( - void **data); - -// *** Draft method, for development use, may change without warning *** -// Creates a new ztrie. -CZMQ_EXPORT ztrie_t * - ztrie_new (char delimiter); - -// *** Draft method, for development use, may change without warning *** -// Destroy the ztrie. -CZMQ_EXPORT void - ztrie_destroy (ztrie_t **self_p); - -// *** Draft method, for development use, may change without warning *** -// Inserts a new route into the tree and attaches the data. Returns -1 -// if the route already exists, otherwise 0. This method takes ownership of -// the provided data if a destroy_data_fn is provided. -CZMQ_EXPORT int - ztrie_insert_route (ztrie_t *self, const char *path, void *data, ztrie_destroy_data_fn destroy_data_fn); - -// *** Draft method, for development use, may change without warning *** -// Removes a route from the trie and destroys its data. Returns -1 if the -// route does not exists, otherwise 0. -// the start of the list call zlist_first (). Advances the cursor. -CZMQ_EXPORT int - ztrie_remove_route (ztrie_t *self, const char *path); - -// *** Draft method, for development use, may change without warning *** -// Returns true if the path matches a route in the tree, otherwise false. -CZMQ_EXPORT bool - ztrie_matches (ztrie_t *self, const char *path); - -// *** Draft method, for development use, may change without warning *** -// Returns the data of a matched route from last ztrie_matches. If the path -// did not match, returns NULL. Do not delete the data as it's owned by -// ztrie. -CZMQ_EXPORT void * - ztrie_hit_data (ztrie_t *self); - -// *** Draft method, for development use, may change without warning *** -// Returns the count of parameters that a matched route has. -CZMQ_EXPORT size_t - ztrie_hit_parameter_count (ztrie_t *self); - -// *** Draft method, for development use, may change without warning *** -// Returns the parameters of a matched route with named regexes from last -// ztrie_matches. If the path did not match or the route did not contain any -// named regexes, returns NULL. -CZMQ_EXPORT zhashx_t * - ztrie_hit_parameters (ztrie_t *self); - -// *** Draft method, for development use, may change without warning *** -// Returns the asterisk matched part of a route, if there has been no match -// or no asterisk match, returns NULL. -CZMQ_EXPORT const char * - ztrie_hit_asterisk_match (ztrie_t *self); - -// *** Draft method, for development use, may change without warning *** -// Print the trie -CZMQ_EXPORT void - ztrie_print (ztrie_t *self); - -// *** Draft method, for development use, may change without warning *** -// Self test of this class. -CZMQ_EXPORT void - ztrie_test (bool verbose); - -#endif // CZMQ_BUILD_DRAFT_API -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/include/zuuid.h b/phonelibs/zmq/arm/include/zuuid.h deleted file mode 100644 index afc1104fea..0000000000 --- a/phonelibs/zmq/arm/include/zuuid.h +++ /dev/null @@ -1,96 +0,0 @@ -/* ========================================================================= - zuuid - UUID support class - - Copyright (c) the Contributors as noted in the AUTHORS file. - This file is part of CZMQ, the high-level C binding for 0MQ: - http://czmq.zeromq.org. - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - ========================================================================= -*/ - -#ifndef __ZUUID_H_INCLUDED__ -#define __ZUUID_H_INCLUDED__ - -#define ZUUID_LEN 16 -#define ZUUID_STR_LEN (ZUUID_LEN * 2) - -#ifdef __cplusplus -extern "C" { -#endif - -// @warning THE FOLLOWING @INTERFACE BLOCK IS AUTO-GENERATED BY ZPROJECT -// @warning Please edit the model at "api/zuuid.api" to make changes. -// @interface -// This is a stable class, and may not change except for emergencies. It -// is provided in stable builds. -// Create a new UUID object. -CZMQ_EXPORT zuuid_t * - zuuid_new (void); - -// Create UUID object from supplied ZUUID_LEN-octet value. -CZMQ_EXPORT zuuid_t * - zuuid_new_from (const byte *source); - -// Destroy a specified UUID object. -CZMQ_EXPORT void - zuuid_destroy (zuuid_t **self_p); - -// Set UUID to new supplied ZUUID_LEN-octet value. -CZMQ_EXPORT void - zuuid_set (zuuid_t *self, const byte *source); - -// Set UUID to new supplied string value skipping '-' and '{' '}' -// optional delimiters. Return 0 if OK, else returns -1. -CZMQ_EXPORT int - zuuid_set_str (zuuid_t *self, const char *source); - -// Return UUID binary data. -CZMQ_EXPORT const byte * - zuuid_data (zuuid_t *self); - -// Return UUID binary size -CZMQ_EXPORT size_t - zuuid_size (zuuid_t *self); - -// Returns UUID as string -CZMQ_EXPORT const char * - zuuid_str (zuuid_t *self); - -// Return UUID in the canonical string format: 8-4-4-4-12, in lower -// case. Caller does not modify or free returned value. See -// http://en.wikipedia.org/wiki/Universally_unique_identifier -CZMQ_EXPORT const char * - zuuid_str_canonical (zuuid_t *self); - -// Store UUID blob in target array -CZMQ_EXPORT void - zuuid_export (zuuid_t *self, byte *target); - -// Check if UUID is same as supplied value -CZMQ_EXPORT bool - zuuid_eq (zuuid_t *self, const byte *compare); - -// Check if UUID is different from supplied value -CZMQ_EXPORT bool - zuuid_neq (zuuid_t *self, const byte *compare); - -// Make copy of UUID object; if uuid is null, or memory was exhausted, -// returns null. -CZMQ_EXPORT zuuid_t * - zuuid_dup (zuuid_t *self); - -// Self test of this class. -CZMQ_EXPORT void - zuuid_test (bool verbose); - -// @end - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/phonelibs/zmq/arm/lib/libczmq.a b/phonelibs/zmq/arm/lib/libczmq.a deleted file mode 100644 index cb78e4b829..0000000000 Binary files a/phonelibs/zmq/arm/lib/libczmq.a and /dev/null differ diff --git a/phonelibs/zmq/arm/lib/libczmq.so b/phonelibs/zmq/arm/lib/libczmq.so deleted file mode 100755 index 87ee937f72..0000000000 Binary files a/phonelibs/zmq/arm/lib/libczmq.so and /dev/null differ diff --git a/phonelibs/zmq/arm/lib/libzmq.a b/phonelibs/zmq/arm/lib/libzmq.a deleted file mode 100644 index cd523cd73e..0000000000 Binary files a/phonelibs/zmq/arm/lib/libzmq.a and /dev/null differ diff --git a/phonelibs/zmq/arm/lib/libzmq.so b/phonelibs/zmq/arm/lib/libzmq.so deleted file mode 100755 index 27ec72d7bc..0000000000 Binary files a/phonelibs/zmq/arm/lib/libzmq.so and /dev/null differ diff --git a/phonelibs/zmq/build.sh b/phonelibs/zmq/build.sh deleted file mode 100755 index 8c4d9a50f1..0000000000 --- a/phonelibs/zmq/build.sh +++ /dev/null @@ -1,60 +0,0 @@ -#!/bin/sh -set -e - -# aarch64 is actually built natively and copied in... - -SED=gsed - -git clone --depth 1 -b v4.2.2 git://github.com/zeromq/libzmq.git libzmq -git clone --depth 1 -b v4.0.2 git://github.com/zeromq/czmq.git czmq - -$SED -i 's/defined .HAVE_GETIFADDRS./0/' czmq/src/ziflist.c - -LIBZMQ_ROOT=$HOME/one/phonelibs/zmq/libzmq - -export ANDROID_NDK_ROOT=/opt/android-ndk - -export ANDROID_BUILD_EXTRA_CFLAGS='-std=gnu99 -O2' -export ANDROID_BUILD_EXTRA_CXXFLAGS='-O2' - -######## arm - -export TOOLCHAIN_PATH=${ANDROID_NDK_ROOT}/toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86_64/bin -export TOOLCHAIN_NAME=arm-linux-androideabi-4.9 -export TOOLCHAIN_HOST=arm-linux-androideabi -export TOOLCHAIN_ARCH=arm -cd czmq/builds/android -./build.sh -cd ../../../ -cp czmq/builds/android/prefix/arm-linux-androideabi-4.9/lib/libczmq.a \ - czmq/builds/android/prefix/arm-linux-androideabi-4.9/lib/libczmq.so \ - czmq/builds/android/prefix/arm-linux-androideabi-4.9/lib/libzmq.a \ - czmq/builds/android/prefix/arm-linux-androideabi-4.9/lib/libzmq.so ./arm/lib/ -cp czmq/builds/android/prefix/arm-linux-androideabi-4.9/include/*.h ./arm/include/ - - -######## aarch64 - -(cd libzmq && patch -p0 <../build_aarch64.patch) -(cd czmq && patch -p0 <../build_aarch64.patch) - -# android-9 lacks aarch64. -$SED -i 's/android-9/android-24/' *zmq/builds/android/android_build_helper.sh -# For some reason gcc doesn't work for aarch64, but g++ does. -$SED -i 's/-lgnustl_shared/-l:libgnustl_static.a/' *zmq/builds/android/android_build_helper.sh - -export TOOLCHAIN_PATH=${ANDROID_NDK_ROOT}/toolchains/aarch64-linux-android-4.9/prebuilt/darwin-x86_64/bin -export TOOLCHAIN_NAME=aarch64-linux-android-4.9 -export TOOLCHAIN_HOST=aarch64-linux-android -export TOOLCHAIN_ARCH=arm64 -cd czmq/builds/android -./build.sh -cd ../../../ -cp czmq/builds/android/prefix/aarch64-linux-android-4.9/lib/libczmq.a \ - czmq/builds/android/prefix/aarch64-linux-android-4.9/lib/libczmq.so \ - czmq/builds/android/prefix/aarch64-linux-android-4.9/lib/libzmq.a \ - czmq/builds/android/prefix/aarch64-linux-android-4.9/lib/libzmq.so ./aarch64/lib/ -cp czmq/builds/android/prefix/aarch64-linux-android-4.9/include/*.h ./aarch64/include/ - -# rm -rf czmq -echo SUCCESS diff --git a/phonelibs/zmq/build_aarch64.patch b/phonelibs/zmq/build_aarch64.patch deleted file mode 100644 index d689b99c51..0000000000 --- a/phonelibs/zmq/build_aarch64.patch +++ /dev/null @@ -1,15 +0,0 @@ -diff --git builds/android/android_build_helper.sh builds/android/android_build_helper.sh -index 6263f70..d0b24c3 100755 ---- builds/android/android_build_helper.sh -+++ builds/android/android_build_helper.sh -@@ -202,6 +202,10 @@ function _android_build_opts_process_cxx_stl { - LDFLAGS+=" -L${ANDROID_NDK_ROOT}/sources/cxx-stl/gnu-libstdc++/4.9/libs/mips" - CPPFLAGS+=" -I${ANDROID_NDK_ROOT}/sources/cxx-stl/gnu-libstdc++/4.9/libs/mips/include" - ;; -+ arm64) -+ LDFLAGS+=" -L${ANDROID_NDK_ROOT}/sources/cxx-stl/gnu-libstdc++/4.9/libs/arm64-v8a" -+ CPPFLAGS+=" -I${ANDROID_NDK_ROOT}/sources/cxx-stl/gnu-libstdc++/4.9/libs/arm64-v8a/include" -+ ;; - *) - ANDROID_BUILD_FAIL+=("Unknown combination for ANDROID_BUILD_CXXSTL and TOOLCHAIN_ARCH") - ANDROID_BUILD_FAIL+=(" ${ANDROID_BUILD_CXXSTL}") diff --git a/phonelibs/zmq/build_linux.txt b/phonelibs/zmq/build_linux.txt deleted file mode 100644 index 54e3b2a340..0000000000 --- a/phonelibs/zmq/build_linux.txt +++ /dev/null @@ -1,7 +0,0 @@ -https://github.com/zeromq/libzmq/releases/download/v4.2.2/zeromq-4.2.2.tar.gz -./configure --prefix="this_thingy" -make -j4 -make install - -czmq -see ~/one/external/zmq/build_czmq.sh diff --git a/phonelibs/zmq/mac/lib/libczmq.a b/phonelibs/zmq/mac/lib/libczmq.a deleted file mode 100644 index 061f2afabd..0000000000 Binary files a/phonelibs/zmq/mac/lib/libczmq.a and /dev/null differ diff --git a/phonelibs/zmq/mac/lib/libczmq.dylib b/phonelibs/zmq/mac/lib/libczmq.dylib deleted file mode 100644 index 50d2167e9c..0000000000 Binary files a/phonelibs/zmq/mac/lib/libczmq.dylib and /dev/null differ diff --git a/phonelibs/zmq/mac/lib/libzmq.a b/phonelibs/zmq/mac/lib/libzmq.a deleted file mode 100644 index 3365d42e87..0000000000 Binary files a/phonelibs/zmq/mac/lib/libzmq.a and /dev/null differ diff --git a/phonelibs/zmq/mac/lib/libzmq.dylib b/phonelibs/zmq/mac/lib/libzmq.dylib deleted file mode 100755 index 19b7514960..0000000000 Binary files a/phonelibs/zmq/mac/lib/libzmq.dylib and /dev/null differ diff --git a/requirements_openpilot.txt b/requirements_openpilot.txt deleted file mode 100644 index a36aa048eb..0000000000 --- a/requirements_openpilot.txt +++ /dev/null @@ -1,73 +0,0 @@ -# This are the packages installed on the EON --e git+https://github.com/commaai/le_python.git@5eef8f5be5929d33973e1b10e686fa0cdcd6792f#egg=Logentries --e git+https://github.com/commaai/python-overpy.git@f86529af402d4642e1faeb146671c40284007323#egg=overpy -Cython==0.27.3 -Flask==1.0.2 -#PyGObject==3.28.2 This is installed on the EON, but requires a ton of dependencies to install -PyJWT==1.4.1 -PyYAML==3.12 -appdirs==1.4.0 -atomicwrites==1.1.5 -attrs==16.0.0 -bitstring==3.1.5 -capnpy==0.4.2 -certifi==2016.8.31 -cffi==1.11.5 -contextlib2==0.5.4 -crc16==0.1.1 -crcmod==1.7 -cryptography==1.4 -cycler==0.10.0 -decorator==4.0.10 -docopt==0.6.2 -enum34==1.1.6 -evdev==0.6.1 -fastcluster==1.1.20 -filterpy==1.2.4 -hexdump==3.3 -ipaddress==1.0.16 -json-rpc==1.12.1 -libusb1==1.5.0 -lmdb==0.92 -mpmath==1.0.0 -nose==1.3.7 -numpy==1.11.1 -opencv-python==3.4.0.12 -pause==0.1.2 -psutil==3.4.2 -py==1.4.31 -pyOpenSSL==16.0.0 -pyasn1-modules==0.0.8 -pyasn1==0.1.9 -pycapnp==0.6.3 -pycparser==2.18 -pycrypto==2.6.1 -pyflakes==1.6.0 -pylint==1.8.3 -pyopencl==2016.1 -pyparsing==2.1.10 -#pypcap==1.1.5 needs extra dependencies and is not used -pyproj==1.9.5.1 -pypytools==0.4.3 -pyserial==3.1.1 -pytest==2.9.2 -python-dateutil==2.6.0 -pytools==2016.2.1 -pytz==2016.10 -pyyaml==3.12 -pyzmq==15.4.0 -raven==5.23.0 -recordclass==0.4.1 -requests==2.10.0 -scipy==0.19.1 -service-identity==16.0.0 -setproctitle==1.1.10 -simplejson==3.8.2 -six==1.10.0 -smbus-cffi==0.5.1 -smbus2==0.2.0 -sympy==1.1.1 -tqdm==4.23.1 -ujson==1.35 -v4l2==0.2 -websocket_client==0.55.0 diff --git a/selfdrive/athena/athenad.py b/selfdrive/athena/athenad.py index 2671672c52..58918de81a 100755 --- a/selfdrive/athena/athenad.py +++ b/selfdrive/athena/athenad.py @@ -65,10 +65,9 @@ def jsonrpc_handler(end_event): # TODO: add service to, for example, start visiond and take a picture @dispatcher.add_method def getMessage(service=None, timeout=1000): - context = zmq.Context() if service is None or service not in service_list: raise Exception("invalid service") - socket = messaging.sub_sock(context, service_list[service].port) + socket = messaging.sub_sock(service_list[service].port) socket.setsockopt(zmq.RCVTIMEO, timeout) ret = messaging.recv_one(socket) return ret.to_dict() diff --git a/selfdrive/boardd/Makefile b/selfdrive/boardd/Makefile index 18d0571093..c6b5f21910 100644 --- a/selfdrive/boardd/Makefile +++ b/selfdrive/boardd/Makefile @@ -16,14 +16,11 @@ WARN_FLAGS = -Werror=implicit-function-declaration \ CFLAGS = -std=gnu11 -g -fPIC -I../ -I../../ -O2 $(WARN_FLAGS) CXXFLAGS = -std=c++11 -g -fPIC -I../ -I../../ -O2 $(WARN_FLAGS) -ZMQ_FLAGS = -I$(PHONELIBS)/zmq/aarch64/include -ZMQ_LIBS = -L$(PHONELIBS)/zmq/aarch64/lib \ - -l:libczmq.a -l:libzmq.a \ - -lgnustl_shared +ZMQ_LIBS = -l:libczmq.a -l:libzmq.a -lgnustl_shared JSON_FLAGS = -I$(PHONELIBS)/json/src -EXTRA_LIBS = -lusb +EXTRA_LIBS = -lusb-1.0 # ifeq ($(OS),GNU/Linux) # # for Drive PX2 @@ -31,8 +28,14 @@ EXTRA_LIBS = -lusb # CEREAL_LIBS = -lcapnp -lkj -lcapnp_c # EXTRA_LIBS = -lusb-1.0 -lpthread # endif +ifeq ($(ARCH),aarch64) +CFLAGS += -mcpu=cortex-a57 +CXXFLAGS += -mcpu=cortex-a57 +endif + ifeq ($(ARCH),x86_64) +ZMQ_FLAGS = -I$(PHONELIBS)/zmq/aarch64/include ZMQ_LIBS = -L$(BASEDIR)/external/zmq/lib/ \ -l:libczmq.a -l:libzmq.a EXTRA_LIBS = -lusb-1.0 -lpthread @@ -75,7 +78,7 @@ boardd.o: boardd.cc boardd_api_impl.so: libcan_list_to_can_capnp.a boardd_api_impl.pyx boardd_setup.py - python boardd_setup.py build_ext --inplace + python2 boardd_setup.py build_ext --inplace rm -rf build rm -f boardd_api_impl.cpp diff --git a/selfdrive/boardd/boardd.cc b/selfdrive/boardd/boardd.cc index 3ee867083f..1a64416e9f 100644 --- a/selfdrive/boardd/boardd.cc +++ b/selfdrive/boardd/boardd.cc @@ -15,7 +15,7 @@ #include #include -#include +#include #include #include "cereal/gen/cpp/log.capnp.h" @@ -96,37 +96,37 @@ void *safety_setter_thread(void *s) { int safety_setting = 0; switch (safety_model) { - case (int)cereal::CarParams::SafetyModels::NO_OUTPUT: + case cereal::CarParams::SafetyModel::NO_OUTPUT: safety_setting = SAFETY_NOOUTPUT; break; - case (int)cereal::CarParams::SafetyModels::HONDA: + case cereal::CarParams::SafetyModel::HONDA: safety_setting = SAFETY_HONDA; break; - case (int)cereal::CarParams::SafetyModels::TOYOTA: + case cereal::CarParams::SafetyModel::TOYOTA: safety_setting = SAFETY_TOYOTA; break; - case (int)cereal::CarParams::SafetyModels::ELM327: + case cereal::CarParams::SafetyModel::ELM327: safety_setting = SAFETY_ELM327; break; - case (int)cereal::CarParams::SafetyModels::GM: + case cereal::CarParams::SafetyModel::GM: safety_setting = SAFETY_GM; break; - case (int)cereal::CarParams::SafetyModels::HONDA_BOSCH: + case cereal::CarParams::SafetyModel::HONDA_BOSCH: safety_setting = SAFETY_HONDA_BOSCH; break; - case (int)cereal::CarParams::SafetyModels::FORD: + case cereal::CarParams::SafetyModel::FORD: safety_setting = SAFETY_FORD; break; - case (int)cereal::CarParams::SafetyModels::CADILLAC: + case cereal::CarParams::SafetyModel::CADILLAC: safety_setting = SAFETY_CADILLAC; break; - case (int)cereal::CarParams::SafetyModels::HYUNDAI: + case cereal::CarParams::SafetyModel::HYUNDAI: safety_setting = SAFETY_HYUNDAI; break; - case (int)cereal::CarParams::SafetyModels::CHRYSLER: + case cereal::CarParams::SafetyModel::CHRYSLER: safety_setting = SAFETY_CHRYSLER; break; - case (int)cereal::CarParams::SafetyModels::SUBARU: + case cereal::CarParams::SafetyModel::SUBARU: safety_setting = SAFETY_SUBARU; break; default: diff --git a/selfdrive/boardd/boardd_api_impl.pyx b/selfdrive/boardd/boardd_api_impl.pyx index 75aa1081c3..eddf1fbf7a 100644 --- a/selfdrive/boardd/boardd_api_impl.pyx +++ b/selfdrive/boardd/boardd_api_impl.pyx @@ -9,9 +9,9 @@ cdef struct can_frame: long busTime long src -cdef extern void can_list_to_can_capnp_cpp(const vector[can_frame] &can_list, string &out, bool sendCan) +cdef extern void can_list_to_can_capnp_cpp(const vector[can_frame] &can_list, string &out, bool sendCan, bool valid) -def can_list_to_can_capnp(can_msgs, msgtype='can'): +def can_list_to_can_capnp(can_msgs, msgtype='can', valid=True): cdef vector[can_frame] can_list cdef can_frame f for can_msg in can_msgs: @@ -21,5 +21,5 @@ def can_list_to_can_capnp(can_msgs, msgtype='can'): f.src = can_msg[3] can_list.push_back(f) cdef string out - can_list_to_can_capnp_cpp(can_list, out, msgtype == 'sendcan') + can_list_to_can_capnp_cpp(can_list, out, msgtype == 'sendcan', valid) return out diff --git a/selfdrive/boardd/can_list_to_can_capnp.cc b/selfdrive/boardd/can_list_to_can_capnp.cc index 3850474100..8ba9d3d560 100644 --- a/selfdrive/boardd/can_list_to_can_capnp.cc +++ b/selfdrive/boardd/can_list_to_can_capnp.cc @@ -15,10 +15,11 @@ typedef struct { extern "C" { -void can_list_to_can_capnp_cpp(const std::vector &can_list, std::string &out, bool sendCan) { +void can_list_to_can_capnp_cpp(const std::vector &can_list, std::string &out, bool sendCan, bool valid) { capnp::MallocMessageBuilder msg; cereal::Event::Builder event = msg.initRoot(); event.setLogMonoTime(nanos_since_boot()); + event.setValid(valid); auto canData = sendCan ? event.initSendcan(can_list.size()) : event.initCan(can_list.size()); int j = 0; diff --git a/selfdrive/boardd/tests/boardd_old.py b/selfdrive/boardd/tests/boardd_old.py index 9ce5f7f3e1..5989e62746 100755 --- a/selfdrive/boardd/tests/boardd_old.py +++ b/selfdrive/boardd/tests/boardd_old.py @@ -8,7 +8,6 @@ import os import struct -import zmq import time import selfdrive.messaging as messaging @@ -113,12 +112,11 @@ def can_init(): cloudlog.info("can init done") def boardd_mock_loop(): - context = zmq.Context() can_init() handle.controlWrite(0x40, 0xdc, SAFETY_ALLOUTPUT, 0, b'') - logcan = messaging.sub_sock(context, service_list['can'].port) - sendcan = messaging.pub_sock(context, service_list['sendcan'].port) + logcan = messaging.sub_sock(service_list['can'].port) + sendcan = messaging.pub_sock(service_list['sendcan'].port) while 1: tsc = messaging.drain_sock(logcan, wait_for_one=True) @@ -126,12 +124,19 @@ def boardd_mock_loop(): snd = [] for s in snds: snd += s - snd = filter(lambda x: x[-1] <= 1, snd) + snd = filter(lambda x: x[-1] <= 2, snd) + snd_0 = len(filter(lambda x: x[-1] == 0, snd)) + snd_1 = len(filter(lambda x: x[-1] == 1, snd)) + snd_2 = len(filter(lambda x: x[-1] == 2, snd)) can_send_many(snd) # recv @ 100hz can_msgs = can_recv() - print("sent %d got %d" % (len(snd), len(can_msgs))) + got_0 = len(filter(lambda x: x[-1] == 0+0x80, can_msgs)) + got_1 = len(filter(lambda x: x[-1] == 1+0x80, can_msgs)) + got_2 = len(filter(lambda x: x[-1] == 2+0x80, can_msgs)) + print("sent %3d (%3d/%3d/%3d) got %3d (%3d/%3d/%3d)" % + (len(snd), snd_0, snd_1, snd_2, len(can_msgs), got_0, got_1, got_2)) m = can_list_to_can_capnp(can_msgs, msgtype='sendcan') sendcan.send(m.to_bytes()) @@ -151,16 +156,15 @@ def boardd_test_loop(): # *** main loop *** def boardd_loop(rate=200): rk = Ratekeeper(rate) - context = zmq.Context() can_init() # *** publishes can and health - logcan = messaging.pub_sock(context, service_list['can'].port) - health_sock = messaging.pub_sock(context, service_list['health'].port) + logcan = messaging.pub_sock(service_list['can'].port) + health_sock = messaging.pub_sock(service_list['health'].port) # *** subscribes to can send - sendcan = messaging.sub_sock(context, service_list['sendcan'].port) + sendcan = messaging.sub_sock(service_list['sendcan'].port) # drain sendcan to delete any stale messages from previous runs messaging.drain_sock(sendcan) @@ -199,14 +203,13 @@ def boardd_loop(rate=200): # *** main loop *** def boardd_proxy_loop(rate=200, address="192.168.2.251"): rk = Ratekeeper(rate) - context = zmq.Context() can_init() # *** subscribes can - logcan = messaging.sub_sock(context, service_list['can'].port, addr=address) + logcan = messaging.sub_sock(service_list['can'].port, addr=address) # *** publishes to can send - sendcan = messaging.pub_sock(context, service_list['sendcan'].port) + sendcan = messaging.pub_sock(service_list['sendcan'].port) # drain sendcan to delete any stale messages from previous runs messaging.drain_sock(sendcan) diff --git a/selfdrive/boardd/tests/replay_many.py b/selfdrive/boardd/tests/replay_many.py new file mode 100755 index 0000000000..710cfee486 --- /dev/null +++ b/selfdrive/boardd/tests/replay_many.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +import sys +import time +import signal +from panda import Panda +from multiprocessing import Pool + +import selfdrive.messaging as messaging +from selfdrive.services import service_list +from selfdrive.boardd.boardd import can_capnp_to_can_list + +def initializer(): + """Ignore CTRL+C in the worker process. + source: https://stackoverflow.com/a/44869451 """ + signal.signal(signal.SIGINT, signal.SIG_IGN) + +def send_thread(serial): + panda = Panda(serial) + panda.set_safety_mode(Panda.SAFETY_ALLOUTPUT) + panda.set_can_loopback(False) + + can_sock = messaging.sub_sock(service_list['can'].port) + + while True: + # Send messages one bus 0 and 1 + tsc = messaging.recv_one(can_sock) + snd = can_capnp_to_can_list(tsc.can) + snd = filter(lambda x: x[-1] <= 2, snd) + panda.can_send_many(snd) + + # Drain panda message buffer + panda.can_recv() + + +if __name__ == "__main__": + serials = Panda.list() + num_pandas = len(serials) + + if num_pandas == 0: + print("No pandas found. Exiting") + sys.exit(1) + else: + print("%d pandas found. Starting broadcast" % num_pandas) + + pool = Pool(num_pandas, initializer=initializer) + pool.map_async(send_thread, serials) + + while True: + try: + time.sleep(10) + except KeyboardInterrupt: + pool.terminate() + pool.join() + raise diff --git a/selfdrive/boardd/tests/test_boardd_loopback.py b/selfdrive/boardd/tests/test_boardd_loopback.py index 1b6f1b1387..042a5783a5 100755 --- a/selfdrive/boardd/tests/test_boardd_loopback.py +++ b/selfdrive/boardd/tests/test_boardd_loopback.py @@ -3,7 +3,6 @@ import os import random -import zmq import time from selfdrive.boardd.boardd import can_list_to_can_capnp @@ -16,10 +15,8 @@ def get_test_string(): BUS = 0 def main(): - context = zmq.Context() - - rcv = sub_sock(context, service_list['can'].port) # port 8006 - snd = pub_sock(context, service_list['sendcan'].port) # port 8017 + rcv = sub_sock(service_list['can'].port) # port 8006 + snd = pub_sock(service_list['sendcan'].port) # port 8017 time.sleep(0.3) # wait to bind before send/recv for i in range(10): diff --git a/selfdrive/can/Makefile b/selfdrive/can/Makefile index 918c445288..e53a0730de 100644 --- a/selfdrive/can/Makefile +++ b/selfdrive/can/Makefile @@ -18,6 +18,11 @@ CFLAGS = -std=gnu11 -g -fPIC -O2 $(WARN_FLAGS) CXXFLAGS = -std=c++11 -g -fPIC -O2 $(WARN_FLAGS) LDFLAGS = +ifeq ($(ARCH),aarch64) +CFLAGS += -mcpu=cortex-a57 +CXXFLAGS += -mcpu=cortex-a57 +endif + ifeq ($(UNAME_S),Darwin) ZMQ_LIBS = -L/usr/local/lib -lzmq else ifeq ($(OPTEST),1) @@ -26,14 +31,12 @@ else ifeq ($(UNAME_M),x86_64) ZMQ_FLAGS = -I$(PHONELIBS)/zmq/x64/include ZMQ_LIBS = -L$(PHONELIBS)/zmq/x64/lib -l:libzmq.a else ifeq ($(UNAME_M),aarch64) - ZMQ_FLAGS = -I$(PHONELIBS)/zmq/aarch64/include - ZMQ_LIBS = -L$(PHONELIBS)/zmq/aarch64/lib -l:libzmq.a - LDFLAGS += -lgnustl_shared + ZMQ_LIBS = -l:libzmq.a -lgnustl_shared endif OBJDIR = obj -OPENDBC_PATH := $(shell python -c 'import opendbc; print opendbc.DBC_PATH') +OPENDBC_PATH := $(shell python2 -c 'import opendbc; print opendbc.DBC_PATH') DBC_SOURCES := $(wildcard $(OPENDBC_PATH)/*.dbc) DBC_OBJS := $(patsubst $(OPENDBC_PATH)/%.dbc,$(OBJDIR)/%.o,$(DBC_SOURCES)) @@ -45,7 +48,7 @@ LIBDBC_OBJS := $(OBJDIR)/dbc.o $(OBJDIR)/parser.o $(OBJDIR)/packer.o CWD := $(shell pwd) .PHONY: all -all: $(OBJDIR) libdbc.so +all: $(OBJDIR) libdbc.so parser_pyx.so include ../common/cereal.mk @@ -67,10 +70,15 @@ libdbc.so:: $(LIBDBC_OBJS) $(DBC_OBJS) $(CEREAL_LIBS) packer_impl.so: packer_impl.pyx packer_setup.py - python packer_setup.py build_ext --inplace + python2 packer_setup.py build_ext --inplace rm -rf build rm -f packer_impl.cpp +parser_pyx.so: parser_pyx_setup.py parser_pyx.pyx parser_pyx.pxd + python $< build_ext --inplace + rm -rf build + rm -f parser_pyx.cpp + $(OBJDIR)/%.o: %.cc @echo "[ CXX ] $@" $(CXX) -fPIC -c -o '$@' $^ \ @@ -90,7 +98,7 @@ $(OBJDIR)/%.o: dbc_out/%.cc dbc_out/%.cc: process_dbc.py dbc_template.cc $(OPENDBC_PATH)/%.dbc @echo "[ DBC GEN ] $@" @echo "Missing prereq $?" - PYTHONPATH=$(PYTHONPATH):$(CWD)/../../pyextra ./process_dbc.py $(OPENDBC_PATH) dbc_out + ./process_dbc.py $(OPENDBC_PATH) dbc_out $(OBJDIR): mkdir -p $@ diff --git a/selfdrive/can/can_define.py b/selfdrive/can/can_define.py new file mode 100644 index 0000000000..48ff8798fd --- /dev/null +++ b/selfdrive/can/can_define.py @@ -0,0 +1,39 @@ +from collections import defaultdict +from selfdrive.can.libdbc_py import libdbc, ffi + +class CANDefine(object): + def __init__(self, dbc_name): + self.dv = defaultdict(dict) + self.dbc_name = dbc_name + self.dbc = libdbc.dbc_lookup(dbc_name) + + num_vals = self.dbc[0].num_vals + + self.address_to_msg_name = {} + num_msgs = self.dbc[0].num_msgs + for i in range(num_msgs): + msg = self.dbc[0].msgs[i] + name = ffi.string(msg.name) + address = msg.address + self.address_to_msg_name[address] = name + + for i in range(num_vals): + val = self.dbc[0].vals[i] + + sgname = ffi.string(val.name) + address = val.address + def_val = ffi.string(val.def_val) + + #separate definition/value pairs + def_val = def_val.split() + values = [int(v) for v in def_val[::2]] + defs = def_val[1::2] + + if address not in self.dv: + self.dv[address] = {} + msgname = self.address_to_msg_name[address] + self.dv[msgname] = {} + + # two ways to lookup: address or msg name + self.dv[address][sgname] = {v: d for v, d in zip(values, defs)} #build dict + self.dv[msgname][sgname] = self.dv[address][sgname] diff --git a/selfdrive/can/parser.cc b/selfdrive/can/parser.cc index eb828cd8ee..e3225181ba 100644 --- a/selfdrive/can/parser.cc +++ b/selfdrive/can/parser.cc @@ -416,6 +416,17 @@ void* can_init(int bus, const char* dbc_name, return (void*)ret; } +void* can_init_with_vectors(int bus, const char* dbc_name, + std::vector message_options, + std::vector signal_options, + bool sendcan, const char* tcp_addr, int timeout) { + CANParser* ret = new CANParser(bus, std::string(dbc_name), + message_options, + signal_options, + sendcan, std::string(tcp_addr), timeout); + return (void*)ret; +} + int can_update(void* can, uint64_t sec, bool wait) { CANParser* cp = (CANParser*)can; return cp->update(sec, wait); @@ -435,6 +446,14 @@ size_t can_query(void* can, uint64_t sec, bool *out_can_valid, size_t out_values return values.size(); }; +void can_query_vector(void* can, uint64_t sec, bool *out_can_valid, std::vector &values) { + CANParser* cp = (CANParser*)can; + if (out_can_valid) { + *out_can_valid = cp->can_valid; + } + values = cp->query(sec); +}; + } #ifdef TEST diff --git a/selfdrive/can/parser.py b/selfdrive/can/parser.py index 31af2df04e..b8b2061dc9 100644 --- a/selfdrive/can/parser.py +++ b/selfdrive/can/parser.py @@ -1,252 +1,9 @@ -import time -from collections import defaultdict -import numbers +import os +import subprocess -from selfdrive.can.libdbc_py import libdbc, ffi +can_dir = os.path.dirname(os.path.abspath(__file__)) +libdbc_fn = os.path.join(can_dir, "libdbc.so") +subprocess.check_call(["make"], cwd=can_dir) - -class CANParser(object): - def __init__(self, dbc_name, signals, checks=None, bus=0, sendcan=False, tcp_addr="127.0.0.1", timeout=-1): - if checks is None: - checks = [] - - self.can_valid = True - self.vl = defaultdict(dict) - self.ts = defaultdict(dict) - - self.dbc_name = dbc_name - self.dbc = libdbc.dbc_lookup(dbc_name) - self.msg_name_to_addres = {} - self.address_to_msg_name = {} - - num_msgs = self.dbc[0].num_msgs - for i in range(num_msgs): - msg = self.dbc[0].msgs[i] - - name = ffi.string(msg.name) - address = msg.address - - self.msg_name_to_addres[name] = address - self.address_to_msg_name[address] = name - - # Convert message names into addresses - for i in range(len(signals)): - s = signals[i] - if not isinstance(s[1], numbers.Number): - s = (s[0], self.msg_name_to_addres[s[1]], s[2]) - signals[i] = s - - for i in range(len(checks)): - c = checks[i] - if not isinstance(c[0], numbers.Number): - c = (self.msg_name_to_addres[c[0]], c[1]) - checks[i] = c - - sig_names = dict((name, ffi.new("char[]", name)) for name, _, _ in signals) - - signal_options_c = ffi.new("SignalParseOptions[]", [ - { - 'address': sig_address, - 'name': sig_names[sig_name], - 'default_value': sig_default, - } for sig_name, sig_address, sig_default in signals]) - - message_options = dict((address, 0) for _, address, _ in signals) - message_options.update(dict(checks)) - - message_options_c = ffi.new("MessageParseOptions[]", [ - { - 'address': msg_address, - 'check_frequency': freq, - } for msg_address, freq in message_options.items()]) - - self.can = libdbc.can_init(bus, dbc_name, len(message_options_c), message_options_c, - len(signal_options_c), signal_options_c, sendcan, tcp_addr, timeout) - - self.p_can_valid = ffi.new("bool*") - - value_count = libdbc.can_query(self.can, 0, self.p_can_valid, 0, ffi.NULL) - self.can_values = ffi.new("SignalValue[%d]" % value_count) - self.update_vl(0) - # print("===") - - def update_vl(self, sec): - - can_values_len = libdbc.can_query(self.can, sec, self.p_can_valid, len(self.can_values), self.can_values) - assert can_values_len <= len(self.can_values) - - self.can_valid = self.p_can_valid[0] - - # print(can_values_len) - ret = set() - for i in xrange(can_values_len): - cv = self.can_values[i] - address = cv.address - # print("{0} {1}".format(hex(cv.address), ffi.string(cv.name))) - name = ffi.string(cv.name) - self.vl[address][name] = cv.value - self.ts[address][name] = cv.ts - - sig_name = self.address_to_msg_name[address] - self.vl[sig_name][name] = cv.value - self.ts[sig_name][name] = cv.ts - ret.add(address) - return ret - - def update(self, sec, wait): - """Returns if the update was successfull (e.g. no rcv timeout happened)""" - r = libdbc.can_update(self.can, sec, wait) - return bool(r >= 0), self.update_vl(sec) - - -class CANDefine(object): - def __init__(self, dbc_name): - self.dv = defaultdict(dict) - self.dbc_name = dbc_name - self.dbc = libdbc.dbc_lookup(dbc_name) - - num_vals = self.dbc[0].num_vals - - self.address_to_msg_name = {} - num_msgs = self.dbc[0].num_msgs - for i in range(num_msgs): - msg = self.dbc[0].msgs[i] - name = ffi.string(msg.name) - address = msg.address - self.address_to_msg_name[address] = name - - for i in range(num_vals): - val = self.dbc[0].vals[i] - - sgname = ffi.string(val.name) - address = val.address - def_val = ffi.string(val.def_val) - - #separate definition/value pairs - def_val = def_val.split() - values = [int(v) for v in def_val[::2]] - defs = def_val[1::2] - - if address not in self.dv: - self.dv[address] = {} - msgname = self.address_to_msg_name[address] - self.dv[msgname] = {} - - # two ways to lookup: address or msg name - self.dv[address][sgname] = {v: d for v, d in zip(values, defs)} #build dict - self.dv[msgname][sgname] = self.dv[address][sgname] - - -if __name__ == "__main__": - from common.realtime import sec_since_boot - - radar_messages = range(0x430, 0x43A) + range(0x440, 0x446) - # signals = zip(['LONG_DIST'] * 16 + ['NEW_TRACK'] * 16 + ['LAT_DIST'] * 16 + - # ['REL_SPEED'] * 16, radar_messages * 4, - # [255] * 16 + [1] * 16 + [0] * 16 + [0] * 16) - # checks = zip(radar_messages, [20]*16) - - # cp = CANParser("acura_ilx_2016_nidec", signals, checks, 1) - - - # signals = [ - # ("XMISSION_SPEED", 0x158, 0), #sig_name, sig_address, default - # ("WHEEL_SPEED_FL", 0x1d0, 0), - # ("WHEEL_SPEED_FR", 0x1d0, 0), - # ("WHEEL_SPEED_RL", 0x1d0, 0), - # ("STEER_ANGLE", 0x14a, 0), - # ("STEER_TORQUE_SENSOR", 0x18f, 0), - # ("GEAR", 0x191, 0), - # ("WHEELS_MOVING", 0x1b0, 1), - # ("DOOR_OPEN_FL", 0x405, 1), - # ("DOOR_OPEN_FR", 0x405, 1), - # ("DOOR_OPEN_RL", 0x405, 1), - # ("DOOR_OPEN_RR", 0x405, 1), - # ("CRUISE_SPEED_PCM", 0x324, 0), - # ("SEATBELT_DRIVER_LAMP", 0x305, 1), - # ("SEATBELT_DRIVER_LATCHED", 0x305, 0), - # ("BRAKE_PRESSED", 0x17c, 0), - # ("CAR_GAS", 0x130, 0), - # ("CRUISE_BUTTONS", 0x296, 0), - # ("ESP_DISABLED", 0x1a4, 1), - # ("HUD_LEAD", 0x30c, 0), - # ("USER_BRAKE", 0x1a4, 0), - # ("STEER_STATUS", 0x18f, 5), - # ("WHEEL_SPEED_RR", 0x1d0, 0), - # ("BRAKE_ERROR_1", 0x1b0, 1), - # ("BRAKE_ERROR_2", 0x1b0, 1), - # ("GEAR_SHIFTER", 0x191, 0), - # ("MAIN_ON", 0x326, 0), - # ("ACC_STATUS", 0x17c, 0), - # ("PEDAL_GAS", 0x17c, 0), - # ("CRUISE_SETTING", 0x296, 0), - # ("LEFT_BLINKER", 0x326, 0), - # ("RIGHT_BLINKER", 0x326, 0), - # ("COUNTER", 0x324, 0), - # ("ENGINE_RPM", 0x17C, 0) - # ] - # checks = [ - # (0x14a, 100), # address, frequency - # (0x158, 100), - # (0x17c, 100), - # (0x191, 100), - # (0x1a4, 50), - # (0x326, 10), - # (0x1b0, 50), - # (0x1d0, 50), - # (0x305, 10), - # (0x324, 10), - # (0x405, 3), - # ] - - # cp = CANParser("honda_civic_touring_2016_can_generated", signals, checks, 0) - - - signals = [ - # sig_name, sig_address, default - ("GEAR", 956, 0x20), - ("BRAKE_PRESSED", 548, 0), - ("GAS_PEDAL", 705, 0), - - ("WHEEL_SPEED_FL", 170, 0), - ("WHEEL_SPEED_FR", 170, 0), - ("WHEEL_SPEED_RL", 170, 0), - ("WHEEL_SPEED_RR", 170, 0), - ("DOOR_OPEN_FL", 1568, 1), - ("DOOR_OPEN_FR", 1568, 1), - ("DOOR_OPEN_RL", 1568, 1), - ("DOOR_OPEN_RR", 1568, 1), - ("SEATBELT_DRIVER_UNLATCHED", 1568, 1), - ("TC_DISABLED", 951, 1), - ("STEER_ANGLE", 37, 0), - ("STEER_FRACTION", 37, 0), - ("STEER_RATE", 37, 0), - ("GAS_RELEASED", 466, 0), - ("CRUISE_STATE", 466, 0), - ("MAIN_ON", 467, 0), - ("SET_SPEED", 467, 0), - ("STEER_TORQUE_DRIVER", 608, 0), - ("STEER_TORQUE_EPS", 608, 0), - ("TURN_SIGNALS", 1556, 3), # 3 is no blinkers - ("LKA_STATE", 610, 0), - ] - checks = [ - (548, 40), - (705, 33), - - (170, 80), - (37, 80), - (466, 33), - (608, 50), - ] - - cp = CANParser("toyota_rav4_2017_pt_generated", signals, checks, 0) - - # print(cp.vl) - - while True: - cp.update(int(sec_since_boot()*1e9), True) - # print(cp.vl) - print(cp.ts) - print(cp.can_valid) - time.sleep(0.01) +from selfdrive.can.parser_pyx import CANParser # pylint: disable=no-name-in-module, import-error +assert CANParser diff --git a/selfdrive/can/parser_pyx.pxd b/selfdrive/can/parser_pyx.pxd new file mode 100644 index 0000000000..9d8efa318c --- /dev/null +++ b/selfdrive/can/parser_pyx.pxd @@ -0,0 +1,92 @@ +# distutils: language = c++ +from libc.stdint cimport uint32_t, uint64_t, uint16_t +from libcpp.vector cimport vector +from libcpp.map cimport map +from libcpp.string cimport string +from libcpp.unordered_set cimport unordered_set +from libcpp cimport bool + +ctypedef enum SignalType: + DEFAULT, + HONDA_CHECKSUM, + HONDA_COUNTER, + TOYOTA_CHECKSUM, + PEDAL_CHECKSUM, + PEDAL_COUNTER + +cdef struct Signal: + const char* name + int b1, b2, bo + bool is_signed + double factor, offset + SignalType type + + + +cdef struct Msg: + const char* name + uint32_t address + unsigned int size + size_t num_sigs + const Signal *sigs + +cdef struct Val: + const char* name + uint32_t address + const char* def_val + const Signal *sigs + +cdef struct DBC: + const char* name + size_t num_msgs + const Msg *msgs + const Val *vals + size_t num_vals + +cdef struct SignalParseOptions: + uint32_t address + const char* name + double default_value + + +cdef struct MessageParseOptions: + uint32_t address + int check_frequency + +cdef struct SignalValue: + uint32_t address + uint16_t ts + const char* name + double value + +ctypedef const DBC * (*dbc_lookup_func)(const char* dbc_name) +ctypedef void* (*can_init_with_vectors_func)(int bus, const char* dbc_name, + vector[MessageParseOptions] message_options, + vector[SignalParseOptions] signal_options, + bool sendcan, + const char* tcp_addr, + int timeout) +ctypedef int (*can_update_func)(void* can, uint64_t sec, bool wait); +ctypedef size_t (*can_query_func)(void* can, uint64_t sec, bool *out_can_valid, size_t out_values_size, SignalValue* out_values); +ctypedef void (*can_query_vector_func)(void* can, uint64_t sec, bool *out_can_valid, vector[SignalValue] &values) + +cdef class CANParser: + cdef: + void *can + const DBC *dbc + dbc_lookup_func dbc_lookup + can_init_with_vectors_func can_init_with_vectors + can_update_func can_update + can_query_vector_func can_query_vector + map[string, uint32_t] msg_name_to_address + map[uint32_t, string] address_to_msg_name + vector[SignalValue] can_values + bool test_mode_enabled + cdef public: + string dbc_name + dict vl + dict ts + bool can_valid + int can_invalid_cnt + + cdef unordered_set[uint32_t] update_vl(self, uint64_t sec) diff --git a/selfdrive/can/parser_pyx.pyx b/selfdrive/can/parser_pyx.pyx new file mode 100644 index 0000000000..65c6f5ab21 --- /dev/null +++ b/selfdrive/can/parser_pyx.pyx @@ -0,0 +1,105 @@ +# distutils: language = c++ +from posix.dlfcn cimport dlopen, dlsym, RTLD_LAZY + +from libcpp cimport bool +import os +import numbers + +cdef int CAN_INVALID_CNT = 5 + +cdef class CANParser: + def __init__(self, dbc_name, signals, checks=None, bus=0, sendcan=False, tcp_addr="127.0.0.1", timeout=-1): + self.test_mode_enabled = False + can_dir = os.path.dirname(os.path.abspath(__file__)) + libdbc_fn = os.path.join(can_dir, "libdbc.so") + + cdef void *libdbc = dlopen(libdbc_fn, RTLD_LAZY) + self.can_init_with_vectors = dlsym(libdbc, 'can_init_with_vectors') + self.dbc_lookup = dlsym(libdbc, 'dbc_lookup') + self.can_update = dlsym(libdbc, 'can_update') + self.can_query_vector = dlsym(libdbc, 'can_query_vector') + if checks is None: + checks = [] + + self.can_valid = True + self.dbc_name = dbc_name + self.dbc = self.dbc_lookup(dbc_name) + self.vl = {} + self.ts = {} + + self.can_invalid_cnt = CAN_INVALID_CNT + + num_msgs = self.dbc[0].num_msgs + for i in range(num_msgs): + msg = self.dbc[0].msgs[i] + self.msg_name_to_address[string(msg.name)] = msg.address + self.address_to_msg_name[msg.address] = string(msg.name) + self.vl[msg.address] = {} + self.vl[str(msg.name)] = {} + self.ts[msg.address] = {} + self.ts[str(msg.name)] = {} + + # Convert message names into addresses + for i in range(len(signals)): + s = signals[i] + if not isinstance(s[1], numbers.Number): + s = (s[0], self.msg_name_to_address[s[1]], s[2]) + signals[i] = s + + for i in range(len(checks)): + c = checks[i] + if not isinstance(c[0], numbers.Number): + c = (self.msg_name_to_address[c[0]], c[1]) + checks[i] = c + + cdef vector[SignalParseOptions] signal_options_v + cdef SignalParseOptions spo + for sig_name, sig_address, sig_default in signals: + spo.address = sig_address + spo.name = sig_name + spo.default_value = sig_default + signal_options_v.push_back(spo) + + message_options = dict((address, 0) for _, address, _ in signals) + message_options.update(dict(checks)) + + cdef vector[MessageParseOptions] message_options_v + cdef MessageParseOptions mpo + for msg_address, freq in message_options.items(): + mpo.address = msg_address + mpo.check_frequency = freq + message_options_v.push_back(mpo) + + self.can = self.can_init_with_vectors(bus, dbc_name, message_options_v, signal_options_v, sendcan, tcp_addr, timeout) + self.update_vl(0) + + cdef unordered_set[uint32_t] update_vl(self, uint64_t sec): + cdef string sig_name + cdef unordered_set[uint32_t] updated_val + cdef bool valid = False + + self.can_query_vector(self.can, sec, &valid, self.can_values) + + # Update invalid flag + self.can_invalid_cnt += 1 + if valid: + self.can_invalid_cnt = 0 + self.can_valid = self.can_invalid_cnt < CAN_INVALID_CNT + + + for cv in self.can_values: + self.vl[cv.address][string(cv.name)] = cv.value + self.ts[cv.address][string(cv.name)] = cv.ts + + sig_name = self.address_to_msg_name[cv.address] + self.vl[sig_name][string(cv.name)] = cv.value + self.ts[sig_name][string(cv.name)] = cv.ts + + updated_val.insert(cv.address) + + return updated_val + + def update(self, uint64_t sec, bool wait): + r = (self.can_update(self.can, sec, wait) >= 0) + updated_val = self.update_vl(sec) + return r, updated_val diff --git a/selfdrive/can/parser_pyx_setup.py b/selfdrive/can/parser_pyx_setup.py new file mode 100644 index 0000000000..f20224f343 --- /dev/null +++ b/selfdrive/can/parser_pyx_setup.py @@ -0,0 +1,18 @@ +from distutils.core import setup, Extension +from Cython.Build import cythonize +import subprocess + +sourcefiles = ['parser_pyx.pyx'] +extra_compile_args = ["-std=c++11"] +ARCH = subprocess.check_output(["uname", "-m"]).rstrip() +if ARCH == "aarch64": + extra_compile_args += ["-Wno-deprecated-register"] + +setup(name='Radard Thread', + ext_modules=cythonize( + Extension( + "parser_pyx", + sources=sourcefiles, + extra_compile_args=extra_compile_args + ), + nthreads=4)) diff --git a/selfdrive/can/process_dbc.py b/selfdrive/can/process_dbc.py index 3f3f2ddcad..5f9237020b 100755 --- a/selfdrive/can/process_dbc.py +++ b/selfdrive/can/process_dbc.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2 import os import glob import sys diff --git a/selfdrive/can/tests/parser_old.py b/selfdrive/can/tests/parser_old.py new file mode 100644 index 0000000000..5a899efa50 --- /dev/null +++ b/selfdrive/can/tests/parser_old.py @@ -0,0 +1,220 @@ +import time +import numbers + +from selfdrive.can.libdbc_py import libdbc, ffi + +CAN_INVALID_CNT = 5 # after so many consecutive CAN data with wrong checksum, counter or frequency, flag CAN invalidity + +class CANParser(object): + def __init__(self, dbc_name, signals, checks=None, bus=0, sendcan=False, tcp_addr="127.0.0.1", timeout=-1): + if checks is None: + checks = [] + + self.can_valid = True + self.can_invalid_cnt = CAN_INVALID_CNT + self.vl = {} + self.ts = {} + + self.dbc_name = dbc_name + self.dbc = libdbc.dbc_lookup(dbc_name) + self.msg_name_to_addres = {} + self.address_to_msg_name = {} + + num_msgs = self.dbc[0].num_msgs + for i in range(num_msgs): + msg = self.dbc[0].msgs[i] + + name = ffi.string(msg.name) + address = msg.address + + self.msg_name_to_addres[name] = address + self.address_to_msg_name[address] = name + + self.vl[address] = {} + self.vl[name] = {} + self.ts[address] = {} + self.ts[name] = {} + + # Convert message names into addresses + for i in range(len(signals)): + s = signals[i] + if not isinstance(s[1], numbers.Number): + s = (s[0], self.msg_name_to_addres[s[1]], s[2]) + signals[i] = s + + for i in range(len(checks)): + c = checks[i] + if not isinstance(c[0], numbers.Number): + c = (self.msg_name_to_addres[c[0]], c[1]) + checks[i] = c + + sig_names = dict((name, ffi.new("char[]", name)) for name, _, _ in signals) + + signal_options_c = ffi.new("SignalParseOptions[]", [ + { + 'address': sig_address, + 'name': sig_names[sig_name], + 'default_value': sig_default, + } for sig_name, sig_address, sig_default in signals]) + + message_options = dict((address, 0) for _, address, _ in signals) + message_options.update(dict(checks)) + + message_options_c = ffi.new("MessageParseOptions[]", [ + { + 'address': msg_address, + 'check_frequency': freq, + } for msg_address, freq in message_options.items()]) + + self.can = libdbc.can_init(bus, dbc_name, len(message_options_c), message_options_c, + len(signal_options_c), signal_options_c, sendcan, tcp_addr, timeout) + + self.p_can_valid = ffi.new("bool*") + + value_count = libdbc.can_query(self.can, 0, self.p_can_valid, 0, ffi.NULL) + self.can_values = ffi.new("SignalValue[%d]" % value_count) + self.update_vl(0) + + def update_vl(self, sec): + can_values_len = libdbc.can_query(self.can, sec, self.p_can_valid, len(self.can_values), self.can_values) + assert can_values_len <= len(self.can_values) + + self.can_invalid_cnt += 1 + if self.p_can_valid[0]: + self.can_invalid_cnt = 0 + self.can_valid = self.can_invalid_cnt < CAN_INVALID_CNT + + ret = set() + for i in xrange(can_values_len): + cv = self.can_values[i] + address = cv.address + # print("{0} {1}".format(hex(cv.address), ffi.string(cv.name))) + name = ffi.string(cv.name) + self.vl[address][name] = cv.value + self.ts[address][name] = cv.ts + + sig_name = self.address_to_msg_name[address] + self.vl[sig_name][name] = cv.value + self.ts[sig_name][name] = cv.ts + ret.add(address) + return ret + + def update(self, sec, wait): + """Returns if the update was successfull (e.g. no rcv timeout happened)""" + r = libdbc.can_update(self.can, sec, wait) + return bool(r >= 0), self.update_vl(sec) + + +if __name__ == "__main__": + from common.realtime import sec_since_boot + + radar_messages = range(0x430, 0x43A) + range(0x440, 0x446) + # signals = zip(['LONG_DIST'] * 16 + ['NEW_TRACK'] * 16 + ['LAT_DIST'] * 16 + + # ['REL_SPEED'] * 16, radar_messages * 4, + # [255] * 16 + [1] * 16 + [0] * 16 + [0] * 16) + # checks = zip(radar_messages, [20]*16) + + # cp = CANParser("acura_ilx_2016_nidec", signals, checks, 1) + + + # signals = [ + # ("XMISSION_SPEED", 0x158, 0), #sig_name, sig_address, default + # ("WHEEL_SPEED_FL", 0x1d0, 0), + # ("WHEEL_SPEED_FR", 0x1d0, 0), + # ("WHEEL_SPEED_RL", 0x1d0, 0), + # ("STEER_ANGLE", 0x14a, 0), + # ("STEER_TORQUE_SENSOR", 0x18f, 0), + # ("GEAR", 0x191, 0), + # ("WHEELS_MOVING", 0x1b0, 1), + # ("DOOR_OPEN_FL", 0x405, 1), + # ("DOOR_OPEN_FR", 0x405, 1), + # ("DOOR_OPEN_RL", 0x405, 1), + # ("DOOR_OPEN_RR", 0x405, 1), + # ("CRUISE_SPEED_PCM", 0x324, 0), + # ("SEATBELT_DRIVER_LAMP", 0x305, 1), + # ("SEATBELT_DRIVER_LATCHED", 0x305, 0), + # ("BRAKE_PRESSED", 0x17c, 0), + # ("CAR_GAS", 0x130, 0), + # ("CRUISE_BUTTONS", 0x296, 0), + # ("ESP_DISABLED", 0x1a4, 1), + # ("HUD_LEAD", 0x30c, 0), + # ("USER_BRAKE", 0x1a4, 0), + # ("STEER_STATUS", 0x18f, 5), + # ("WHEEL_SPEED_RR", 0x1d0, 0), + # ("BRAKE_ERROR_1", 0x1b0, 1), + # ("BRAKE_ERROR_2", 0x1b0, 1), + # ("GEAR_SHIFTER", 0x191, 0), + # ("MAIN_ON", 0x326, 0), + # ("ACC_STATUS", 0x17c, 0), + # ("PEDAL_GAS", 0x17c, 0), + # ("CRUISE_SETTING", 0x296, 0), + # ("LEFT_BLINKER", 0x326, 0), + # ("RIGHT_BLINKER", 0x326, 0), + # ("COUNTER", 0x324, 0), + # ("ENGINE_RPM", 0x17C, 0) + # ] + # checks = [ + # (0x14a, 100), # address, frequency + # (0x158, 100), + # (0x17c, 100), + # (0x191, 100), + # (0x1a4, 50), + # (0x326, 10), + # (0x1b0, 50), + # (0x1d0, 50), + # (0x305, 10), + # (0x324, 10), + # (0x405, 3), + # ] + + # cp = CANParser("honda_civic_touring_2016_can_generated", signals, checks, 0) + + + signals = [ + # sig_name, sig_address, default + ("GEAR", 956, 0x20), + ("BRAKE_PRESSED", 548, 0), + ("GAS_PEDAL", 705, 0), + + ("WHEEL_SPEED_FL", 170, 0), + ("WHEEL_SPEED_FR", 170, 0), + ("WHEEL_SPEED_RL", 170, 0), + ("WHEEL_SPEED_RR", 170, 0), + ("DOOR_OPEN_FL", 1568, 1), + ("DOOR_OPEN_FR", 1568, 1), + ("DOOR_OPEN_RL", 1568, 1), + ("DOOR_OPEN_RR", 1568, 1), + ("SEATBELT_DRIVER_UNLATCHED", 1568, 1), + ("TC_DISABLED", 951, 1), + ("STEER_ANGLE", 37, 0), + ("STEER_FRACTION", 37, 0), + ("STEER_RATE", 37, 0), + ("GAS_RELEASED", 466, 0), + ("CRUISE_STATE", 466, 0), + ("MAIN_ON", 467, 0), + ("SET_SPEED", 467, 0), + ("STEER_TORQUE_DRIVER", 608, 0), + ("STEER_TORQUE_EPS", 608, 0), + ("TURN_SIGNALS", 1556, 3), # 3 is no blinkers + ("LKA_STATE", 610, 0), + ] + checks = [ + (548, 40), + (705, 33), + + (170, 80), + (37, 80), + (466, 33), + (608, 50), + ] + + cp = CANParser("toyota_rav4_2017_pt_generated", signals, checks, 0) + + # print(cp.vl) + + while True: + cp.update(int(sec_since_boot()*1e9), True) + # print(cp.vl) + print(cp.ts) + print(cp.can_valid) + time.sleep(0.01) diff --git a/selfdrive/can/tests/test_parser.py b/selfdrive/can/tests/test_parser.py new file mode 100755 index 0000000000..bb00d042fc --- /dev/null +++ b/selfdrive/can/tests/test_parser.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python2 + +import os +import unittest + +import requests + +import selfdrive.messaging as messaging +from selfdrive.can.parser import CANParser as CANParserNew +from selfdrive.can.tests.parser_old import CANParser as CANParserOld +from selfdrive.car.honda.carstate import get_can_signals +from selfdrive.car.honda.interface import CarInterface +from selfdrive.car.honda.values import CAR, DBC +from selfdrive.services import service_list +from tools.lib.logreader import LogReader + +BASE_URL = "https://commadataci.blob.core.windows.net/openpilotci/" +DT = int(0.01 * 1e9) # ns + + +def dict_keys_differ(dict1, dict2): + keys1 = set(dict1.keys()) + keys2 = set(dict2.keys()) + + if keys1 != keys2: + return True + + for k in keys1: + keys1 = set(dict1[k].keys()) + keys2 = set(dict2[k].keys()) + + if keys1 != keys2: + return True + + return False + +def dicts_vals_differ(dict1, dict2): + for k_outer in dict1.keys(): + for k_inner in dict1[k_outer].keys(): + if dict1[k_outer][k_inner] != dict2[k_outer][k_inner]: + return True + + return False + +def run_route(route): + can = messaging.pub_sock(service_list['can'].port) + + CP = CarInterface.get_params(CAR.CIVIC, {}) + signals, checks = get_can_signals(CP) + parser_old = CANParserOld(DBC[CP.carFingerprint]['pt'], signals, checks, 0, timeout=-1) + parser_new = CANParserNew(DBC[CP.carFingerprint]['pt'], signals, checks, 0, timeout=-1) + + if dict_keys_differ(parser_old.vl, parser_new.vl): + return False + + lr = LogReader(route + ".bz2") + + route_ok = True + + t = 0 + for msg in lr: + if msg.which() == 'can': + t += DT + can.send(msg.as_builder().to_bytes()) + + _, updated_old = parser_old.update(t, True) + _, updated_new = parser_new.update(t, True) + + if updated_old != updated_new: + route_ok = False + print(t, "Diff in seen") + + if dicts_vals_differ(parser_old.vl, parser_new.vl): + print(t, "Diff in dict") + route_ok = False + + return route_ok + +class TestCanParser(unittest.TestCase): + def setUp(self): + self.routes = { + CAR.CIVIC: "b0c9d2329ad1606b|2019-05-30--20-23-57" + } + + for route in self.routes.values(): + route_filename = route + ".bz2" + if not os.path.isfile(route_filename): + with open(route + ".bz2", "w") as f: + f.write(requests.get(BASE_URL + route_filename).content) + + def test_parser_civic(self): + self.assertTrue(run_route(self.routes[CAR.CIVIC])) + + +if __name__ == "__main__": + unittest.main() diff --git a/selfdrive/car/__init__.py b/selfdrive/car/__init__.py index 255b20806c..bb996e5885 100644 --- a/selfdrive/car/__init__.py +++ b/selfdrive/car/__init__.py @@ -1,7 +1,9 @@ # functions common among cars from common.numpy_fast import clip - +# kg of standard extra cargo to count for drive, gas, etc... +STD_CARGO_KG = 136. + def dbc_dict(pt_dbc, radar_dbc, chassis_dbc=None): return {'pt': pt_dbc, 'radar': radar_dbc, 'chassis': chassis_dbc} diff --git a/selfdrive/car/car_helpers.py b/selfdrive/car/car_helpers.py index ef807abb65..f7e8c53757 100644 --- a/selfdrive/car/car_helpers.py +++ b/selfdrive/car/car_helpers.py @@ -1,8 +1,6 @@ import os -import time from common.vin import is_vin_response_valid from common.basedir import BASEDIR -from common.realtime import sec_since_boot from common.fingerprints import eliminate_incompatible_cars, all_known_cars from selfdrive.boardd.boardd import can_list_to_can_capnp from selfdrive.swaglog import cloudlog @@ -64,7 +62,7 @@ def fingerprint(logcan, sendcan): finger = {} cloudlog.warning("waiting for fingerprint...") candidate_cars = all_known_cars() - can_seen_ts = None + can_seen_frame = None can_seen = False # works on standard 11-bit addresses for diagnostic. Tested on Toyota and Subaru; @@ -80,52 +78,55 @@ def fingerprint(logcan, sendcan): vin_dat = [] vin = "" - while 1: - for a in messaging.drain_sock(logcan): - for can in a.can: - can_seen = True - - # have we got a VIN query response? - if can.src == 0 and can.address == 0x7e8: - vin_never_responded = False - # basic sanity checks on ISO-TP response - if is_vin_response_valid(can.dat, vin_step, vin_cnt): - vin_dat += can.dat[2:] if vin_step == 0 else can.dat[1:] - vin_cnt += 1 - if vin_cnt == vin_cnts[vin_step]: - vin_responded = True - vin_step += 1 - - # ignore everything not on bus 0 and with more than 11 bits, - # which are ussually sporadic and hard to include in fingerprints. - # also exclude VIN query response on 0x7e8 - if can.src == 0 and can.address < 0x800 and can.address != 0x7e8: - finger[can.address] = len(can.dat) - candidate_cars = eliminate_incompatible_cars(can, candidate_cars) - - if can_seen_ts is None and can_seen: - can_seen_ts = sec_since_boot() # start time - ts = sec_since_boot() + frame = 0 + while True: + a = messaging.recv_one(logcan) + + for can in a.can: + can_seen = True + + # have we got a VIN query response? + if can.src == 0 and can.address == 0x7e8: + vin_never_responded = False + # basic sanity checks on ISO-TP response + if is_vin_response_valid(can.dat, vin_step, vin_cnt): + vin_dat += can.dat[2:] if vin_step == 0 else can.dat[1:] + vin_cnt += 1 + if vin_cnt == vin_cnts[vin_step]: + vin_responded = True + vin_step += 1 + + # ignore everything not on bus 0 and with more than 11 bits, + # which are ussually sporadic and hard to include in fingerprints. + # also exclude VIN query response on 0x7e8 + if can.src == 0 and can.address < 0x800 and can.address != 0x7e8: + finger[can.address] = len(can.dat) + candidate_cars = eliminate_incompatible_cars(can, candidate_cars) + + if can_seen_frame is None and can_seen: + can_seen_frame = frame + # if we only have one car choice and the time_fingerprint since we got our first # message has elapsed, exit. Toyota needs higher time_fingerprint, since DSU does not # broadcast immediately - if len(candidate_cars) == 1 and can_seen_ts is not None: + if len(candidate_cars) == 1 and can_seen_frame is not None: time_fingerprint = 1.0 if ("TOYOTA" in candidate_cars[0] or "LEXUS" in candidate_cars[0]) else 0.1 - if (ts - can_seen_ts) > time_fingerprint: + if (frame - can_seen_frame) > (time_fingerprint * 100): break # bail if no cars left or we've been waiting for more than 2s since can_seen - elif len(candidate_cars) == 0 or (can_seen_ts is not None and (ts - can_seen_ts) > 2.): + elif len(candidate_cars) == 0 or (can_seen_frame is not None and (frame - can_seen_frame) > 200): return None, finger, "" # keep sending VIN qury if ECU isn't responsing. # sendcan is probably not ready due to the zmq slow joiner syndrome - if can_seen and (vin_never_responded or (vin_responded and vin_step < len(vin_cnts))): + # TODO: VIN query temporarily disabled until we have the harness + if False and can_seen and (vin_never_responded or (vin_responded and vin_step < len(vin_cnts))): sendcan.send(can_list_to_can_capnp([vin_query_msg[vin_step]], msgtype='sendcan')) vin_responded = False vin_cnt = 0 - time.sleep(0.01) + frame += 1 # only report vin if procedure is finished if vin_step == len(vin_cnts) and vin_cnt == vin_cnts[-1]: diff --git a/selfdrive/car/chrysler/carstate.py b/selfdrive/car/chrysler/carstate.py index 7f4ad675d0..1d38b8cdab 100644 --- a/selfdrive/car/chrysler/carstate.py +++ b/selfdrive/car/chrysler/carstate.py @@ -97,8 +97,6 @@ class CarState(object): def update(self, cp, cp_cam): - # copy can_valid - self.can_valid = cp.can_valid # update prevs, update must run once per loop self.prev_left_blinker_on = self.left_blinker_on diff --git a/selfdrive/car/chrysler/interface.py b/selfdrive/car/chrysler/interface.py index cef9698fd3..6621c7e20f 100755 --- a/selfdrive/car/chrysler/interface.py +++ b/selfdrive/car/chrysler/interface.py @@ -6,6 +6,7 @@ from selfdrive.controls.lib.drive_helpers import EventTypes as ET, create_event from selfdrive.controls.lib.vehicle_model import VehicleModel from selfdrive.car.chrysler.carstate import CarState, get_can_parser, get_camera_parser from selfdrive.car.chrysler.values import ECU, check_ecu_msgs, CAR +from selfdrive.car import STD_CARGO_KG class CarInterface(object): @@ -14,7 +15,6 @@ class CarInterface(object): self.VM = VehicleModel(CP) self.frame = 0 - self.can_invalid_count = 0 self.gas_pressed_prev = False self.brake_pressed_prev = False self.cruise_enabled_prev = False @@ -40,23 +40,20 @@ class CarInterface(object): @staticmethod def get_params(candidate, fingerprint, vin=""): - # kg of standard extra cargo to count for drive, gas, etc... - std_cargo = 136 - ret = car.CarParams.new_message() ret.carName = "chrysler" ret.carFingerprint = candidate ret.carVin = vin - ret.safetyModel = car.CarParams.SafetyModels.chrysler + ret.safetyModel = car.CarParams.SafetyModel.chrysler # pedal ret.enableCruise = True # FIXME: hardcoding honda civic 2016 touring params so they can be used to # scale unknown params for other cars - mass_civic = 2923./2.205 + std_cargo + mass_civic = 2923. * CV.LB_TO_KG + STD_CARGO_KG wheelbase_civic = 2.70 centerToFront_civic = wheelbase_civic * 0.4 centerToRear_civic = wheelbase_civic - centerToFront_civic @@ -67,7 +64,7 @@ class CarInterface(object): # Speed conversion: 20, 45 mph ret.wheelbase = 3.089 # in meters for Pacifica Hybrid 2017 ret.steerRatio = 16.2 # Pacifica Hybrid 2017 - ret.mass = 2858 + std_cargo # kg curb weight Pacifica Hybrid 2017 + ret.mass = 2858. + STD_CARGO_KG # kg curb weight Pacifica Hybrid 2017 ret.lateralTuning.pid.kpBP, ret.lateralTuning.pid.kiBP = [[9., 20.], [9., 20.]] ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.15,0.30], [0.03,0.05]] ret.lateralTuning.pid.kf = 0.00006 # full torque for 10 deg at 80mph means 0.00007818594 @@ -135,15 +132,16 @@ class CarInterface(object): def update(self, c): # ******************* do can recv ******************* canMonoTimes = [] - can_valid, _ = self.cp.update(int(sec_since_boot() * 1e9), True) - cam_valid, _ = self.cp_cam.update(int(sec_since_boot() * 1e9), False) - can_rcv_error = not can_valid or not cam_valid + can_rcv_valid, _ = self.cp.update(int(sec_since_boot() * 1e9), True) + cam_rcv_valid, _ = self.cp_cam.update(int(sec_since_boot() * 1e9), False) self.CS.update(self.cp, self.cp_cam) # create message ret = car.CarState.new_message() + ret.canValid = can_rcv_valid and cam_rcv_valid and self.cp.can_valid and self.cp_cam.can_valid + # speeds ret.vEgo = self.CS.v_ego ret.vEgoRaw = self.CS.v_ego_raw @@ -212,14 +210,6 @@ class CarInterface(object): # events events = [] - if not self.CS.can_valid: - self.can_invalid_count += 1 - else: - self.can_invalid_count = 0 - - if can_rcv_error or self.can_invalid_count >= 5: - events.append(create_event('commIssue', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE])) - if not (ret.gearShifter in ('drive', 'low')): events.append(create_event('wrongGear', [ET.NO_ENTRY, ET.SOFT_DISABLE])) if ret.doorOpen: diff --git a/selfdrive/car/chrysler/radar_interface.py b/selfdrive/car/chrysler/radar_interface.py index e5359fad8e..b4970b2223 100755 --- a/selfdrive/car/chrysler/radar_interface.py +++ b/selfdrive/car/chrysler/radar_interface.py @@ -3,10 +3,6 @@ import os from selfdrive.can.parser import CANParser from cereal import car from common.realtime import sec_since_boot -import zmq -from selfdrive.services import service_list -import selfdrive.messaging as messaging - RADAR_MSGS_C = range(0x2c2, 0x2d4+2, 2) # c_ messages 706,...,724 RADAR_MSGS_D = range(0x2a2, 0x2b4+2, 2) # d_ messages @@ -55,8 +51,6 @@ class RadarInterface(object): self.pts = {} self.delay = 0.0 # Delay of radar #TUNE self.rcp = _create_radar_can_parser() - context = zmq.Context() - self.logcan = messaging.sub_sock(context, service_list['can'].port) def update(self): canMonoTimes = [] @@ -73,7 +67,7 @@ class RadarInterface(object): ret = car.RadarData.new_message() errors = [] if not self.rcp.can_valid: - errors.append("commIssue") + errors.append("canError") ret.errors = errors ret.canMonoTimes = canMonoTimes diff --git a/selfdrive/car/ford/carstate.py b/selfdrive/car/ford/carstate.py index 2e26eb7c64..dc6d824ff5 100644 --- a/selfdrive/car/ford/carstate.py +++ b/selfdrive/car/ford/carstate.py @@ -53,9 +53,6 @@ class CarState(object): self.v_ego = 0.0 def update(self, cp): - # copy can_valid - self.can_valid = cp.can_valid - # update prevs, update must run once per loop self.prev_left_blinker_on = self.left_blinker_on self.prev_right_blinker_on = self.right_blinker_on diff --git a/selfdrive/car/ford/interface.py b/selfdrive/car/ford/interface.py index 439e561a4e..7664d99640 100755 --- a/selfdrive/car/ford/interface.py +++ b/selfdrive/car/ford/interface.py @@ -7,6 +7,7 @@ from selfdrive.controls.lib.drive_helpers import EventTypes as ET, create_event from selfdrive.controls.lib.vehicle_model import VehicleModel from selfdrive.car.ford.carstate import CarState, get_can_parser from selfdrive.car.ford.values import MAX_ANGLE +from selfdrive.car import STD_CARGO_KG class CarInterface(object): @@ -15,7 +16,6 @@ class CarInterface(object): self.VM = VehicleModel(CP) self.frame = 0 - self.can_invalid_count = 0 self.gas_pressed_prev = False self.brake_pressed_prev = False self.cruise_enabled_prev = False @@ -40,23 +40,20 @@ class CarInterface(object): @staticmethod def get_params(candidate, fingerprint, vin=""): - # kg of standard extra cargo to count for drive, gas, etc... - std_cargo = 136 - ret = car.CarParams.new_message() ret.carName = "ford" ret.carFingerprint = candidate ret.carVin = vin - ret.safetyModel = car.CarParams.SafetyModels.ford + ret.safetyModel = car.CarParams.SafetyModel.ford # pedal ret.enableCruise = True # FIXME: hardcoding honda civic 2016 touring params so they can be used to # scale unknown params for other cars - mass_civic = 2923. * CV.LB_TO_KG + std_cargo + mass_civic = 2923. * CV.LB_TO_KG + STD_CARGO_KG wheelbase_civic = 2.70 centerToFront_civic = wheelbase_civic * 0.4 centerToRear_civic = wheelbase_civic - centerToFront_civic @@ -66,7 +63,7 @@ class CarInterface(object): ret.wheelbase = 2.85 ret.steerRatio = 14.8 - ret.mass = 3045. * CV.LB_TO_KG + std_cargo + ret.mass = 3045. * CV.LB_TO_KG + STD_CARGO_KG ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.01], [0.005]] # TODO: tune this ret.lateralTuning.pid.kf = 1. / MAX_ANGLE # MAX Steer angle to normalize FF @@ -133,14 +130,15 @@ class CarInterface(object): # ******************* do can recv ******************* canMonoTimes = [] - can_valid, _ = self.cp.update(int(sec_since_boot() * 1e9), True) - can_rcv_error = not can_valid + can_rcv_valid, _ = self.cp.update(int(sec_since_boot() * 1e9), True) self.CS.update(self.cp) # create message ret = car.CarState.new_message() + ret.canValid = can_rcv_valid and self.cp.can_valid + # speeds ret.vEgo = self.CS.v_ego ret.vEgoRaw = self.CS.v_ego_raw @@ -168,13 +166,6 @@ class CarInterface(object): # events events = [] - if not self.CS.can_valid: - self.can_invalid_count += 1 - else: - self.can_invalid_count = 0 - - if can_rcv_error or self.can_invalid_count >= 5: - events.append(create_event('commIssue', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE])) if self.CS.steer_error: events.append(create_event('steerUnavailable', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE, ET.PERMANENT])) diff --git a/selfdrive/car/ford/radar_interface.py b/selfdrive/car/ford/radar_interface.py index a49ad413c1..08b54723d6 100755 --- a/selfdrive/car/ford/radar_interface.py +++ b/selfdrive/car/ford/radar_interface.py @@ -4,10 +4,6 @@ import numpy as np from selfdrive.can.parser import CANParser from cereal import car from common.realtime import sec_since_boot -import zmq -from selfdrive.services import service_list -import selfdrive.messaging as messaging - RADAR_MSGS = range(0x500, 0x540) @@ -33,9 +29,6 @@ class RadarInterface(object): # Nidec self.rcp = _create_radar_can_parser() - context = zmq.Context() - self.logcan = messaging.sub_sock(context, service_list['can'].port) - def update(self): canMonoTimes = [] @@ -52,7 +45,7 @@ class RadarInterface(object): ret = car.RadarData.new_message() errors = [] if not self.rcp.can_valid: - errors.append("commIssue") + errors.append("canError") ret.errors = errors ret.canMonoTimes = canMonoTimes diff --git a/selfdrive/car/gm/carcontroller.py b/selfdrive/car/gm/carcontroller.py index 000f7dde68..a2ffac61f0 100644 --- a/selfdrive/car/gm/carcontroller.py +++ b/selfdrive/car/gm/carcontroller.py @@ -1,6 +1,6 @@ from cereal import car +from common.realtime import DT_CTRL from common.numpy_fast import interp -from common.realtime import sec_since_boot from selfdrive.config import Conversions as CV from selfdrive.car import apply_std_steer_torque_limits from selfdrive.car.gm import gmcan @@ -9,6 +9,7 @@ from selfdrive.can.packer import CANPacker VisualAlert = car.CarControl.HUDControl.VisualAlert + class CarControllerParams(): def __init__(self, car_fingerprint): if car_fingerprint in SUPERCRUISE_CARS: @@ -47,7 +48,7 @@ class CarControllerParams(): def actuator_hystereses(final_pedal, pedal_steady): # hyst params... TODO: move these to VehicleParams - pedal_hyst_gap = 0.01 # don't change pedal command for small oscilalitons within this value + pedal_hyst_gap = 0.01 # don't change pedal command for small oscillations within this value # for small pedal oscillations within pedal_hyst_gap, don't change the pedal command if final_pedal == 0.: @@ -70,7 +71,7 @@ def process_hud_alert(hud_alert): class CarController(object): def __init__(self, canbus, car_fingerprint): self.pedal_steady = 0. - self.start_time = sec_since_boot() + self.start_time = 0. self.chime = 0 self.steer_idx = 0 self.apply_steer_last = 0 @@ -154,7 +155,7 @@ class CarController(object): # Radar needs to know current speed and yaw rate (50hz), # and that ADAS is alive (10hz) time_and_headlights_step = 10 - tt = sec_since_boot() + tt = frame * DT_CTRL if frame % time_and_headlights_step == 0: idx = (frame // time_and_headlights_step) % 4 diff --git a/selfdrive/car/gm/carstate.py b/selfdrive/car/gm/carstate.py index 350274f2f6..174d11b46b 100644 --- a/selfdrive/car/gm/carstate.py +++ b/selfdrive/car/gm/carstate.py @@ -71,8 +71,6 @@ class CarState(object): self.v_ego = 0. def update(self, pt_cp): - - self.can_valid = pt_cp.can_valid self.prev_cruise_buttons = self.cruise_buttons self.cruise_buttons = pt_cp.vl["ASCMSteeringButton"]['ACCButtons'] @@ -118,7 +116,6 @@ class CarState(object): self.steer_error = False self.brake_error = False - self.can_valid = True self.prev_left_blinker_on = self.left_blinker_on self.prev_right_blinker_on = self.right_blinker_on diff --git a/selfdrive/car/gm/interface.py b/selfdrive/car/gm/interface.py index d8177ccef6..4a909bc844 100755 --- a/selfdrive/car/gm/interface.py +++ b/selfdrive/car/gm/interface.py @@ -7,6 +7,7 @@ from selfdrive.controls.lib.vehicle_model import VehicleModel from selfdrive.car.gm.values import DBC, CAR, STOCK_CONTROL_MSGS, AUDIO_HUD, \ SUPERCRUISE_CARS, AccState from selfdrive.car.gm.carstate import CarState, CruiseButtons, get_powertrain_can_parser +from selfdrive.car import STD_CARGO_KG class CanBus(object): @@ -23,7 +24,6 @@ class CarInterface(object): self.frame = 0 self.gas_pressed_prev = False self.brake_pressed_prev = False - self.can_invalid_count = 0 self.acc_active_prev = 0 # *** init the major players *** @@ -61,14 +61,11 @@ class CarInterface(object): ret.enableCamera = not any(x for x in STOCK_CONTROL_MSGS[candidate] if x in fingerprint) ret.openpilotLongitudinalControl = ret.enableCamera - std_cargo = 136 - if candidate == CAR.VOLT: # supports stop and go, but initial engage must be above 18mph (which include conservatism) ret.minEnableSpeed = 18 * CV.MPH_TO_MS - # kg of standard extra cargo to count for driver, gas, etc... - ret.mass = 1607. + std_cargo - ret.safetyModel = car.CarParams.SafetyModels.gm + ret.mass = 1607. + STD_CARGO_KG + ret.safetyModel = car.CarParams.SafetyModel.gm ret.wheelbase = 2.69 ret.steerRatio = 15.7 ret.steerRatioRear = 0. @@ -77,28 +74,27 @@ class CarInterface(object): elif candidate == CAR.MALIBU: # supports stop and go, but initial engage must be above 18mph (which include conservatism) ret.minEnableSpeed = 18 * CV.MPH_TO_MS - ret.mass = 1496. + std_cargo - ret.safetyModel = car.CarParams.SafetyModels.gm + ret.mass = 1496. + STD_CARGO_KG + ret.safetyModel = car.CarParams.SafetyModel.gm ret.wheelbase = 2.83 ret.steerRatio = 15.8 ret.steerRatioRear = 0. ret.centerToFront = ret.wheelbase * 0.4 # wild guess elif candidate == CAR.HOLDEN_ASTRA: - # kg of standard extra cargo to count for driver, gas, etc... - ret.mass = 1363. + std_cargo + ret.mass = 1363. + STD_CARGO_KG ret.wheelbase = 2.662 # Remaining parameters copied from Volt for now ret.centerToFront = ret.wheelbase * 0.4 ret.minEnableSpeed = 18 * CV.MPH_TO_MS - ret.safetyModel = car.CarParams.SafetyModels.gm + ret.safetyModel = car.CarParams.SafetyModel.gm ret.steerRatio = 15.7 ret.steerRatioRear = 0. elif candidate == CAR.ACADIA: ret.minEnableSpeed = -1. # engage speed is decided by pcm - ret.mass = 4353. * CV.LB_TO_KG + std_cargo - ret.safetyModel = car.CarParams.SafetyModels.gm + ret.mass = 4353. * CV.LB_TO_KG + STD_CARGO_KG + ret.safetyModel = car.CarParams.SafetyModel.gm ret.wheelbase = 2.86 ret.steerRatio = 14.4 #end to end is 13.46 ret.steerRatioRear = 0. @@ -106,8 +102,8 @@ class CarInterface(object): elif candidate == CAR.BUICK_REGAL: ret.minEnableSpeed = 18 * CV.MPH_TO_MS - ret.mass = 3779. * CV.LB_TO_KG + std_cargo # (3849+3708)/2 - ret.safetyModel = car.CarParams.SafetyModels.gm + ret.mass = 3779. * CV.LB_TO_KG + STD_CARGO_KG # (3849+3708)/2 + ret.safetyModel = car.CarParams.SafetyModel.gm ret.wheelbase = 2.83 #111.4 inches in meters ret.steerRatio = 14.4 # guess for tourx ret.steerRatioRear = 0. @@ -115,8 +111,8 @@ class CarInterface(object): elif candidate == CAR.CADILLAC_ATS: ret.minEnableSpeed = 18 * CV.MPH_TO_MS - ret.mass = 1601. + std_cargo - ret.safetyModel = car.CarParams.SafetyModels.gm + ret.mass = 1601. + STD_CARGO_KG + ret.safetyModel = car.CarParams.SafetyModel.gm ret.wheelbase = 2.78 ret.steerRatio = 15.3 ret.steerRatioRear = 0. @@ -125,9 +121,8 @@ class CarInterface(object): elif candidate == CAR.CADILLAC_CT6: # engage speed is decided by pcm ret.minEnableSpeed = -1. - # kg of standard extra cargo to count for driver, gas, etc... - ret.mass = 4016. * CV.LB_TO_KG + std_cargo - ret.safetyModel = car.CarParams.SafetyModels.cadillac + ret.mass = 4016. * CV.LB_TO_KG + STD_CARGO_KG + ret.safetyModel = car.CarParams.SafetyModel.cadillac ret.wheelbase = 3.11 ret.steerRatio = 14.6 # it's 16.3 without rear active steering ret.steerRatioRear = 0. # TODO: there is RAS on this car! @@ -136,7 +131,7 @@ class CarInterface(object): # hardcoding honda civic 2016 touring params so they can be used to # scale unknown params for other cars - mass_civic = 2923. * CV.LB_TO_KG + std_cargo + mass_civic = 2923. * CV.LB_TO_KG + STD_CARGO_KG wheelbase_civic = 2.70 centerToFront_civic = wheelbase_civic * 0.4 centerToRear_civic = wheelbase_civic - centerToFront_civic @@ -191,13 +186,15 @@ class CarInterface(object): # returns a car.CarState def update(self, c): - can_valid, _ = self.pt_cp.update(int(sec_since_boot() * 1e9), True) - can_rcv_error = not can_valid + can_rcv_valid, _ = self.pt_cp.update(int(sec_since_boot() * 1e9), True) + self.CS.update(self.pt_cp) # create message ret = car.CarState.new_message() + ret.canValid = can_rcv_valid and self.pt_cp.can_valid + # speeds ret.vEgo = self.CS.v_ego ret.aEgo = self.CS.a_ego @@ -275,14 +272,6 @@ class CarInterface(object): ret.buttonEvents = buttonEvents events = [] - if not self.CS.can_valid: - self.can_invalid_count += 1 - else: - self.can_invalid_count = 0 - - if can_rcv_error or self.can_invalid_count >= 5: - events.append(create_event('commIssue', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE])) - if self.CS.steer_error: events.append(create_event('steerUnavailable', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE, ET.PERMANENT])) if self.CS.steer_not_allowed: diff --git a/selfdrive/car/gm/radar_interface.py b/selfdrive/car/gm/radar_interface.py index 7a8d9c4716..12fb7c2342 100755 --- a/selfdrive/car/gm/radar_interface.py +++ b/selfdrive/car/gm/radar_interface.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -import zmq import math import time import numpy as np @@ -8,8 +7,6 @@ from selfdrive.can.parser import CANParser from selfdrive.car.gm.interface import CanBus from selfdrive.car.gm.values import DBC, CAR from common.realtime import sec_since_boot -from selfdrive.services import service_list -import selfdrive.messaging as messaging RADAR_HEADER_MSG = 1120 SLOT_1_MSG = RADAR_HEADER_MSG + 1 @@ -55,9 +52,6 @@ class RadarInterface(object): print "Using %d as obstacle CAN bus ID" % canbus.obstacle self.rcp = create_radar_can_parser(canbus, CP.carFingerprint) - context = zmq.Context() - self.logcan = messaging.sub_sock(context, service_list['can'].port) - def update(self): updated_messages = set() ret = car.RadarData.new_message() @@ -79,7 +73,7 @@ class RadarInterface(object): header['FLRRAntTngFltPrsnt'] or header['FLRRAlgnFltPrsnt'] errors = [] if not self.rcp.can_valid: - errors.append("commIssue") + errors.append("canError") if fault: errors.append("fault") ret.errors = errors diff --git a/selfdrive/car/honda/carcontroller.py b/selfdrive/car/honda/carcontroller.py index bf7d158fc3..3a5703e117 100644 --- a/selfdrive/car/honda/carcontroller.py +++ b/selfdrive/car/honda/carcontroller.py @@ -1,5 +1,5 @@ from collections import namedtuple -from common.realtime import sec_since_boot +from common.realtime import DT_CTRL from selfdrive.controls.lib.drive_helpers import rate_limit from common.numpy_fast import clip from selfdrive.car import create_gas_command @@ -7,6 +7,7 @@ from selfdrive.car.honda import hondacan from selfdrive.car.honda.values import AH, CruiseButtons, CAR from selfdrive.can.packer import CANPacker + def actuator_hystereses(brake, braking, brake_steady, v_ego, car_fingerprint): # hyst params brake_hyst_on = 0.02 # to activate brakes exceed this value @@ -33,15 +34,14 @@ def actuator_hystereses(brake, braking, brake_steady, v_ego, car_fingerprint): return brake, braking, brake_steady -def brake_pump_hysteresis(apply_brake, apply_brake_last, last_pump_ts): - ts = sec_since_boot() +def brake_pump_hysteresis(apply_brake, apply_brake_last, last_pump_ts, ts): pump_on = False # reset pump timer if: # - there is an increment in brake request # - we are applying steady state brakes and we haven't been running the pump # for more than 20s (to prevent pressure bleeding) - if apply_brake > apply_brake_last or (ts - last_pump_ts > 20 and apply_brake > 0): + if apply_brake > apply_brake_last or (ts - last_pump_ts > 20. and apply_brake > 0): last_pump_ts = ts # once the pump is on, run it for at least 0.2s @@ -79,7 +79,7 @@ class CarController(object): self.brake_steady = 0. self.brake_last = 0. self.apply_brake_last = 0 - self.last_pump_ts = 0 + self.last_pump_ts = 0. self.packer = CANPacker(dbc_name) self.new_radar_config = False @@ -167,7 +167,8 @@ class CarController(object): # Send gas and brake commands. if (frame % 2) == 0: idx = frame // 2 - pump_on, self.last_pump_ts = brake_pump_hysteresis(apply_brake, self.apply_brake_last, self.last_pump_ts) + ts = frame * DT_CTRL + pump_on, self.last_pump_ts = brake_pump_hysteresis(apply_brake, self.apply_brake_last, self.last_pump_ts, ts) can_sends.append(hondacan.create_brake_command(self.packer, apply_brake, pump_on, pcm_override, pcm_cancel_cmd, hud.chime, hud.fcw, idx)) self.apply_brake_last = apply_brake diff --git a/selfdrive/car/honda/carstate.py b/selfdrive/car/honda/carstate.py index f3374da576..6c0aec52a0 100644 --- a/selfdrive/car/honda/carstate.py +++ b/selfdrive/car/honda/carstate.py @@ -1,6 +1,7 @@ from common.numpy_fast import interp from common.kalman.simple_kalman import KF1D -from selfdrive.can.parser import CANParser, CANDefine +from selfdrive.can.can_define import CANDefine +from selfdrive.can.parser import CANParser from selfdrive.config import Conversions as CV from selfdrive.car.honda.values import CAR, DBC, STEER_THRESHOLD, SPEED_FACTOR, HONDA_BOSCH @@ -199,10 +200,6 @@ class CarState(object): def update(self, cp, cp_cam): - # copy can_valid on buses 0 and 2 - self.can_valid = cp.can_valid - self.cam_can_valid = cp_cam.can_valid - # car params v_weight_v = [0., 1.] # don't trust smooth speed at low values to avoid premature zero snapping v_weight_bp = [1., 6.] # smooth blending, below ~0.6m/s the smooth speed snaps to zero diff --git a/selfdrive/car/honda/interface.py b/selfdrive/car/honda/interface.py index c261d86c26..72c85c862c 100755 --- a/selfdrive/car/honda/interface.py +++ b/selfdrive/car/honda/interface.py @@ -3,20 +3,16 @@ import os import numpy as np from cereal import car from common.numpy_fast import clip, interp -from common.realtime import sec_since_boot +from common.realtime import sec_since_boot, DT_CTRL from selfdrive.swaglog import cloudlog from selfdrive.config import Conversions as CV from selfdrive.controls.lib.drive_helpers import create_event, EventTypes as ET, get_events from selfdrive.controls.lib.vehicle_model import VehicleModel from selfdrive.car.honda.carstate import CarState, get_can_parser, get_cam_can_parser -from selfdrive.car.honda.values import CruiseButtons, CAR, HONDA_BOSCH, AUDIO_HUD, VISUAL_HUD +from selfdrive.car.honda.values import CruiseButtons, CAR, HONDA_BOSCH, AUDIO_HUD, VISUAL_HUD, CAMERA_MSGS +from selfdrive.car import STD_CARGO_KG from selfdrive.controls.lib.planner import _A_CRUISE_MAX_V_FOLLOWING - -# msgs sent for steering controller by camera module on can 0. -# those messages are mutually exclusive on CRV and non-CRV cars -CAMERA_MSGS = [0xe4, 0x194] - A_ACC_MAX = max(_A_CRUISE_MAX_V_FOLLOWING) @@ -83,8 +79,6 @@ class CarInterface(object): self.last_enable_sent = 0 self.gas_pressed_prev = False self.brake_pressed_prev = False - self.can_invalid_count = 0 - self.cam_can_invalid_count = 0 self.cp = get_can_parser(CP) self.cp_cam = get_cam_can_parser(CP) @@ -143,12 +137,12 @@ class CarInterface(object): ret.carVin = vin if candidate in HONDA_BOSCH: - ret.safetyModel = car.CarParams.SafetyModels.hondaBosch + ret.safetyModel = car.CarParams.SafetyModel.hondaBosch ret.enableCamera = True ret.radarOffCan = True ret.openpilotLongitudinalControl = False else: - ret.safetyModel = car.CarParams.SafetyModels.honda + ret.safetyModel = car.CarParams.SafetyModel.honda ret.enableCamera = not any(x for x in CAMERA_MSGS if x in fingerprint) ret.enableGasInterceptor = 0x201 in fingerprint ret.openpilotLongitudinalControl = ret.enableCamera @@ -158,12 +152,9 @@ class CarInterface(object): ret.enableCruise = not ret.enableGasInterceptor - # kg of standard extra cargo to count for drive, gas, etc... - std_cargo = 136 - # FIXME: hardcoding honda civic 2016 touring params so they can be used to # scale unknown params for other cars - mass_civic = 2923 * CV.LB_TO_KG + std_cargo + mass_civic = 2923. * CV.LB_TO_KG + STD_CARGO_KG wheelbase_civic = 2.70 centerToFront_civic = wheelbase_civic * 0.4 centerToRear_civic = wheelbase_civic - centerToFront_civic @@ -203,7 +194,7 @@ class CarInterface(object): stop_and_go = True if not candidate == CAR.ACCORDH: # Hybrid uses same brake msg as hatch ret.safetyParam = 1 # Accord and CRV 5G use an alternate user brake msg - ret.mass = 3279. * CV.LB_TO_KG + std_cargo + ret.mass = 3279. * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.83 ret.centerToFront = ret.wheelbase * 0.39 ret.steerRatio = 15.96 # 11.82 is spec end-to-end @@ -216,7 +207,7 @@ class CarInterface(object): elif candidate == CAR.ACURA_ILX: stop_and_go = False - ret.mass = 3095 * CV.LB_TO_KG + std_cargo + ret.mass = 3095. * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.67 ret.centerToFront = ret.wheelbase * 0.37 ret.steerRatio = 18.61 # 15.3 is spec end-to-end @@ -229,7 +220,7 @@ class CarInterface(object): elif candidate == CAR.CRV: stop_and_go = False - ret.mass = 3572 * CV.LB_TO_KG + std_cargo + ret.mass = 3572. * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.62 ret.centerToFront = ret.wheelbase * 0.41 ret.steerRatio = 15.3 # as spec @@ -243,7 +234,7 @@ class CarInterface(object): elif candidate == CAR.CRV_5G: stop_and_go = True ret.safetyParam = 1 # Accord and CRV 5G use an alternate user brake msg - ret.mass = 3410. * CV.LB_TO_KG + std_cargo + ret.mass = 3410. * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.66 ret.centerToFront = ret.wheelbase * 0.41 ret.steerRatio = 16.0 # 12.3 is spec end-to-end @@ -257,7 +248,7 @@ class CarInterface(object): elif candidate == CAR.CRV_HYBRID: stop_and_go = True ret.safetyParam = 1 # Accord and CRV 5G use an alternate user brake msg - ret.mass = 1667. + std_cargo # mean of 4 models in kg + ret.mass = 1667. + STD_CARGO_KG # mean of 4 models in kg ret.wheelbase = 2.66 ret.centerToFront = ret.wheelbase * 0.41 ret.steerRatio = 16.0 # 12.3 is spec end-to-end @@ -270,7 +261,7 @@ class CarInterface(object): elif candidate == CAR.ACURA_RDX: stop_and_go = False - ret.mass = 3935 * CV.LB_TO_KG + std_cargo + ret.mass = 3935. * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.68 ret.centerToFront = ret.wheelbase * 0.38 ret.steerRatio = 15.0 # as spec @@ -283,7 +274,7 @@ class CarInterface(object): elif candidate == CAR.ODYSSEY: stop_and_go = False - ret.mass = 4471 * CV.LB_TO_KG + std_cargo + ret.mass = 4471. * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 3.00 ret.centerToFront = ret.wheelbase * 0.41 ret.steerRatio = 14.35 # as spec @@ -296,7 +287,7 @@ class CarInterface(object): elif candidate == CAR.ODYSSEY_CHN: stop_and_go = False - ret.mass = 1849.2 + std_cargo # mean of 4 models in kg + ret.mass = 1849.2 + STD_CARGO_KG # mean of 4 models in kg ret.wheelbase = 2.90 # spec ret.centerToFront = ret.wheelbase * 0.41 # from CAR.ODYSSEY ret.steerRatio = 14.35 # from CAR.ODYSSEY @@ -309,7 +300,7 @@ class CarInterface(object): elif candidate in (CAR.PILOT, CAR.PILOT_2019): stop_and_go = False - ret.mass = 4204 * CV.LB_TO_KG + std_cargo # average weight + ret.mass = 4204. * CV.LB_TO_KG + STD_CARGO_KG # average weight ret.wheelbase = 2.82 ret.centerToFront = ret.wheelbase * 0.428 # average weight distribution ret.steerRatio = 16.0 # as spec @@ -322,7 +313,7 @@ class CarInterface(object): elif candidate == CAR.RIDGELINE: stop_and_go = False - ret.mass = 4515 * CV.LB_TO_KG + std_cargo + ret.mass = 4515. * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 3.18 ret.centerToFront = ret.wheelbase * 0.41 ret.steerRatio = 15.59 # as spec @@ -386,15 +377,16 @@ class CarInterface(object): def update(self, c): # ******************* do can recv ******************* canMonoTimes = [] - can_valid, _ = self.cp.update(int(sec_since_boot() * 1e9), True) - cam_valid, _ = self.cp_cam.update(int(sec_since_boot() * 1e9), False) - can_rcv_error = not can_valid or not cam_valid + can_rcv_valid, _ = self.cp.update(int(sec_since_boot() * 1e9), True) + cam_rcv_valid, _ = self.cp_cam.update(int(sec_since_boot() * 1e9), False) self.CS.update(self.cp, self.cp_cam) # create message ret = car.CarState.new_message() + ret.canValid = can_rcv_valid and cam_rcv_valid and self.cp.can_valid + # speeds ret.vEgo = self.CS.v_ego ret.aEgo = self.CS.a_ego @@ -493,25 +485,10 @@ class CarInterface(object): ret.buttonEvents = buttonEvents # events - # TODO: event names aren't checked at compile time. - # Maybe there is a way to use capnp enums directly events = [] - if not self.CS.can_valid: - self.can_invalid_count += 1 - else: - self.can_invalid_count = 0 - - if can_rcv_error or self.can_invalid_count >= 5: - events.append(create_event('commIssue', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE])) - - if not self.CS.cam_can_valid and self.CP.enableCamera: - self.cam_can_invalid_count += 1 - # wait 1.0s before throwing the alert to avoid it popping when you turn off the car - if self.cam_can_invalid_count >= 100 and self.CS.CP.carFingerprint not in HONDA_BOSCH: - events.append(create_event('invalidGiraffeHonda', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE, ET.PERMANENT])) - else: - self.cam_can_invalid_count = 0 - + # wait 1.0s before throwing the alert to avoid it popping when you turn off the car + if self.cp_cam.can_invalid_cnt >= 100 and self.CS.CP.carFingerprint not in HONDA_BOSCH and self.CP.enableCamera: + events.append(create_event('invalidGiraffeHonda', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE, ET.PERMANENT])) if self.CS.steer_error: events.append(create_event('steerUnavailable', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE, ET.PERMANENT])) elif self.CS.steer_warning: @@ -557,7 +534,7 @@ class CarInterface(object): if self.CS.CP.minEnableSpeed > 0 and ret.vEgo < 0.001: events.append(create_event('manualRestart', [ET.WARNING])) - cur_time = sec_since_boot() + cur_time = self.frame * DT_CTRL enable_pressed = False # handle button presses for b in ret.buttonEvents: diff --git a/selfdrive/car/honda/radar_interface.py b/selfdrive/car/honda/radar_interface.py index 6b5d692084..94e98cf2cb 100755 --- a/selfdrive/car/honda/radar_interface.py +++ b/selfdrive/car/honda/radar_interface.py @@ -1,13 +1,9 @@ #!/usr/bin/env python import os -import zmq import time from cereal import car from selfdrive.can.parser import CANParser from common.realtime import sec_since_boot -from selfdrive.services import service_list -import selfdrive.messaging as messaging - def _create_nidec_can_parser(): dbc_f = 'acura_ilx_2016_nidec.dbc' @@ -36,9 +32,6 @@ class RadarInterface(object): # Nidec self.rcp = _create_nidec_can_parser() - context = zmq.Context() - self.logcan = messaging.sub_sock(context, service_list['can'].port) - def update(self): canMonoTimes = [] @@ -81,7 +74,7 @@ class RadarInterface(object): errors = [] if not self.rcp.can_valid: - errors.append("commIssue") + errors.append("canError") if self.radar_fault: errors.append("fault") if self.radar_wrong_config: diff --git a/selfdrive/car/honda/values.py b/selfdrive/car/honda/values.py index a79ac6dc55..8b4d13bf75 100644 --- a/selfdrive/car/honda/values.py +++ b/selfdrive/car/honda/values.py @@ -193,5 +193,9 @@ SPEED_FACTOR = { CAR.RIDGELINE: 1., } +# msgs sent for steering controller by camera module on can 0. +# those messages are mutually exclusive on CRV and non-CRV cars +CAMERA_MSGS = [0xe4, 0x194] + # TODO: get these from dbc file HONDA_BOSCH = [CAR.ACCORD, CAR.ACCORD_15, CAR.ACCORDH, CAR.CIVIC_BOSCH, CAR.CRV_5G, CAR.CRV_HYBRID] diff --git a/selfdrive/car/hyundai/carstate.py b/selfdrive/car/hyundai/carstate.py index 6e5db74e5e..8c900d73f8 100644 --- a/selfdrive/car/hyundai/carstate.py +++ b/selfdrive/car/hyundai/carstate.py @@ -145,9 +145,6 @@ class CarState(object): self.right_blinker_flash = 0 def update(self, cp, cp_cam): - # copy can_valid - self.can_valid = cp.can_valid - # update prevs, update must run once per Loop self.prev_left_blinker_on = self.left_blinker_on self.prev_right_blinker_on = self.right_blinker_on diff --git a/selfdrive/car/hyundai/interface.py b/selfdrive/car/hyundai/interface.py index 75597bcb2c..bd99eaa5ac 100644 --- a/selfdrive/car/hyundai/interface.py +++ b/selfdrive/car/hyundai/interface.py @@ -6,6 +6,7 @@ from selfdrive.controls.lib.drive_helpers import EventTypes as ET, create_event from selfdrive.controls.lib.vehicle_model import VehicleModel from selfdrive.car.hyundai.carstate import CarState, get_can_parser, get_camera_parser from selfdrive.car.hyundai.values import CAMERA_MSGS, CAR, get_hud_alerts, FEATURES +from selfdrive.car import STD_CARGO_KG class CarInterface(object): @@ -18,7 +19,6 @@ class CarInterface(object): self.gas_pressed_prev = False self.brake_pressed_prev = False - self.can_invalid_count = 0 self.cruise_enabled_prev = False self.low_speed_alert = False @@ -42,21 +42,18 @@ class CarInterface(object): @staticmethod def get_params(candidate, fingerprint, vin=""): - # kg of standard extra cargo to count for drive, gas, etc... - std_cargo = 136 - ret = car.CarParams.new_message() ret.carName = "hyundai" ret.carFingerprint = candidate ret.carVin = vin ret.radarOffCan = True - ret.safetyModel = car.CarParams.SafetyModels.hyundai + ret.safetyModel = car.CarParams.SafetyModel.hyundai ret.enableCruise = True # stock acc # FIXME: hardcoding honda civic 2016 touring params so they can be used to # scale unknown params for other cars - mass_civic = 2923 * CV.LB_TO_KG + std_cargo + mass_civic = 2923. * CV.LB_TO_KG + STD_CARGO_KG wheelbase_civic = 2.70 centerToFront_civic = wheelbase_civic * 0.4 centerToRear_civic = wheelbase_civic - centerToFront_civic @@ -70,7 +67,7 @@ class CarInterface(object): if candidate == CAR.SANTA_FE: ret.lateralTuning.pid.kf = 0.00005 - ret.mass = 3982 * CV.LB_TO_KG + std_cargo + ret.mass = 3982. * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.766 # Values from optimizer @@ -82,7 +79,7 @@ class CarInterface(object): ret.minSteerSpeed = 0. elif candidate == CAR.KIA_SORENTO: ret.lateralTuning.pid.kf = 0.00005 - ret.mass = 1985 + std_cargo + ret.mass = 1985. + STD_CARGO_KG ret.wheelbase = 2.78 ret.steerRatio = 14.4 * 1.1 # 10% higher at the center seems reasonable ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] @@ -90,7 +87,7 @@ class CarInterface(object): ret.minSteerSpeed = 0. elif candidate == CAR.ELANTRA: ret.lateralTuning.pid.kf = 0.00006 - ret.mass = 1275 + std_cargo + ret.mass = 1275. + STD_CARGO_KG ret.wheelbase = 2.7 ret.steerRatio = 13.73 #Spec tire_stiffness_factor = 0.385 @@ -99,7 +96,7 @@ class CarInterface(object): ret.minSteerSpeed = 32 * CV.MPH_TO_MS elif candidate == CAR.GENESIS: ret.lateralTuning.pid.kf = 0.00005 - ret.mass = 2060 + std_cargo + ret.mass = 2060. + STD_CARGO_KG ret.wheelbase = 3.01 ret.steerRatio = 16.5 ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] @@ -107,7 +104,7 @@ class CarInterface(object): ret.minSteerSpeed = 35 * CV.MPH_TO_MS elif candidate == CAR.KIA_OPTIMA: ret.lateralTuning.pid.kf = 0.00005 - ret.mass = 3558 * CV.LB_TO_KG + ret.mass = 3558. * CV.LB_TO_KG ret.wheelbase = 2.80 ret.steerRatio = 13.75 tire_stiffness_factor = 0.5 @@ -115,7 +112,7 @@ class CarInterface(object): ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.25], [0.05]] elif candidate == CAR.KIA_STINGER: ret.lateralTuning.pid.kf = 0.00005 - ret.mass = 1825 + std_cargo + ret.mass = 1825. + STD_CARGO_KG ret.wheelbase = 2.78 ret.steerRatio = 14.4 * 1.15 # 15% higher at the center seems reasonable ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] @@ -174,13 +171,15 @@ class CarInterface(object): def update(self, c): # ******************* do can recv ******************* canMonoTimes = [] - can_rcv_error = not self.cp.update(int(sec_since_boot() * 1e9), True) - cam_rcv_error = not self.cp_cam.update(int(sec_since_boot() * 1e9), False) - can_rcv_error = can_rcv_error or cam_rcv_error + can_rcv_valid, _ = self.cp.update(int(sec_since_boot() * 1e9), True) + cam_rcv_valid, _ = self.cp_cam.update(int(sec_since_boot() * 1e9), False) self.CS.update(self.cp, self.cp_cam) # create message ret = car.CarState.new_message() + + ret.canValid = can_rcv_valid and cam_rcv_valid and self.cp.can_valid # TODO: check cp_cam validity + # speeds ret.vEgo = self.CS.v_ego ret.vEgoRaw = self.CS.v_ego_raw @@ -247,23 +246,13 @@ class CarInterface(object): ret.doorOpen = not self.CS.door_all_closed ret.seatbeltUnlatched = not self.CS.seatbelt - # low speed steer alert hysteresis logic (only for cars with steer cut off above 10 m/s) if ret.vEgo < (self.CP.minSteerSpeed + 2.) and self.CP.minSteerSpeed > 10.: self.low_speed_alert = True if ret.vEgo > (self.CP.minSteerSpeed + 4.): self.low_speed_alert = False - # events events = [] - if not self.CS.can_valid: - self.can_invalid_count += 1 - else: - self.can_invalid_count = 0 - - if can_rcv_error or self.can_invalid_count >= 5: - events.append(create_event('commIssue', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE])) - if not ret.gearShifter == 'drive': events.append(create_event('wrongGear', [ET.NO_ENTRY, ET.SOFT_DISABLE])) if ret.doorOpen: diff --git a/selfdrive/car/mock/interface.py b/selfdrive/car/mock/interface.py index a14e4f0be9..a18d2bf244 100755 --- a/selfdrive/car/mock/interface.py +++ b/selfdrive/car/mock/interface.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -import zmq from cereal import car from selfdrive.config import Conversions as CV from selfdrive.services import service_list @@ -21,11 +20,10 @@ class CarInterface(object): self.CC = CarController cloudlog.debug("Using Mock Car Interface") - context = zmq.Context() # TODO: subscribe to phone sensor - self.sensor = messaging.sub_sock(context, service_list['sensorEvents'].port) - self.gps = messaging.sub_sock(context, service_list['gpsLocation'].port) + self.sensor = messaging.sub_sock(service_list['sensorEvents'].port) + self.gps = messaging.sub_sock(service_list['gpsLocation'].port) self.speed = 0. self.prev_speed = 0. @@ -50,7 +48,7 @@ class CarInterface(object): ret.carName = "mock" ret.carFingerprint = candidate - ret.safetyModel = car.CarParams.SafetyModels.noOutput + ret.safetyModel = car.CarParams.SafetyModel.noOutput ret.openpilotLongitudinalControl = False # FIXME: hardcoding honda civic 2016 touring params so they can be used to diff --git a/selfdrive/car/subaru/carcontroller.py b/selfdrive/car/subaru/carcontroller.py index 83dbbd7c5a..95e0013faa 100644 --- a/selfdrive/car/subaru/carcontroller.py +++ b/selfdrive/car/subaru/carcontroller.py @@ -1,5 +1,4 @@ #from common.numpy_fast import clip -from common.realtime import sec_since_boot from selfdrive.car import apply_std_steer_torque_limits from selfdrive.car.subaru import subarucan from selfdrive.car.subaru.values import CAR, DBC @@ -21,7 +20,6 @@ class CarControllerParams(): class CarController(object): def __init__(self, car_fingerprint): - self.start_time = sec_since_boot() self.lkas_active = False self.steer_idx = 0 self.apply_steer_last = 0 diff --git a/selfdrive/car/subaru/carstate.py b/selfdrive/car/subaru/carstate.py index 0d5deec011..9a92777548 100644 --- a/selfdrive/car/subaru/carstate.py +++ b/selfdrive/car/subaru/carstate.py @@ -106,9 +106,6 @@ class CarState(object): def update(self, cp, cp_cam): - self.can_valid = cp.can_valid - self.cam_can_valid = cp_cam.can_valid - self.pedal_gas = cp.vl["Throttle"]['Throttle_Pedal'] self.brake_pressure = cp.vl["Brake_Pedal"]['Brake_Pedal'] self.user_gas_pressed = self.pedal_gas > 0 diff --git a/selfdrive/car/subaru/interface.py b/selfdrive/car/subaru/interface.py index 874745a66f..a609ee9092 100644 --- a/selfdrive/car/subaru/interface.py +++ b/selfdrive/car/subaru/interface.py @@ -6,6 +6,7 @@ from selfdrive.controls.lib.drive_helpers import create_event, EventTypes as ET from selfdrive.controls.lib.vehicle_model import VehicleModel from selfdrive.car.subaru.values import CAR from selfdrive.car.subaru.carstate import CarState, get_powertrain_can_parser, get_camera_can_parser +from selfdrive.car import STD_CARGO_KG class CarInterface(object): @@ -13,7 +14,6 @@ class CarInterface(object): self.CP = CP self.frame = 0 - self.can_invalid_count = 0 self.acc_active_prev = 0 self.gas_pressed_prev = False @@ -44,18 +44,17 @@ class CarInterface(object): ret.carName = "subaru" ret.carFingerprint = candidate ret.carVin = vin - ret.safetyModel = car.CarParams.SafetyModels.subaru + ret.safetyModel = car.CarParams.SafetyModel.subaru ret.enableCruise = True ret.steerLimitAlert = True ret.enableCamera = True - std_cargo = 136 ret.steerRateCost = 0.7 if candidate in [CAR.IMPREZA]: - ret.mass = 1568 + std_cargo + ret.mass = 1568. + STD_CARGO_KG ret.wheelbase = 2.67 ret.centerToFront = ret.wheelbase * 0.5 ret.steerRatio = 15 @@ -87,7 +86,7 @@ class CarInterface(object): # hardcoding honda civic 2016 touring params so they can be used to # scale unknown params for other cars - mass_civic = 2923./2.205 + std_cargo + mass_civic = 2923. * CV.LB_TO_KG + STD_CARGO_KG wheelbase_civic = 2.70 centerToFront_civic = wheelbase_civic * 0.4 centerToRear_civic = wheelbase_civic - centerToFront_civic @@ -114,15 +113,16 @@ class CarInterface(object): # returns a car.CarState def update(self, c): - can_rcv_error = not self.pt_cp.update(int(sec_since_boot() * 1e9), True) - cam_rcv_error = not self.cam_cp.update(int(sec_since_boot() * 1e9), False) - can_rcv_error = can_rcv_error or cam_rcv_error + can_rcv_valid, _ = self.pt_cp.update(int(sec_since_boot() * 1e9), True) + cam_rcv_valid, _ = self.cam_cp.update(int(sec_since_boot() * 1e9), False) self.CS.update(self.pt_cp, self.cam_cp) # create message ret = car.CarState.new_message() + ret.canValid = can_rcv_valid and cam_rcv_valid and self.pt_cp.can_valid and self.cam_cp.can_valid + # speeds ret.vEgo = self.CS.v_ego ret.aEgo = self.CS.a_ego @@ -177,14 +177,6 @@ class CarInterface(object): events = [] - if not self.CS.can_valid: - self.can_invalid_count += 1 - else: - self.can_invalid_count = 0 - - if can_rcv_error or self.can_invalid_count >= 5: - events.append(create_event('commIssue', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE])) - if ret.seatbeltUnlatched: events.append(create_event('seatbeltNotLatched', [ET.NO_ENTRY, ET.SOFT_DISABLE])) diff --git a/selfdrive/car/toyota/carcontroller.py b/selfdrive/car/toyota/carcontroller.py index 91bcb677a5..c6ffe0ea1e 100644 --- a/selfdrive/car/toyota/carcontroller.py +++ b/selfdrive/car/toyota/carcontroller.py @@ -6,7 +6,7 @@ from selfdrive.car.toyota.toyotacan import make_can_msg, create_video_target,\ create_steer_command, create_ui_command, \ create_ipas_steer_command, create_accel_command, \ create_fcw_command -from selfdrive.car.toyota.values import ECU, STATIC_MSGS, TSSP2_CAR +from selfdrive.car.toyota.values import ECU, STATIC_MSGS, TSS2_CAR from selfdrive.can.packer import CANPacker VisualAlert = car.CarControl.HUDControl.VisualAlert @@ -248,7 +248,7 @@ class CarController(object): if (frame % 100 == 0 or send_ui) and ECU.CAM in self.fake_ecus: can_sends.append(create_ui_command(self.packer, steer, sound1, sound2, left_line, right_line, left_lane_depart, right_lane_depart)) - if frame % 100 == 0 and ECU.DSU in self.fake_ecus and self.car_fingerprint not in TSSP2_CAR: + if frame % 100 == 0 and ECU.DSU in self.fake_ecus and self.car_fingerprint not in TSS2_CAR: can_sends.append(create_fcw_command(self.packer, fcw)) #*** static msgs *** diff --git a/selfdrive/car/toyota/carstate.py b/selfdrive/car/toyota/carstate.py index cdb735d4fc..9994e793dd 100644 --- a/selfdrive/car/toyota/carstate.py +++ b/selfdrive/car/toyota/carstate.py @@ -1,8 +1,9 @@ import numpy as np from common.kalman.simple_kalman import KF1D -from selfdrive.can.parser import CANParser, CANDefine +from selfdrive.can.parser import CANParser +from selfdrive.can.can_define import CANDefine from selfdrive.config import Conversions as CV -from selfdrive.car.toyota.values import CAR, DBC, STEER_THRESHOLD +from selfdrive.car.toyota.values import CAR, DBC, STEER_THRESHOLD, NO_DSU_CAR def parse_gear_shifter(gear, vals): @@ -31,10 +32,8 @@ def get_can_parser(CP): ("DOOR_OPEN_RR", "SEATS_DOORS", 1), ("SEATBELT_DRIVER_UNLATCHED", "SEATS_DOORS", 1), ("TC_DISABLED", "ESP_CONTROL", 1), - ("STEER_ANGLE", "STEER_ANGLE_SENSOR", 0), ("STEER_FRACTION", "STEER_ANGLE_SENSOR", 0), ("STEER_RATE", "STEER_ANGLE_SENSOR", 0), - ("GAS_RELEASED", "PCM_CRUISE", 0), ("CRUISE_ACTIVE", "PCM_CRUISE", 0), ("CRUISE_STATE", "PCM_CRUISE", 0), ("MAIN_ON", "PCM_CRUISE_2", 0), @@ -60,6 +59,11 @@ def get_can_parser(CP): ("EPS_STATUS", 25), ] + if CP.carFingerprint in NO_DSU_CAR: + signals += [("STEER_ANGLE", "STEER_TORQUE_SENSOR", 0)] + else: + signals += [("STEER_ANGLE", "STEER_ANGLE_SENSOR", 0)] + if CP.carFingerprint == CAR.PRIUS: signals += [("STATE", "AUTOPARK_STATUS", 0)] @@ -103,11 +107,7 @@ class CarState(object): K=[[0.12287673], [0.29666309]]) self.v_ego = 0.0 - def update(self, cp, cp_cam): - # copy can_valid - self.can_valid = cp.can_valid - self.cam_can_valid = cp_cam.can_valid - + def update(self, cp): # update prevs, update must run once per loop self.prev_left_blinker_on = self.left_blinker_on self.prev_right_blinker_on = self.right_blinker_on @@ -141,7 +141,10 @@ class CarState(object): self.a_ego = float(v_ego_x[1]) self.standstill = not v_wheel > 0.001 - self.angle_steers = cp.vl["STEER_ANGLE_SENSOR"]['STEER_ANGLE'] + cp.vl["STEER_ANGLE_SENSOR"]['STEER_FRACTION'] + if self.CP.carFingerprint in NO_DSU_CAR: + self.angle_steers = cp.vl["STEER_TORQUE_SENSOR"]['STEER_ANGLE'] + else: + self.angle_steers = cp.vl["STEER_ANGLE_SENSOR"]['STEER_ANGLE'] + cp.vl["STEER_ANGLE_SENSOR"]['STEER_FRACTION'] self.angle_steers_rate = cp.vl["STEER_ANGLE_SENSOR"]['STEER_RATE'] can_gear = int(cp.vl["GEAR_PACKET"]['GEAR']) self.gear_shifter = parse_gear_shifter(can_gear, self.shifter_values) @@ -163,7 +166,6 @@ class CarState(object): self.v_cruise_pcm = cp.vl["PCM_CRUISE_2"]['SET_SPEED'] self.pcm_acc_status = cp.vl["PCM_CRUISE"]['CRUISE_STATE'] self.pcm_acc_active = bool(cp.vl["PCM_CRUISE"]['CRUISE_ACTIVE']) - self.gas_pressed = not cp.vl["PCM_CRUISE"]['GAS_RELEASED'] self.low_speed_lockout = cp.vl["PCM_CRUISE_2"]['LOW_SPEED_LOCKOUT'] == 2 self.brake_lights = bool(cp.vl["ESP_CONTROL"]['BRAKE_LIGHTS_ACC'] or self.brake_pressed) if self.CP.carFingerprint == CAR.PRIUS: diff --git a/selfdrive/car/toyota/interface.py b/selfdrive/car/toyota/interface.py index 71ace4c1f6..83bf921d95 100755 --- a/selfdrive/car/toyota/interface.py +++ b/selfdrive/car/toyota/interface.py @@ -6,6 +6,7 @@ from selfdrive.controls.lib.drive_helpers import EventTypes as ET, create_event from selfdrive.controls.lib.vehicle_model import VehicleModel from selfdrive.car.toyota.carstate import CarState, get_can_parser, get_cam_can_parser from selfdrive.car.toyota.values import ECU, check_ecu_msgs, CAR, NO_STOP_TIMER_CAR +from selfdrive.car import STD_CARGO_KG from selfdrive.swaglog import cloudlog @@ -17,8 +18,6 @@ class CarInterface(object): self.frame = 0 self.gas_pressed_prev = False self.brake_pressed_prev = False - self.can_invalid_count = 0 - self.cam_can_valid_count = 0 self.cruise_enabled_prev = False # *** init the major players *** @@ -44,23 +43,20 @@ class CarInterface(object): @staticmethod def get_params(candidate, fingerprint, vin=""): - # kg of standard extra cargo to count for drive, gas, etc... - std_cargo = 136 - ret = car.CarParams.new_message() ret.carName = "toyota" ret.carFingerprint = candidate ret.carVin = vin - ret.safetyModel = car.CarParams.SafetyModels.toyota + ret.safetyModel = car.CarParams.SafetyModel.toyota # pedal ret.enableCruise = not ret.enableGasInterceptor # FIXME: hardcoding honda civic 2016 touring params so they can be used to # scale unknown params for other cars - mass_civic = 2923 * CV.LB_TO_KG + std_cargo + mass_civic = 2923. * CV.LB_TO_KG + STD_CARGO_KG wheelbase_civic = 2.70 centerToFront_civic = wheelbase_civic * 0.4 centerToRear_civic = wheelbase_civic - centerToFront_civic @@ -79,7 +75,7 @@ class CarInterface(object): ret.wheelbase = 2.70 ret.steerRatio = 15.00 # unknown end-to-end spec tire_stiffness_factor = 0.6371 # hand-tune - ret.mass = 3045 * CV.LB_TO_KG + std_cargo + ret.mass = 3045. * CV.LB_TO_KG + STD_CARGO_KG ret.lateralTuning.init('indi') ret.lateralTuning.indi.innerLoopGain = 4.0 @@ -88,96 +84,105 @@ class CarInterface(object): ret.lateralTuning.indi.actuatorEffectiveness = 1.0 ret.steerActuatorDelay = 0.5 - ret.steerRateCost = 0.5 elif candidate in [CAR.RAV4, CAR.RAV4H]: stop_and_go = True if (candidate in CAR.RAV4H) else False - ret.safetyParam = 73 # see conversion factor for STEER_TORQUE_EPS in dbc file + ret.safetyParam = 73 ret.wheelbase = 2.65 ret.steerRatio = 16.30 # 14.5 is spec end-to-end tire_stiffness_factor = 0.5533 - ret.mass = 3650 * CV.LB_TO_KG + std_cargo # mean between normal and hybrid + ret.mass = 3650. * CV.LB_TO_KG + STD_CARGO_KG # mean between normal and hybrid ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.6], [0.05]] ret.lateralTuning.pid.kf = 0.00006 # full torque for 10 deg at 80mph means 0.00007818594 elif candidate == CAR.COROLLA: stop_and_go = False - ret.safetyParam = 100 # see conversion factor for STEER_TORQUE_EPS in dbc file + ret.safetyParam = 100 ret.wheelbase = 2.70 ret.steerRatio = 17.8 tire_stiffness_factor = 0.444 - ret.mass = 2860 * CV.LB_TO_KG + std_cargo # mean between normal and hybrid + ret.mass = 2860. * CV.LB_TO_KG + STD_CARGO_KG # mean between normal and hybrid ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.2], [0.05]] ret.lateralTuning.pid.kf = 0.00003 # full torque for 20 deg at 80mph means 0.00007818594 elif candidate == CAR.LEXUS_RXH: stop_and_go = True - ret.safetyParam = 100 # see conversion factor for STEER_TORQUE_EPS in dbc file + ret.safetyParam = 73 ret.wheelbase = 2.79 ret.steerRatio = 16. # 14.8 is spec end-to-end tire_stiffness_factor = 0.444 # not optimized yet - ret.mass = 4481 * CV.LB_TO_KG + std_cargo # mean between min and max + ret.mass = 4481. * CV.LB_TO_KG + STD_CARGO_KG # mean between min and max ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.6], [0.1]] ret.lateralTuning.pid.kf = 0.00006 # full torque for 10 deg at 80mph means 0.00007818594 elif candidate in [CAR.CHR, CAR.CHRH]: stop_and_go = True - ret.safetyParam = 100 + ret.safetyParam = 73 ret.wheelbase = 2.63906 ret.steerRatio = 13.6 tire_stiffness_factor = 0.7933 - ret.mass = 3300. * CV.LB_TO_KG + std_cargo + ret.mass = 3300. * CV.LB_TO_KG + STD_CARGO_KG ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.723], [0.0428]] ret.lateralTuning.pid.kf = 0.00006 elif candidate in [CAR.CAMRY, CAR.CAMRYH]: stop_and_go = True - ret.safetyParam = 100 + ret.safetyParam = 73 ret.wheelbase = 2.82448 ret.steerRatio = 13.7 tire_stiffness_factor = 0.7933 - ret.mass = 3400 * CV.LB_TO_KG + std_cargo #mean between normal and hybrid + ret.mass = 3400. * CV.LB_TO_KG + STD_CARGO_KG #mean between normal and hybrid ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.6], [0.1]] ret.lateralTuning.pid.kf = 0.00006 elif candidate in [CAR.HIGHLANDER, CAR.HIGHLANDERH]: stop_and_go = True - ret.safetyParam = 100 + ret.safetyParam = 73 ret.wheelbase = 2.78 ret.steerRatio = 16.0 tire_stiffness_factor = 0.444 # not optimized yet - ret.mass = 4607 * CV.LB_TO_KG + std_cargo #mean between normal and hybrid limited + ret.mass = 4607. * CV.LB_TO_KG + STD_CARGO_KG #mean between normal and hybrid limited ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.6], [0.05]] ret.lateralTuning.pid.kf = 0.00006 elif candidate == CAR.AVALON: stop_and_go = False - ret.safetyParam = 73 # see conversion factor for STEER_TORQUE_EPS in dbc file + ret.safetyParam = 73 ret.wheelbase = 2.82 ret.steerRatio = 14.8 #Found at https://pressroom.toyota.com/releases/2016+avalon+product+specs.download tire_stiffness_factor = 0.7983 - ret.mass = 3505 * CV.LB_TO_KG + std_cargo # mean between normal and hybrid + ret.mass = 3505. * CV.LB_TO_KG + STD_CARGO_KG # mean between normal and hybrid ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.17], [0.03]] ret.lateralTuning.pid.kf = 0.00006 - elif candidate == CAR.RAV4_2019: + elif candidate == CAR.RAV4_TSS2: stop_and_go = True - ret.safetyParam = 100 + ret.safetyParam = 73 ret.wheelbase = 2.68986 ret.steerRatio = 14.3 tire_stiffness_factor = 0.7933 - ret.mass = 3370. * CV.LB_TO_KG + std_cargo - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.3], [0.05]] + ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.6], [0.1]] + ret.mass = 3370. * CV.LB_TO_KG + STD_CARGO_KG ret.lateralTuning.pid.kf = 0.00007818594 - elif candidate == CAR.COROLLA_HATCH: + elif candidate == CAR.COROLLA_TSS2: stop_and_go = True - ret.safetyParam = 100 + ret.safetyParam = 73 ret.wheelbase = 2.63906 ret.steerRatio = 13.9 tire_stiffness_factor = 0.444 - ret.mass = 3060. * CV.LB_TO_KG + std_cargo - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.3], [0.05]] + ret.mass = 3060. * CV.LB_TO_KG + STD_CARGO_KG + ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.6], [0.1]] + ret.lateralTuning.pid.kf = 0.00007818594 + + elif candidate == CAR.LEXUS_ESH_TSS2: + stop_and_go = True + ret.safetyParam = 73 + ret.wheelbase = 2.8702 + ret.steerRatio = 16.0 #not optimized + tire_stiffness_factor = 0.444 + ret.mass = 3704. * CV.LB_TO_KG + STD_CARGO_KG + ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.6], [0.1]] ret.lateralTuning.pid.kf = 0.00007818594 ret.steerRateCost = 1. @@ -251,18 +256,19 @@ class CarInterface(object): # ******************* do can recv ******************* canMonoTimes = [] - can_valid, _ = self.cp.update(int(sec_since_boot() * 1e9), True) - can_rcv_error = not can_valid + can_rcv_valid, _ = self.cp.update(int(sec_since_boot() * 1e9), True) # run the cam can update for 10s as we just need to know if the camera is alive if self.frame < 1000: self.cp_cam.update(int(sec_since_boot() * 1e9), False) - self.CS.update(self.cp, self.cp_cam) + self.CS.update(self.cp) # create message ret = car.CarState.new_message() + ret.canValid = can_rcv_valid and self.cp.can_valid + # speeds ret.vEgo = self.CS.v_ego ret.vEgoRaw = self.CS.v_ego_raw @@ -335,18 +341,8 @@ class CarInterface(object): # events events = [] - if not self.CS.can_valid: - self.can_invalid_count += 1 - else: - self.can_invalid_count = 0 - - if can_rcv_error or self.can_invalid_count >= 5: - events.append(create_event('commIssue', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE])) - - if self.CS.cam_can_valid: - self.cam_can_valid_count += 1 - if self.cam_can_valid_count >= 5: - self.forwarding_camera = True + if self.cp_cam.can_valid: + self.forwarding_camera = True if not ret.gearShifter == 'drive' and self.CP.enableDsu: events.append(create_event('wrongGear', [ET.NO_ENTRY, ET.SOFT_DISABLE])) diff --git a/selfdrive/car/toyota/radar_interface.py b/selfdrive/car/toyota/radar_interface.py index b8628c5bb1..c160e751aa 100755 --- a/selfdrive/car/toyota/radar_interface.py +++ b/selfdrive/car/toyota/radar_interface.py @@ -1,18 +1,15 @@ #!/usr/bin/env python import os -import zmq import time from selfdrive.can.parser import CANParser from cereal import car from common.realtime import sec_since_boot -from selfdrive.services import service_list -import selfdrive.messaging as messaging -from selfdrive.car.toyota.values import NO_DSU_CAR, DBC, TSSP2_CAR +from selfdrive.car.toyota.values import NO_DSU_CAR, DBC, TSS2_CAR def _create_radar_can_parser(car_fingerprint): dbc_f = DBC[car_fingerprint]['radar'] - if car_fingerprint in TSSP2_CAR: + if car_fingerprint in TSS2_CAR: RADAR_A_MSGS = list(range(0x180, 0x190)) RADAR_B_MSGS = list(range(0x190, 0x1a0)) else: @@ -39,7 +36,7 @@ class RadarInterface(object): self.delay = 0.0 # Delay of radar - if CP.carFingerprint in TSSP2_CAR: + if CP.carFingerprint in TSS2_CAR: self.RADAR_A_MSGS = list(range(0x180, 0x190)) self.RADAR_B_MSGS = list(range(0x190, 0x1a0)) else: @@ -49,17 +46,15 @@ class RadarInterface(object): self.valid_cnt = {key: 0 for key in self.RADAR_A_MSGS} self.rcp = _create_radar_can_parser(CP.carFingerprint) - self.no_dsu_car = CP.carFingerprint in NO_DSU_CAR - - context = zmq.Context() - self.logcan = messaging.sub_sock(context, service_list['can'].port) + # No radar dbc for cars without DSU which are not TSS 2.0 + # TODO: make a adas dbc file for dsu-less models + self.no_radar = CP.carFingerprint in NO_DSU_CAR and CP.carFingerprint not in TSS2_CAR def update(self): ret = car.RadarData.new_message() - if self.no_dsu_car: - # TODO: make a adas dbc file for dsu-less models + if self.no_radar: time.sleep(0.05) return ret @@ -74,7 +69,7 @@ class RadarInterface(object): errors = [] if not self.rcp.can_valid: - errors.append("commIssue") + errors.append("canError") ret.errors = errors ret.canMonoTimes = canMonoTimes diff --git a/selfdrive/car/toyota/toyotacan.py b/selfdrive/car/toyota/toyotacan.py index 85b8dce8d7..7de38c8914 100644 --- a/selfdrive/car/toyota/toyotacan.py +++ b/selfdrive/car/toyota/toyotacan.py @@ -64,6 +64,22 @@ def create_steer_command(packer, steer, steer_req, raw_cnt): return packer.make_can_msg("STEERING_LKA", 0, values) +def create_lta_steer_command(packer, steer, steer_req, raw_cnt, angle): + """Creates a CAN message for the Toyota LTA Steer Command.""" + + values = { + "COUNTER": raw_cnt, + "SETME_X3": 3, + "PERCENTAGE" : 100, + "SETME_X64": 0x64, + "ANGLE": angle, + "STEER_ANGLE_CMD": steer, + "STEER_REQUEST": steer_req, + "BIT": 0, + } + return packer.make_can_msg("STEERING_LTA", 0, values) + + def create_accel_command(packer, accel, pcm_cancel, standstill_req, lead): # TODO: find the exact canceling bit that does not create a chime values = { diff --git a/selfdrive/car/toyota/values.py b/selfdrive/car/toyota/values.py index b3c5a11fa7..f487888424 100644 --- a/selfdrive/car/toyota/values.py +++ b/selfdrive/car/toyota/values.py @@ -13,8 +13,9 @@ class CAR: HIGHLANDER = "TOYOTA HIGHLANDER 2017" HIGHLANDERH = "TOYOTA HIGHLANDER HYBRID 2018" AVALON = "TOYOTA AVALON 2016" - RAV4_2019 = "TOYOTA RAV4 2019" - COROLLA_HATCH = "TOYOTA COROLLA HATCH 2019" + RAV4_TSS2 = "TOYOTA RAV4 2019" + COROLLA_TSS2 = "TOYOTA COROLLA TSS2 2019" + LEXUS_ESH_TSS2 = "LEXUS ES 300H 2019" class ECU: @@ -159,7 +160,7 @@ FINGERPRINTS = { CAR.AVALON: [{ 36: 8, 37: 8, 170: 8, 180: 8, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 547: 8, 550: 8, 552: 4, 562: 6, 608: 8, 610: 5, 643: 7, 705: 8, 740: 5, 800: 8, 835: 8, 836: 8, 849: 4, 869: 7, 870: 7, 871: 2, 896: 8, 897: 8, 905: 8, 911: 1, 916: 2, 921: 8, 933: 6, 944: 8, 945: 8, 951: 8, 955: 8, 956: 8, 979: 2, 1005: 2, 1014: 8, 1017: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1059: 1, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1176: 8, 1177: 8, 1178: 8, 1179: 8, 1180: 8, 1181: 8, 1190: 8, 1191: 8, 1192: 8, 1196: 8, 1200: 8, 1201: 8, 1202: 8, 1203: 8, 1206: 8, 1227: 8, 1235: 8, 1237: 8, 1264: 8, 1279: 8, 1552: 8, 1553: 8, 1554: 8, 1555: 8, 1556: 8, 1557: 8, 1558: 8, 1561: 8, 1562: 8, 1568: 8, 1569: 8, 1570: 8, 1571: 8, 1572: 8, 1584: 8, 1589: 8, 1592: 8, 1593: 8, 1595: 8, 1596: 8, 1597: 8, 1664: 8, 1728: 8, 1779: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8 }], - CAR.RAV4_2019: [ + CAR.RAV4_TSS2: [ # LE { 36: 8, 37: 8, 170: 8, 180: 8, 186: 4, 355: 5, 401: 8, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 544: 4, 550: 8, 552: 4, 562: 6, 565: 8, 608: 8, 610: 8, 643: 7, 705: 8, 728: 8, 740: 5, 742: 8, 743: 8, 761: 8, 764: 8, 765: 8, 800: 8, 810: 2, 812: 8, 824: 8, 829: 2, 830: 7, 835: 8, 836: 8, 865: 8, 869: 7, 870: 7, 871: 2, 877: 8, 881: 8, 882: 8, 885: 8, 896: 8, 898: 8, 900: 6, 902: 6, 905: 8, 921: 8, 933: 8, 934: 8, 935: 8, 944: 8, 945: 8, 951: 8, 955: 8, 956: 8, 976: 1, 998: 5, 999: 7, 1000: 8, 1001: 8, 1002: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1059: 1, 1063: 8, 1076: 8, 1077: 8,1114: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1172: 8, 1235: 8, 1279: 8, 1541: 8, 1552: 8, 1553:8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1592: 8, 1594: 8, 1595: 8, 1649: 8, 1745: 8, 1775: 8, 1779: 8, 1786: 8, 1787: 8, 1788: 8, 1789: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8 @@ -168,30 +169,37 @@ FINGERPRINTS = { { 36: 8, 37: 8, 170: 8, 180: 8, 186: 4, 401: 8, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 544: 4, 550: 8, 552: 4, 562: 6, 565: 8, 608: 8, 610: 8, 643: 7, 658: 8, 705: 8, 728: 8, 740: 5, 742: 8, 743: 8, 761: 8, 764: 8, 765: 8, 800: 8, 810: 2, 812: 8, 814: 8, 818: 8, 822: 8, 824: 8, 829: 2, 830: 7, 835: 8, 836: 8, 865: 8, 869: 7, 870: 7, 871: 2, 877: 8, 881: 8, 882: 8, 885: 8, 889: 8, 891: 8, 896: 8, 898: 8, 900: 6, 902: 6, 905: 8, 918: 8, 921: 8, 933: 8, 934: 8, 935: 8, 944: 8, 945: 8, 951: 8, 955: 8, 956: 8, 976: 1, 987: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1002: 8, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1059: 1, 1063: 8, 1076: 8, 1077: 8, 1082: 8, 1084: 8, 1085: 8, 1086: 8, 1114: 8, 1132: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1172: 8, 1228: 8, 1235: 8, 1237: 8, 1263: 8, 1264: 8, 1279: 8, 1541: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1592: 8, 1594: 8, 1595: 8, 1649: 8, 1696: 8, 1745: 8, 1775: 8, 1779: 8, 1786: 8, 1787: 8, 1788: 8, 1789: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8 }], - CAR.COROLLA_HATCH: [{ - 36: 8, 37: 8, 114: 5, 170: 8, 180: 8, 186: 4, 401: 8, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 544: 4, 550: 8, 552: 4, 562: 6, 608: 8, 610: 8, 643: 7, 705: 8, 728: 8, 740: 5, 742: 8, 743: 8, 761: 8, 764: 8, 765: 8, 800: 8, 810: 2, 812: 8, 824: 8, 829: 2, 830: 7, 835: 8, 836: 8, 865: 8, 869: 7, 870: 7, 871: 2, 877: 8, 881: 8, 896: 8, 898: 8, 900: 6, 902: 6, 905: 8, 921: 8, 933: 8, 934: 8, 935: 8, 944: 8, 945: 8, 951: 8, 955: 8, 956: 8, 976: 1, 998: 5, 999: 7, 1000: 8, 1001: 8, 1002: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1059: 1, 1076: 8, 1077: 8, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1172: 8, 1235: 8, 1279: 8, 1541: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1592: 8, 1595: 8, 1649: 8, 1745: 8, 1775: 8, 1779: 8, 1786: 8, 1787: 8, 1788: 8, 1789: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8 - }] + CAR.COROLLA_TSS2: [ + # hatch 2019+ and sedan 2020+ + { + 36: 8, 37: 8, 114: 5, 170: 8, 180: 8, 186: 4, 401: 8, 426: 6, 452: 8, 464: 8, 466: 8, 467: 8, 544: 4, 550: 8, 552: 4, 562: 6, 608: 8, 610: 8, 643: 7, 705: 8, 728: 8, 740: 5, 742: 8, 743: 8, 761: 8, 764: 8, 765: 8, 800: 8, 810: 2, 812: 8, 824: 8, 829: 2, 830: 7, 835: 8, 836: 8, 865: 8, 869: 7, 870: 7, 871: 2, 877: 8, 881: 8, 896: 8, 898: 8, 900: 6, 902: 6, 905: 8, 921: 8, 933: 8, 934: 8, 935: 8, 944: 8, 945: 8, 951: 8, 955: 8, 956: 8, 976: 1, 998: 5, 999: 7, 1000: 8, 1001: 8, 1002: 8, 1014: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1044: 8, 1056: 8, 1059: 1, 1076: 8, 1077: 8, 1114: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1172: 8, 1235: 8, 1237: 8, 1279: 8, 1541: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1592: 8, 1595: 8, 1649: 8, 1745: 8, 1775: 8, 1779: 8, 1786: 8, 1787: 8, 1788: 8, 1789: 8, 1808: 8, 1809: 8, 1816: 8, 1817: 8, 1840: 8, 1848: 8, 1904: 8, 1912: 8, 1940: 8, 1941: 8, 1948: 8, 1949: 8, 1952: 8, 1960: 8, 1981: 8, 1986: 8, 1990: 8, 1994: 8, 1998: 8, 2004: 8 + }], + CAR.LEXUS_ESH_TSS2: [ + { + 36: 8, 37: 8, 166: 8, 170: 8, 180: 8, 295: 8, 296: 8, 401: 8, 426: 6, 452: 8, 466: 8, 467: 8, 550: 8, 552: 4, 560: 7, 562: 6, 581: 5, 608: 8, 610: 8, 643: 7, 658: 8, 713: 8, 728: 8, 740: 5, 742: 8, 743: 8, 744: 8, 761: 8, 764: 8, 765: 8, 800: 8, 810: 2, 812: 8, 814: 8, 818: 8, 824: 8, 829: 2, 830: 7, 835: 8, 836: 8, 863: 8, 865: 8, 869: 7, 870: 7, 871: 2, 877: 8, 881: 8, 882: 8, 885: 8, 889: 8, 896: 8, 898: 8, 900: 6, 902: 6, 905: 8, 913: 8, 918: 8, 921: 8, 933: 8, 934: 8, 935: 8, 944: 8, 945: 8, 950: 8, 951: 8, 953: 8, 955: 8, 956: 8, 971: 7, 975: 5, 987: 8, 993: 8, 998: 5, 999: 7, 1000: 8, 1001: 8, 1002: 8, 1017: 8, 1020: 8, 1041: 8, 1042: 8, 1056: 8, 1057: 8, 1059: 1, 1071: 8, 1076: 8, 1077: 8, 1082: 8, 1084: 8, 1085: 8, 1086: 8, 1114: 8, 1132: 8, 1161: 8, 1162: 8, 1163: 8, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1172: 8, 1228: 8, 1235: 8, 1264: 8, 1279: 8, 1541: 8, 1552: 8, 1553: 8, 1556: 8, 1557: 8, 1568: 8, 1570: 8, 1571: 8, 1572: 8, 1575: 8, 1592: 8, 1594: 8, 1595: 8, 1649: 8, 1696: 8, 1775: 8, 1777: 8, 1779: 8, 1786: 8, 1787: 8, 1788: 8, 1789: 8, 1904: 8, 1912: 8, 1990: 8, 1998: 8 + }], } STEER_THRESHOLD = 100 DBC = { - CAR.RAV4H: dbc_dict('toyota_rav4_hybrid_2017_pt_generated', 'toyota_prius_2017_adas'), - CAR.RAV4: dbc_dict('toyota_rav4_2017_pt_generated', 'toyota_prius_2017_adas'), - CAR.PRIUS: dbc_dict('toyota_prius_2017_pt_generated', 'toyota_prius_2017_adas'), - CAR.COROLLA: dbc_dict('toyota_corolla_2017_pt_generated', 'toyota_prius_2017_adas'), - CAR.LEXUS_RXH: dbc_dict('lexus_rx_hybrid_2017_pt_generated', 'toyota_prius_2017_adas'), - CAR.CHR: dbc_dict('toyota_chr_2018_pt_generated', 'toyota_prius_2017_adas'), - CAR.CHRH: dbc_dict('toyota_chr_hybrid_2018_pt_generated', 'toyota_prius_2017_adas'), - CAR.CAMRY: dbc_dict('toyota_chr_2018_pt_generated', 'toyota_prius_2017_adas'), - CAR.CAMRYH: dbc_dict('toyota_camry_hybrid_2018_pt_generated', 'toyota_prius_2017_adas'), - CAR.HIGHLANDER: dbc_dict('toyota_highlander_2017_pt_generated', 'toyota_prius_2017_adas'), - CAR.HIGHLANDERH: dbc_dict('toyota_highlander_hybrid_2018_pt_generated', 'toyota_prius_2017_adas'), - CAR.AVALON: dbc_dict('toyota_avalon_2017_pt_generated', 'toyota_prius_2017_adas'), - CAR.RAV4_2019: dbc_dict('toyota_chr_2018_pt_generated', 'toyota_rav4_2019_adas'), - CAR.COROLLA_HATCH: dbc_dict('toyota_chr_2018_pt_generated', 'toyota_rav4_2019_adas'), + CAR.RAV4H: dbc_dict('toyota_rav4_hybrid_2017_pt_generated', 'toyota_adas'), + CAR.RAV4: dbc_dict('toyota_rav4_2017_pt_generated', 'toyota_adas'), + CAR.PRIUS: dbc_dict('toyota_prius_2017_pt_generated', 'toyota_adas'), + CAR.COROLLA: dbc_dict('toyota_corolla_2017_pt_generated', 'toyota_adas'), + CAR.LEXUS_RXH: dbc_dict('lexus_rx_hybrid_2017_pt_generated', 'toyota_adas'), + CAR.CHR: dbc_dict('toyota_nodsu_pt_generated', 'toyota_adas'), + CAR.CHRH: dbc_dict('toyota_nodsu_hybrid_pt_generated', 'toyota_adas'), + CAR.CAMRY: dbc_dict('toyota_nodsu_pt_generated', 'toyota_adas'), + CAR.CAMRYH: dbc_dict('toyota_camry_hybrid_2018_pt_generated', 'toyota_adas'), + CAR.HIGHLANDER: dbc_dict('toyota_highlander_2017_pt_generated', 'toyota_adas'), + CAR.HIGHLANDERH: dbc_dict('toyota_highlander_hybrid_2018_pt_generated', 'toyota_adas'), + CAR.AVALON: dbc_dict('toyota_avalon_2017_pt_generated', 'toyota_adas'), + CAR.RAV4_TSS2: dbc_dict('toyota_nodsu_pt_generated', 'toyota_tss2_adas'), + CAR.COROLLA_TSS2: dbc_dict('toyota_nodsu_pt_generated', 'toyota_tss2_adas'), + CAR.LEXUS_ESH_TSS2: dbc_dict('toyota_nodsu_pt_generated', 'toyota_tss2_adas'), } -NO_DSU_CAR = [CAR.CHR, CAR.CHRH, CAR.CAMRY, CAR.CAMRYH] -TSSP2_CAR = [CAR.RAV4_2019, CAR.COROLLA_HATCH] -NO_STOP_TIMER_CAR = [CAR.RAV4H, CAR.HIGHLANDERH, CAR.HIGHLANDER, CAR.RAV4_2019, CAR.COROLLA_HATCH] # no resume button press required +NO_DSU_CAR = [CAR.CHR, CAR.CHRH, CAR.CAMRY, CAR.CAMRYH, CAR.RAV4_TSS2, CAR.COROLLA_TSS2, CAR.LEXUS_ESH_TSS2] +TSS2_CAR = [CAR.RAV4_TSS2, CAR.COROLLA_TSS2, CAR.LEXUS_ESH_TSS2] +NO_STOP_TIMER_CAR = [CAR.RAV4H, CAR.HIGHLANDERH, CAR.HIGHLANDER, CAR.RAV4_TSS2, CAR.COROLLA_TSS2, CAR.LEXUS_ESH_TSS2] # no resume button press required diff --git a/selfdrive/common/cereal.mk b/selfdrive/common/cereal.mk index 0a3958a23f..ed05efc08c 100644 --- a/selfdrive/common/cereal.mk +++ b/selfdrive/common/cereal.mk @@ -1,19 +1,15 @@ UNAME_M ?= $(shell uname -m) UNAME_S ?= $(shell uname -s) - - -CEREAL_CFLAGS = -I$(PHONELIBS)/capnp-c/include - ifeq ($(UNAME_S),Darwin) - +CEREAL_CFLAGS = -I$(PHONELIBS)/capnp-c/include CEREAL_CXXFLAGS = -I$(PHONELIBS)/capnp-cpp/mac/include CEREAL_LIBS = $(PHONELIBS)/capnp-cpp/mac/lib/libcapnp.a \ $(PHONELIBS)/capnp-cpp/mac/lib/libkj.a \ $(PHONELIBS)/capnp-c/mac/lib/libcapnp_c.a else ifeq ($(UNAME_M),x86_64) - +CEREAL_CFLAGS = -I$(PHONELIBS)/capnp-c/include CEREAL_CXXFLAGS = -I$(PHONELIBS)/capnp-cpp/include ifeq ($(CEREAL_LIBS),) CEREAL_LIBS = -L$(PHONELIBS)/capnp-cpp/x64/lib/ \ @@ -23,15 +19,12 @@ endif else -CEREAL_CXXFLAGS = -I$(PHONELIBS)/capnp-cpp/include +#CEREAL_CXXFLAGS = -I$(PHONELIBS)/capnp-cpp/include ifeq ($(CEREAL_LIBS),) - CEREAL_LIBS = -L$(PHONELIBS)/capnp-cpp/aarch64/lib/ \ - -L$(PHONELIBS)/capnp-c/aarch64/lib/ \ - -l:libcapn.a -l:libcapnp.a -l:libkj.a + CEREAL_LIBS = -l:libcapn.a -l:libcapnp.a -l:libkj.a endif endif - CEREAL_OBJS = ../../cereal/gen/c/log.capnp.o ../../cereal/gen/c/car.capnp.o log.capnp.o: ../../cereal/gen/cpp/log.capnp.c++ diff --git a/selfdrive/common/cqueue.c b/selfdrive/common/cqueue.c new file mode 100644 index 0000000000..fe2c6f4ebf --- /dev/null +++ b/selfdrive/common/cqueue.c @@ -0,0 +1,52 @@ +#include +#include +#include + +#include "cqueue.h" + +void queue_init(Queue *q) { + memset(q, 0, sizeof(*q)); + TAILQ_INIT(&q->q); + pthread_mutex_init(&q->lock, NULL); + pthread_cond_init(&q->cv, NULL); +} + +void* queue_pop(Queue *q) { + pthread_mutex_lock(&q->lock); + while (TAILQ_EMPTY(&q->q)) { + pthread_cond_wait(&q->cv, &q->lock); + } + QueueEntry *entry = TAILQ_FIRST(&q->q); + TAILQ_REMOVE(&q->q, entry, entries); + pthread_mutex_unlock(&q->lock); + + void* r = entry->data; + free(entry); + return r; +} + +void* queue_try_pop(Queue *q) { + pthread_mutex_lock(&q->lock); + + void* r = NULL; + if (!TAILQ_EMPTY(&q->q)) { + QueueEntry *entry = TAILQ_FIRST(&q->q); + TAILQ_REMOVE(&q->q, entry, entries); + r = entry->data; + free(entry); + } + + pthread_mutex_unlock(&q->lock); + return r; +} + +void queue_push(Queue *q, void *data) { + QueueEntry *entry = calloc(1, sizeof(QueueEntry)); + assert(entry); + entry->data = data; + + pthread_mutex_lock(&q->lock); + TAILQ_INSERT_TAIL(&q->q, entry, entries); + pthread_cond_signal(&q->cv); + pthread_mutex_unlock(&q->lock); +} diff --git a/selfdrive/common/cqueue.h b/selfdrive/common/cqueue.h new file mode 100644 index 0000000000..f2613660b2 --- /dev/null +++ b/selfdrive/common/cqueue.h @@ -0,0 +1,33 @@ +#ifndef COMMON_CQUEUE_H +#define COMMON_CQUEUE_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// a blocking queue + +typedef struct QueueEntry { + TAILQ_ENTRY(QueueEntry) entries; + void *data; +} QueueEntry; + +typedef struct Queue { + TAILQ_HEAD(queue, QueueEntry) q; + pthread_mutex_t lock; + pthread_cond_t cv; +} Queue; + +void queue_init(Queue *q); +void* queue_pop(Queue *q); +void* queue_try_pop(Queue *q); +void queue_push(Queue *q, void *data); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif diff --git a/selfdrive/common/modeldata.h b/selfdrive/common/modeldata.h index c3f48930f2..b5b38bafd8 100644 --- a/selfdrive/common/modeldata.h +++ b/selfdrive/common/modeldata.h @@ -1,18 +1,23 @@ #ifndef MODELDATA_H #define MODELDATA_H -#define MODEL_PATH_DISTANCE 50 +#define MODEL_PATH_DISTANCE 100 +#define POLYFIT_DEGREE 4 typedef struct PathData { float points[MODEL_PATH_DISTANCE]; float prob; float std; + float stds[MODEL_PATH_DISTANCE]; + float poly[POLYFIT_DEGREE]; } PathData; typedef struct LeadData { float dist; float prob; float std; + float rel_v; + float rel_v_std; } LeadData; typedef struct ModelData { diff --git a/selfdrive/common/mutex.h b/selfdrive/common/mutex.h new file mode 100644 index 0000000000..ef01359357 --- /dev/null +++ b/selfdrive/common/mutex.h @@ -0,0 +1,13 @@ +#ifndef COMMON_MUTEX_H +#define COMMON_MUTEX_H + +#include + +static inline void mutex_init_reentrant(pthread_mutex_t *mutex) { + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(mutex, &attr); +} + +#endif diff --git a/selfdrive/common/util.h b/selfdrive/common/util.h index 65dde16e24..b3ca916941 100644 --- a/selfdrive/common/util.h +++ b/selfdrive/common/util.h @@ -1,6 +1,7 @@ #ifndef COMMON_UTIL_H #define COMMON_UTIL_H +#include #ifndef __cplusplus diff --git a/selfdrive/common/version.h b/selfdrive/common/version.h index b925f41522..ad486deed5 100644 --- a/selfdrive/common/version.h +++ b/selfdrive/common/version.h @@ -1 +1 @@ -#define COMMA_VERSION "0.5.13-release" +#define COMMA_VERSION "0.6-release" diff --git a/selfdrive/controls/controlsd.py b/selfdrive/controls/controlsd.py index 8e27c7c3ba..f1c556ba12 100755 --- a/selfdrive/controls/controlsd.py +++ b/selfdrive/controls/controlsd.py @@ -1,12 +1,9 @@ #!/usr/bin/env python import gc -import zmq -import json -from collections import defaultdict - +import capnp from cereal import car, log from common.numpy_fast import clip -from common.realtime import sec_since_boot, set_realtime_priority, Ratekeeper +from common.realtime import sec_since_boot, set_realtime_priority, Ratekeeper, DT_CTRL from common.profiler import Profiler from common.params import Params import selfdrive.messaging as messaging @@ -15,8 +12,7 @@ from selfdrive.services import service_list from selfdrive.boardd.boardd import can_list_to_can_capnp from selfdrive.car.car_helpers import get_car, get_startup_alert from selfdrive.controls.lib.model_parser import CAMERA_OFFSET -from selfdrive.controls.lib.drive_helpers import learn_angle_model_bias, \ - get_events, \ +from selfdrive.controls.lib.drive_helpers import get_events, \ create_event, \ EventTypes as ET, \ update_v_cruise, \ @@ -27,7 +23,7 @@ from selfdrive.controls.lib.latcontrol_indi import LatControlINDI from selfdrive.controls.lib.alertmanager import AlertManager from selfdrive.controls.lib.vehicle_model import VehicleModel from selfdrive.controls.lib.driver_monitor import DriverStatus -from selfdrive.controls.lib.planner import _DT_MPC +from selfdrive.controls.lib.planner import LON_MPC_STEP from selfdrive.locationd.calibration_helpers import Calibration, Filter ThermalStatus = log.ThermalData.ThermalStatus @@ -43,10 +39,18 @@ def isEnabled(state): """Check if openpilot is engaged""" return (isActive(state) or state == State.preEnabled) +def events_to_bytes(events): + # optimization when comparing capnp structs: str() or tree traverse are much slower + ret = [] + for e in events: + if isinstance(e, capnp.lib.capnp._DynamicStructReader): + e = e.as_builder() + ret.append(e.to_bytes()) + return ret + -def data_sample(rcv_times, CI, CC, plan_sock, path_plan_sock, thermal, calibration, health, driver_monitor, - poller, cal_status, cal_perc, overtemp, free_space, low_battery, - driver_status, state, mismatch_counter, params, plan, path_plan): +def data_sample(CI, CC, sm, cal_status, cal_perc, overtemp, free_space, low_battery, + driver_status, state, mismatch_counter, params): """Receive data from sockets and create events for battery, temperature and disk space""" # Update carstate from CAN and create events @@ -54,33 +58,12 @@ def data_sample(rcv_times, CI, CC, plan_sock, path_plan_sock, thermal, calibrati events = list(CS.events) enabled = isEnabled(state) - # Receive from sockets - td = None - cal = None - hh = None - dm = None - - for socket, event in poller.poll(0): - msg = messaging.recv_one(socket) - rcv_times[msg.which()] = sec_since_boot() - - if socket is thermal: - td = msg - elif socket is calibration: - cal = msg - elif socket is health: - hh = msg - elif socket is driver_monitor: - dm = msg - elif socket is plan_sock: - plan = msg - elif socket is path_plan_sock: - path_plan = msg - - if td is not None: - overtemp = td.thermal.thermalStatus >= ThermalStatus.red - free_space = td.thermal.freeSpace < 0.07 # under 7% of space free no enable allowed - low_battery = td.thermal.batteryPercent < 1 and td.thermal.chargingError # at zero percent battery, while discharging, OP should not be allowed + sm.update(0) + + if sm.updated['thermal']: + overtemp = sm['thermal'].thermalStatus >= ThermalStatus.red + free_space = sm['thermal'].freeSpace < 0.07 # under 7% of space free no enable allowed + low_battery = sm['thermal'].batteryPercent < 1 and sm['thermal'].chargingError # at zero percent battery, while discharging, OP should not allowed # Create events for battery, temperature and disk space if low_battery: @@ -91,9 +74,9 @@ def data_sample(rcv_times, CI, CC, plan_sock, path_plan_sock, thermal, calibrati events.append(create_event('outOfSpace', [ET.NO_ENTRY])) # Handle calibration - if cal is not None: - cal_status = cal.liveCalibration.calStatus - cal_perc = cal.liveCalibration.calPerc + if sm.updated['liveCalibration']: + cal_status = sm['liveCalibration'].calStatus + cal_perc = sm['liveCalibration'].calPerc if cal_status != Calibration.CALIBRATED: if cal_status == Calibration.UNCALIBRATED: @@ -103,26 +86,26 @@ def data_sample(rcv_times, CI, CC, plan_sock, path_plan_sock, thermal, calibrati # When the panda and controlsd do not agree on controls_allowed # we want to disengage openpilot. However the status from the panda goes through - # another socket than the CAN messages, therefore one can arrive earlier than the other. + # another socket other than the CAN messages and one can arrive earlier than the other. # Therefore we allow a mismatch for two samples, then we trigger the disengagement. if not enabled: mismatch_counter = 0 - if hh is not None: - controls_allowed = hh.health.controlsAllowed + if sm.updated['health']: + controls_allowed = sm['health'].controlsAllowed if not controls_allowed and enabled: mismatch_counter += 1 if mismatch_counter >= 2: events.append(create_event('controlsMismatch', [ET.IMMEDIATE_DISABLE])) # Driver monitoring - if dm is not None: - driver_status.get_pose(dm.driverMonitoring, params) + if sm.updated['driverMonitoring']: + driver_status.get_pose(sm['driverMonitoring'], params) - return CS, events, cal_status, cal_perc, overtemp, free_space, low_battery, mismatch_counter, plan, path_plan + return CS, events, cal_status, cal_perc, overtemp, free_space, low_battery, mismatch_counter -def state_transition(CS, CP, state, events, soft_disable_timer, v_cruise_kph, AM): +def state_transition(frame, CS, CP, state, events, soft_disable_timer, v_cruise_kph, AM): """Compute conditional state transitions and execute actions on state transitions""" enabled = isEnabled(state) @@ -143,43 +126,43 @@ def state_transition(CS, CP, state, events, soft_disable_timer, v_cruise_kph, AM if get_events(events, [ET.ENABLE]): if get_events(events, [ET.NO_ENTRY]): for e in get_events(events, [ET.NO_ENTRY]): - AM.add(str(e) + "NoEntry", enabled) + AM.add(frame, str(e) + "NoEntry", enabled) else: if get_events(events, [ET.PRE_ENABLE]): state = State.preEnabled else: state = State.enabled - AM.add("enable", enabled) + AM.add(frame, "enable", enabled) v_cruise_kph = initialize_v_cruise(CS.vEgo, CS.buttonEvents, v_cruise_kph_last) # ENABLED elif state == State.enabled: if get_events(events, [ET.USER_DISABLE]): state = State.disabled - AM.add("disable", enabled) + AM.add(frame, "disable", enabled) elif get_events(events, [ET.IMMEDIATE_DISABLE]): state = State.disabled for e in get_events(events, [ET.IMMEDIATE_DISABLE]): - AM.add(e, enabled) + AM.add(frame, e, enabled) elif get_events(events, [ET.SOFT_DISABLE]): state = State.softDisabling soft_disable_timer = 300 # 3s for e in get_events(events, [ET.SOFT_DISABLE]): - AM.add(e, enabled) + AM.add(frame, e, enabled) # SOFT DISABLING elif state == State.softDisabling: if get_events(events, [ET.USER_DISABLE]): state = State.disabled - AM.add("disable", enabled) + AM.add(frame, "disable", enabled) elif get_events(events, [ET.IMMEDIATE_DISABLE]): state = State.disabled for e in get_events(events, [ET.IMMEDIATE_DISABLE]): - AM.add(e, enabled) + AM.add(frame, e, enabled) elif not get_events(events, [ET.SOFT_DISABLE]): # no more soft disabling condition, so go back to ENABLED @@ -187,7 +170,7 @@ def state_transition(CS, CP, state, events, soft_disable_timer, v_cruise_kph, AM elif get_events(events, [ET.SOFT_DISABLE]) and soft_disable_timer > 0: for e in get_events(events, [ET.SOFT_DISABLE]): - AM.add(e, enabled) + AM.add(frame, e, enabled) elif soft_disable_timer <= 0: state = State.disabled @@ -196,12 +179,12 @@ def state_transition(CS, CP, state, events, soft_disable_timer, v_cruise_kph, AM elif state == State.preEnabled: if get_events(events, [ET.USER_DISABLE]): state = State.disabled - AM.add("disable", enabled) + AM.add(frame, "disable", enabled) elif get_events(events, [ET.IMMEDIATE_DISABLE, ET.SOFT_DISABLE]): state = State.disabled for e in get_events(events, [ET.IMMEDIATE_DISABLE, ET.SOFT_DISABLE]): - AM.add(e, enabled) + AM.add(frame, e, enabled) elif not get_events(events, [ET.PRE_ENABLE]): state = State.enabled @@ -209,8 +192,8 @@ def state_transition(CS, CP, state, events, soft_disable_timer, v_cruise_kph, AM return state, soft_disable_timer, v_cruise_kph, v_cruise_kph_last -def state_control(rcv_times, plan, path_plan, CS, CP, state, events, v_cruise_kph, v_cruise_kph_last, AM, rk, - driver_status, LaC, LoC, VM, angle_model_bias, read_only, is_metric, cal_perc): +def state_control(frame, rcv_frame, plan, path_plan, CS, CP, state, events, v_cruise_kph, v_cruise_kph_last, + AM, rk, driver_status, LaC, LoC, VM, read_only, is_metric, cal_perc): """Given the state, this function returns an actuators packet""" actuators = car.CarControl.Actuators.new_message() @@ -228,7 +211,7 @@ def state_control(rcv_times, plan, path_plan, CS, CP, state, events, v_cruise_kp # send FCW alert if triggered by planner if plan.fcw: - AM.add("fcw", enabled) + AM.add(frame, "fcw", enabled) # State specific actions @@ -245,20 +228,12 @@ def state_control(rcv_times, plan, path_plan, CS, CP, state, events, v_cruise_kp extra_text = str(int(round(CP.minSteerSpeed * CV.MS_TO_KPH))) + " kph" else: extra_text = str(int(round(CP.minSteerSpeed * CV.MS_TO_MPH))) + " mph" - AM.add(e, enabled, extra_text_2=extra_text) + AM.add(frame, e, enabled, extra_text_2=extra_text) - # Run angle offset learner at 20 Hz - if rk.frame % 5 == 2: - angle_model_bias = learn_angle_model_bias(active, CS.vEgo, angle_model_bias, - path_plan.cPoly, path_plan.cProb, CS.steeringAngle, - CS.steeringPressed) + plan_age = DT_CTRL * (frame - rcv_frame['plan']) + dt = min(plan_age, LON_MPC_STEP + DT_CTRL) + DT_CTRL # no greater than dt mpc + dt, to prevent too high extraps - cur_time = sec_since_boot() - radar_time = rcv_times['plan'] - plan.processingDelay # Subtract processing delay to get the original measurement time - _DT = 0.01 # 100Hz - - dt = min(cur_time - radar_time, _DT_MPC + _DT) + _DT # no greater than dt mpc + dt, to prevent too high extraps - a_acc_sol = plan.aStart + (dt / _DT_MPC) * (plan.aTarget - plan.aStart) + a_acc_sol = plan.aStart + (dt / LON_MPC_STEP) * (plan.aTarget - plan.aStart) v_acc_sol = plan.vStart + dt * (a_acc_sol + plan.aStart) / 2.0 # Gas/Brake PID loop @@ -270,7 +245,7 @@ def state_control(rcv_times, plan, path_plan, CS, CP, state, events, v_cruise_kp # Send a "steering required alert" if saturation count has reached the limit if LaC.sat_flag and CP.steerLimitAlert: - AM.add("steerSaturated", enabled) + AM.add(frame, "steerSaturated", enabled) # Parse permanent warnings to display constantly for e in get_events(events, [ET.PERMANENT]): @@ -281,65 +256,63 @@ def state_control(rcv_times, plan, path_plan, CS, CP, state, events, v_cruise_kp extra_text_2 = str(int(round(Filter.MIN_SPEED * CV.MS_TO_KPH))) + " kph" else: extra_text_2 = str(int(round(Filter.MIN_SPEED * CV.MS_TO_MPH))) + " mph" - AM.add(str(e) + "Permanent", enabled, extra_text_1=extra_text_1, extra_text_2=extra_text_2) + AM.add(frame, str(e) + "Permanent", enabled, extra_text_1=extra_text_1, extra_text_2=extra_text_2) - AM.process_alerts(sec_since_boot()) + AM.process_alerts(frame) - return actuators, v_cruise_kph, driver_status, angle_model_bias, v_acc_sol, a_acc_sol, lac_log + return actuators, v_cruise_kph, driver_status, v_acc_sol, a_acc_sol, lac_log -def data_send(plan, path_plan, CS, CI, CP, VM, state, events, actuators, v_cruise_kph, rk, carstate, - carcontrol, controlsstate, sendcan, AM, driver_status, - LaC, LoC, angle_model_bias, read_only, start_time, v_acc, a_acc, lac_log): +def data_send(sm, CS, CI, CP, VM, state, events, actuators, v_cruise_kph, rk, carstate, + carcontrol, carevents, carparams, controlsstate, sendcan, AM, driver_status, + LaC, LoC, read_only, start_time, v_acc, a_acc, lac_log, events_prev): """Send actuators and hud commands to the car, send controlsstate and MPC logging""" - plan_ts = plan.logMonoTime - plan = plan.plan CC = car.CarControl.new_message() + CC.enabled = isEnabled(state) + CC.actuators = actuators - if not read_only: - CC.enabled = isEnabled(state) - CC.actuators = actuators - - CC.cruiseControl.override = True - CC.cruiseControl.cancel = not CP.enableCruise or (not isEnabled(state) and CS.cruiseState.enabled) + CC.cruiseControl.override = True + CC.cruiseControl.cancel = not CP.enableCruise or (not isEnabled(state) and CS.cruiseState.enabled) - # Some override values for Honda - brake_discount = (1.0 - clip(actuators.brake * 3., 0.0, 1.0)) # brake discount removes a sharp nonlinearity - CC.cruiseControl.speedOverride = float(max(0.0, (LoC.v_pid + CS.cruiseState.speedOffset) * brake_discount) if CP.enableCruise else 0.0) - CC.cruiseControl.accelOverride = CI.calc_accel_override(CS.aEgo, plan.aTarget, CS.vEgo, plan.vTarget) + # Some override values for Honda + brake_discount = (1.0 - clip(actuators.brake * 3., 0.0, 1.0)) # brake discount removes a sharp nonlinearity + CC.cruiseControl.speedOverride = float(max(0.0, (LoC.v_pid + CS.cruiseState.speedOffset) * brake_discount) if CP.enableCruise else 0.0) + CC.cruiseControl.accelOverride = CI.calc_accel_override(CS.aEgo, sm['plan'].aTarget, CS.vEgo, sm['plan'].vTarget) - CC.hudControl.setSpeed = float(v_cruise_kph * CV.KPH_TO_MS) - CC.hudControl.speedVisible = isEnabled(state) - CC.hudControl.lanesVisible = isEnabled(state) - CC.hudControl.leadVisible = plan.hasLead + CC.hudControl.setSpeed = float(v_cruise_kph * CV.KPH_TO_MS) + CC.hudControl.speedVisible = isEnabled(state) + CC.hudControl.lanesVisible = isEnabled(state) + CC.hudControl.leadVisible = sm['plan'].hasLead - right_lane_visible = path_plan.pathPlan.rProb > 0.5 - left_lane_visible = path_plan.pathPlan.lProb > 0.5 + right_lane_visible = sm['pathPlan'].rProb > 0.5 + left_lane_visible = sm['pathPlan'].lProb > 0.5 - CC.hudControl.rightLaneVisible = bool(right_lane_visible) - CC.hudControl.leftLaneVisible = bool(left_lane_visible) + CC.hudControl.rightLaneVisible = bool(right_lane_visible) + CC.hudControl.leftLaneVisible = bool(left_lane_visible) - blinker = CS.leftBlinker or CS.rightBlinker - ldw_allowed = CS.vEgo > 12.5 and not blinker + blinker = CS.leftBlinker or CS.rightBlinker + ldw_allowed = CS.vEgo > 12.5 and not blinker - if len(list(path_plan.pathPlan.rPoly)) == 4: - CC.hudControl.rightLaneDepart = bool(ldw_allowed and path_plan.pathPlan.rPoly[3] > -(1 + CAMERA_OFFSET) and right_lane_visible) - if len(list(path_plan.pathPlan.lPoly)) == 4: - CC.hudControl.leftLaneDepart = bool(ldw_allowed and path_plan.pathPlan.lPoly[3] < (1 - CAMERA_OFFSET) and left_lane_visible) + if len(list(sm['pathPlan'].rPoly)) == 4: + CC.hudControl.rightLaneDepart = bool(ldw_allowed and sm['pathPlan'].rPoly[3] > -(1 + CAMERA_OFFSET) and right_lane_visible) + if len(list(sm['pathPlan'].lPoly)) == 4: + CC.hudControl.leftLaneDepart = bool(ldw_allowed and sm['pathPlan'].lPoly[3] < (1 - CAMERA_OFFSET) and left_lane_visible) - CC.hudControl.visualAlert = AM.visual_alert - CC.hudControl.audibleAlert = AM.audible_alert + CC.hudControl.visualAlert = AM.visual_alert + CC.hudControl.audibleAlert = AM.audible_alert + if not read_only: # send car controls over can can_sends = CI.apply(CC) - sendcan.send(can_list_to_can_capnp(can_sends, msgtype='sendcan')) + sendcan.send(can_list_to_can_capnp(can_sends, msgtype='sendcan', valid=CS.canValid)) force_decel = driver_status.awareness < 0. # controlsState dat = messaging.new_message() dat.init('controlsState') + dat.valid = CS.canValid dat.controlsState = { "alertText1": AM.alert_text_1, "alertText2": AM.alert_text_2, @@ -351,8 +324,8 @@ def data_send(plan, path_plan, CS, CI, CP, VM, state, events, actuators, v_cruis "awarenessStatus": max(driver_status.awareness, 0.0) if isEnabled(state) else 0.0, "driverMonitoringOn": bool(driver_status.monitor_on and driver_status.face_detected), "canMonoTimes": list(CS.canMonoTimes), - "planMonoTime": plan_ts, - "pathPlanMonoTime": path_plan.logMonoTime, + "planMonoTime": sm.logMonoTime['plan'], + "pathPlanMonoTime": sm.logMonoTime['pathPlan'], "enabled": isEnabled(state), "active": isActive(state), "vEgo": CS.vEgo, @@ -371,14 +344,14 @@ def data_send(plan, path_plan, CS, CI, CP, VM, state, events, actuators, v_cruis "angleSteersDes": float(LaC.angle_steers_des), "vTargetLead": float(v_acc), "aTarget": float(a_acc), - "jerkFactor": float(plan.jerkFactor), - "angleModelBias": float(angle_model_bias), - "gpsPlannerActive": plan.gpsPlannerActive, - "vCurvature": plan.vCurvature, - "decelForTurn": plan.decelForTurn, + "jerkFactor": float(sm['plan'].jerkFactor), + "angleModelBias": 0., + "gpsPlannerActive": sm['plan'].gpsPlannerActive, + "vCurvature": sm['plan'].vCurvature, + "decelForTurn": sm['plan'].decelForTurn, "cumLagMs": -rk.remaining * 1000., "startMonoTime": int(start_time * 1e9), - "mapValid": plan.mapValid, + "mapValid": sm['plan'].mapValid, "forceDecel": bool(force_decel), } @@ -391,17 +364,34 @@ def data_send(plan, path_plan, CS, CI, CP, VM, state, events, actuators, v_cruis # carState cs_send = messaging.new_message() cs_send.init('carState') + cs_send.valid = CS.canValid cs_send.carState = CS cs_send.carState.events = events carstate.send(cs_send.to_bytes()) + # carEvents - logged every second or on change + events_bytes = events_to_bytes(events) + if (sm.frame % int(1. / DT_CTRL) == 0) or (events_bytes != events_prev): + ce_send = messaging.new_message() + ce_send.init('carEvents', len(events)) + ce_send.carEvents = events + carevents.send(ce_send.to_bytes()) + + # carParams - logged every 50 seconds (> 1 per segment) + if (sm.frame % int(50. / DT_CTRL) == 0): + cp_send = messaging.new_message() + cp_send.init('carParams') + cp_send.carParams = CP + carparams.send(cp_send.to_bytes()) + # carControl cc_send = messaging.new_message() cc_send.init('carControl') + cc_send.valid = CS.canValid cc_send.carControl = CC carcontrol.send(cc_send.to_bytes()) - return CC + return CC, events_bytes def controlsd_thread(gctx=None): @@ -410,28 +400,21 @@ def controlsd_thread(gctx=None): # start the loop set_realtime_priority(3) - context = zmq.Context() params = Params() # Pub Sockets - controlsstate = messaging.pub_sock(context, service_list['controlsState'].port) - carstate = messaging.pub_sock(context, service_list['carState'].port) - carcontrol = messaging.pub_sock(context, service_list['carControl'].port) + sendcan = messaging.pub_sock(service_list['sendcan'].port) + controlsstate = messaging.pub_sock(service_list['controlsState'].port) + carstate = messaging.pub_sock(service_list['carState'].port) + carcontrol = messaging.pub_sock(service_list['carControl'].port) + carevents = messaging.pub_sock(service_list['carEvents'].port) + carparams = messaging.pub_sock(service_list['carParams'].port) is_metric = params.get("IsMetric") == "1" passive = params.get("Passive") != "0" - sendcan = messaging.pub_sock(context, service_list['sendcan'].port) - - # Sub sockets - poller = zmq.Poller() - thermal = messaging.sub_sock(context, service_list['thermal'].port, conflate=True, poller=poller) - health = messaging.sub_sock(context, service_list['health'].port, conflate=True, poller=poller) - cal = messaging.sub_sock(context, service_list['liveCalibration'].port, conflate=True, poller=poller) - driver_monitor = messaging.sub_sock(context, service_list['driverMonitoring'].port, conflate=True, poller=poller) - plan_sock = messaging.sub_sock(context, service_list['plan'].port, conflate=True, poller=poller) - path_plan_sock = messaging.sub_sock(context, service_list['pathPlan'].port, conflate=True, poller=poller) - logcan = messaging.sub_sock(context, service_list['can'].port) + sm = messaging.SubMaster(['thermal', 'health', 'liveCalibration', 'driverMonitoring', 'plan', 'pathPlan']) + logcan = messaging.sub_sock(service_list['can'].port) CC = car.CarControl.new_message() CI, CP = get_car(logcan, sendcan) @@ -442,10 +425,10 @@ def controlsd_thread(gctx=None): controller_available = CP.enableCamera and CI.CC is not None and not passive read_only = not car_recognized or not controller_available if read_only: - CP.safetyModel = car.CarParams.SafetyModels.elm327 # diagnostic only + CP.safetyModel = car.CarParams.SafetyModel.elm327 # diagnostic only startup_alert = get_startup_alert(car_recognized, controller_available) - AM.add(startup_alert, False) + AM.add(sm.frame, startup_alert, False) LoC = LongControl(CP, CI.compute_gb) VM = VehicleModel(CP) @@ -471,27 +454,12 @@ def controlsd_thread(gctx=None): cal_perc = 0 mismatch_counter = 0 low_battery = False + events_prev = [] - rcv_times = defaultdict(int) - - plan = messaging.new_message() - plan.init('plan') - path_plan = messaging.new_message() - path_plan.init('pathPlan') - path_plan.pathPlan.sensorValid = True + sm['pathPlan'].sensorValid = True # controlsd is driven by can recv, expected at 100Hz rk = Ratekeeper(100, print_delay_threshold=None) - controls_params = params.get("ControlsParams") - - # Read angle offset from previous drive - angle_model_bias = 0. - if controls_params is not None: - try: - controls_params = json.loads(controls_params) - angle_model_bias = controls_params['angle_model_bias'] - except (ValueError, KeyError): - pass prof = Profiler(False) # off by default @@ -500,50 +468,47 @@ def controlsd_thread(gctx=None): prof.checkpoint("Ratekeeper", ignore=True) # Sample data and compute car events - CS, events, cal_status, cal_perc, overtemp, free_space, low_battery, mismatch_counter, plan, path_plan =\ - data_sample(rcv_times, CI, CC, plan_sock, path_plan_sock, thermal, cal, health, driver_monitor, - poller, cal_status, cal_perc, overtemp, free_space, low_battery, driver_status, - state, mismatch_counter, params, plan, path_plan) + CS, events, cal_status, cal_perc, overtemp, free_space, low_battery, mismatch_counter =\ + data_sample(CI, CC, sm, cal_status, cal_perc, overtemp, free_space, low_battery, + driver_status, state, mismatch_counter, params) prof.checkpoint("Sample") # Create alerts - path_plan_age = start_time - rcv_times['pathPlan'] - plan_age = start_time - rcv_times['plan'] - - if not path_plan.pathPlan.valid or plan_age > 0.5 or path_plan_age > 0.5: - events.append(create_event('plannerError', [ET.NO_ENTRY, ET.SOFT_DISABLE])) - if not path_plan.pathPlan.sensorValid: + if not sm.all_alive_and_valid(): + events.append(create_event('commIssue', [ET.NO_ENTRY, ET.SOFT_DISABLE])) + if not sm['pathPlan'].mpcSolutionValid: + events.append(create_event('plannerError', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE])) + if not sm['pathPlan'].sensorValid: events.append(create_event('sensorDataInvalid', [ET.NO_ENTRY, ET.PERMANENT])) - if not path_plan.pathPlan.paramsValid: + if not sm['pathPlan'].paramsValid: events.append(create_event('vehicleModelInvalid', [ET.WARNING])) - if not path_plan.pathPlan.modelValid: - events.append(create_event('modelCommIssue', [ET.NO_ENTRY, ET.SOFT_DISABLE])) - if not plan.plan.radarValid: + if not sm['plan'].radarValid: events.append(create_event('radarFault', [ET.NO_ENTRY, ET.SOFT_DISABLE])) - if plan.plan.radarCommIssue: - events.append(create_event('radarCommIssue', [ET.NO_ENTRY, ET.SOFT_DISABLE])) + if sm['plan'].radarCanError: + events.append(create_event('radarCanError', [ET.NO_ENTRY, ET.SOFT_DISABLE])) + if not CS.canValid: + events.append(create_event('canError', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE])) # Only allow engagement with brake pressed when stopped behind another stopped car - if CS.brakePressed and plan.plan.vTargetFuture >= STARTING_TARGET_SPEED and not CP.radarOffCan and CS.vEgo < 0.3: + if CS.brakePressed and sm['plan'].vTargetFuture >= STARTING_TARGET_SPEED and not CP.radarOffCan and CS.vEgo < 0.3: events.append(create_event('noTarget', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE])) if not read_only: # update control state state, soft_disable_timer, v_cruise_kph, v_cruise_kph_last = \ - state_transition(CS, CP, state, events, soft_disable_timer, v_cruise_kph, AM) + state_transition(sm.frame, CS, CP, state, events, soft_disable_timer, v_cruise_kph, AM) prof.checkpoint("State transition") # Compute actuators (runs PID loops and lateral MPC) - actuators, v_cruise_kph, driver_status, angle_model_bias, v_acc, a_acc, lac_log = \ - state_control(rcv_times, plan.plan, path_plan.pathPlan, CS, CP, state, events, v_cruise_kph, - v_cruise_kph_last, AM, rk, driver_status, - LaC, LoC, VM, angle_model_bias, read_only, is_metric, cal_perc) + actuators, v_cruise_kph, driver_status, v_acc, a_acc, lac_log = \ + state_control(sm.frame, sm.rcv_frame, sm['plan'], sm['pathPlan'], CS, CP, state, events, v_cruise_kph, v_cruise_kph_last, AM, rk, + driver_status, LaC, LoC, VM, read_only, is_metric, cal_perc) prof.checkpoint("State Control") # Publish data - CC = data_send(plan, path_plan, CS, CI, CP, VM, state, events, actuators, v_cruise_kph, rk, carstate, carcontrol, - controlsstate, sendcan, AM, driver_status, LaC, LoC, angle_model_bias, read_only, start_time, v_acc, a_acc, lac_log) + CC, events_prev = data_send(sm, CS, CI, CP, VM, state, events, actuators, v_cruise_kph, rk, carstate, carcontrol, carevents, carparams, + controlsstate, sendcan, AM, driver_status, LaC, LoC, read_only, start_time, v_acc, a_acc, lac_log, events_prev) prof.checkpoint("Sent") rk.monitor_time() diff --git a/selfdrive/controls/lib/alertmanager.py b/selfdrive/controls/lib/alertmanager.py index 5ce2bfac13..df2727e6e7 100644 --- a/selfdrive/controls/lib/alertmanager.py +++ b/selfdrive/controls/lib/alertmanager.py @@ -1,7 +1,7 @@ from cereal import log +from common.realtime import DT_CTRL from selfdrive.swaglog import cloudlog from selfdrive.controls.lib.alerts import ALERTS -from common.realtime import sec_since_boot import copy @@ -18,12 +18,12 @@ class AlertManager(object): def alertPresent(self): return len(self.activealerts) > 0 - def add(self, alert_type, enabled=True, extra_text_1='', extra_text_2=''): + def add(self, frame, alert_type, enabled=True, extra_text_1='', extra_text_2=''): alert_type = str(alert_type) added_alert = copy.copy(self.alerts[alert_type]) added_alert.alert_text_1 += extra_text_1 added_alert.alert_text_2 += extra_text_2 - added_alert.start_time = sec_since_boot() + added_alert.start_time = frame * DT_CTRL # if new alert is higher priority, log it if not self.alertPresent() or added_alert.alert_priority > self.activealerts[0].alert_priority: @@ -34,7 +34,8 @@ class AlertManager(object): # sort by priority first and then by start_time self.activealerts.sort(key=lambda k: (k.alert_priority, k.start_time), reverse=True) - def process_alerts(self, cur_time): + def process_alerts(self, frame): + cur_time = frame * DT_CTRL # first get rid of all the expired alerts self.activealerts = [a for a in self.activealerts if a.start_time + diff --git a/selfdrive/controls/lib/alerts.py b/selfdrive/controls/lib/alerts.py index d6e3f4535c..da7e88acbd 100644 --- a/selfdrive/controls/lib/alerts.py +++ b/selfdrive/controls/lib/alerts.py @@ -355,28 +355,28 @@ ALERTS = [ AlertStatus.critical, AlertSize.full, Priority.MID, VisualAlert.steerRequired, AudibleAlert.chimeWarning2, .1, 2., 2.), - # Cancellation alerts causing immediate disabling Alert( - "radarCommIssue", + "commIssue", "TAKE CONTROL IMMEDIATELY", - "Radar Error: Restart the Car", + "Communication Issue between Processes", AlertStatus.critical, AlertSize.full, - Priority.HIGHEST, VisualAlert.steerRequired, AudibleAlert.chimeWarningRepeat, 1., 3., 4.), + Priority.MID, VisualAlert.steerRequired, AudibleAlert.chimeWarning2, .1, 2., 2.), Alert( - "radarFault", + "radarCanError", "TAKE CONTROL IMMEDIATELY", "Radar Error: Restart the Car", AlertStatus.critical, AlertSize.full, - Priority.HIGHEST, VisualAlert.steerRequired, AudibleAlert.chimeWarningRepeat, 1., 3., 4.), + Priority.MID, VisualAlert.steerRequired, AudibleAlert.chimeWarning2, .1, 2., 2.), Alert( - "modelCommIssue", + "radarFault", "TAKE CONTROL IMMEDIATELY", - "Model Error: Check Internet Connection", + "Radar Error: Restart the Car", AlertStatus.critical, AlertSize.full, - Priority.HIGHEST, VisualAlert.steerRequired, AudibleAlert.chimeWarningRepeat, 1., 3., 4.), + Priority.MID, VisualAlert.steerRequired, AudibleAlert.chimeWarning2, .1, 2., 2.), + # Cancellation alerts causing immediate disabling Alert( "controlsFailed", "TAKE CONTROL IMMEDIATELY", @@ -392,7 +392,7 @@ ALERTS = [ Priority.HIGHEST, VisualAlert.steerRequired, AudibleAlert.chimeWarningRepeat, 1., 3., 4.), Alert( - "commIssue", + "canError", "TAKE CONTROL IMMEDIATELY", "CAN Error: Check Connections", AlertStatus.critical, AlertSize.full, @@ -520,7 +520,7 @@ ALERTS = [ Priority.MID, VisualAlert.none, AudibleAlert.chimeError, .4, 2., 3.), Alert( - "radarCommIssueNoEntry", + "radarCanErrorNoEntry", "openpilot Unavailable", "Radar Error: Restart the Car", AlertStatus.normal, AlertSize.mid, @@ -533,13 +533,6 @@ ALERTS = [ AlertStatus.normal, AlertSize.mid, Priority.LOW, VisualAlert.none, AudibleAlert.chimeError, .4, 2., 3.), - Alert( - "modelCommIssueNoEntry", - "openpilot Unavailable", - "Model Error: Check Internet Connection", - AlertStatus.normal, AlertSize.mid, - Priority.LOW, VisualAlert.none, AudibleAlert.chimeError, .4, 2., 3.), - Alert( "controlsFailedNoEntry", "openpilot Unavailable", @@ -548,7 +541,7 @@ ALERTS = [ Priority.LOW, VisualAlert.none, AudibleAlert.chimeError, .4, 2., 3.), Alert( - "commIssueNoEntry", + "canErrorNoEntry", "openpilot Unavailable", "CAN Error: Check Connections", AlertStatus.normal, AlertSize.mid, @@ -610,6 +603,13 @@ ALERTS = [ AlertStatus.normal, AlertSize.mid, Priority.LOW, VisualAlert.none, AudibleAlert.chimeDisengage, .4, 2., 3.), + Alert( + "commIssueNoEntry", + "openpilot unavailable", + "Communication Issue between Processes", + AlertStatus.normal, AlertSize.mid, + Priority.LOW, VisualAlert.none, AudibleAlert.chimeDisengage, .4, 2., 3.), + # permanent alerts Alert( "steerUnavailablePermanent", diff --git a/selfdrive/controls/lib/cluster/Makefile b/selfdrive/controls/lib/cluster/Makefile index ed5edfb59e..ca4a23da59 100644 --- a/selfdrive/controls/lib/cluster/Makefile +++ b/selfdrive/controls/lib/cluster/Makefile @@ -1,7 +1,11 @@ CC = clang CXX = clang++ -CPPFLAGS = -Wall -g -fPIC -std=c++11 -O2 +CXXFLAGS = -Wall -g -fPIC -std=c++11 -O2 + +ifeq ($(ARCH),aarch64) +CXXFLAGS += -mcpu=cortex-a57 +endif OBJS = fastcluster.o test.o DEPS := $(OBJS:.o=.d) @@ -19,7 +23,7 @@ libfastcluster.so: fastcluster.o $(CXX) -g -shared -o $@ $+ %.o: %.cpp - $(CXX) $(CPPFLAGS) -MMD -c $*.cpp + $(CXX) $(CXXFLAGS) -MMD -c $*.cpp clean: rm -f $(OBJS) $(DEPS) libfastcluster.so test diff --git a/selfdrive/controls/lib/drive_helpers.py b/selfdrive/controls/lib/drive_helpers.py index 28e35dddf8..9c1144b966 100644 --- a/selfdrive/controls/lib/drive_helpers.py +++ b/selfdrive/controls/lib/drive_helpers.py @@ -2,8 +2,6 @@ from cereal import car from common.numpy_fast import clip, interp from selfdrive.config import Conversions as CV -DT = 0.01 # Controlsd runs at 100Hz - # kph V_CRUISE_MAX = 144 V_CRUISE_MIN = 8 diff --git a/selfdrive/controls/lib/driver_monitor.py b/selfdrive/controls/lib/driver_monitor.py index 814d77a6a6..e813d0b176 100644 --- a/selfdrive/controls/lib/driver_monitor.py +++ b/selfdrive/controls/lib/driver_monitor.py @@ -1,10 +1,8 @@ import numpy as np -from common.realtime import sec_since_boot +from common.realtime import sec_since_boot, DT_CTRL, DT_DMON from selfdrive.controls.lib.drive_helpers import create_event, EventTypes as ET from common.filter_simple import FirstOrderFilter -_DT = 0.01 # update runs at 100Hz -_DTM = 0.1 # DM runs at 10Hz _AWARENESS_TIME = 180 # 3 minutes limit without user touching steering wheels make the car enter a terminal status _AWARENESS_PRE_TIME = 20. # a first alert is issued 20s before expiration _AWARENESS_PROMPT_TIME = 5. # a second alert is issued 5s before start decelerating the car @@ -65,9 +63,9 @@ class DriverStatus(): self.monitor_valid = True # variance needs to be low self.awareness = 1. self.driver_distracted = False - self.driver_distraction_filter = FirstOrderFilter(0., _DISTRACTED_FILTER_TS, _DTM) + self.driver_distraction_filter = FirstOrderFilter(0., _DISTRACTED_FILTER_TS, DT_DMON) self.variance_high = False - self.variance_filter = FirstOrderFilter(0., _VARIANCE_FILTER_TS, _DTM) + self.variance_filter = FirstOrderFilter(0., _VARIANCE_FILTER_TS, DT_DMON) self.ts_last_check = 0. self.face_detected = False self._set_timers() @@ -81,11 +79,11 @@ class DriverStatus(): if self.monitor_on: self.threshold_pre = _DISTRACTED_PRE_TIME / _DISTRACTED_TIME self.threshold_prompt = _DISTRACTED_PROMPT_TIME / _DISTRACTED_TIME - self.step_change = _DT / _DISTRACTED_TIME + self.step_change = DT_CTRL / _DISTRACTED_TIME else: self.threshold_pre = _AWARENESS_PRE_TIME / _AWARENESS_TIME self.threshold_prompt = _AWARENESS_PROMPT_TIME / _AWARENESS_TIME - self.step_change = _DT / _AWARENESS_TIME + self.step_change = DT_CTRL / _AWARENESS_TIME def _is_driver_distracted(self, pose): # to be tuned and to learn the driver's normal pose diff --git a/selfdrive/controls/lib/latcontrol_indi.py b/selfdrive/controls/lib/latcontrol_indi.py index 28e37b9e27..31ff6dd3dc 100644 --- a/selfdrive/controls/lib/latcontrol_indi.py +++ b/selfdrive/controls/lib/latcontrol_indi.py @@ -1,19 +1,20 @@ import math import numpy as np +from cereal import log +from common.realtime import DT_CTRL +from common.numpy_fast import clip from selfdrive.car.toyota.carcontroller import SteerLimitParams from selfdrive.car import apply_toyota_steer_torque_limits -from selfdrive.controls.lib.drive_helpers import get_steer_max, DT -from common.numpy_fast import clip -from cereal import log +from selfdrive.controls.lib.drive_helpers import get_steer_max class LatControlINDI(object): def __init__(self, CP): self.angle_steers_des = 0. - A = np.matrix([[1.0, DT, 0.0], - [0.0, 1.0, DT], + A = np.matrix([[1.0, DT_CTRL, 0.0], + [0.0, 1.0, DT_CTRL], [0.0, 0.0, 1.0]]) C = np.matrix([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]) @@ -37,7 +38,7 @@ class LatControlINDI(object): self.G = CP.lateralTuning.indi.actuatorEffectiveness self.outer_loop_gain = CP.lateralTuning.indi.outerLoopGain self.inner_loop_gain = CP.lateralTuning.indi.innerLoopGain - self.alpha = 1. - DT / (self.RC + DT) + self.alpha = 1. - DT_CTRL / (self.RC + DT_CTRL) self.reset() diff --git a/selfdrive/controls/lib/latcontrol_pid.py b/selfdrive/controls/lib/latcontrol_pid.py index 4468062392..65a5a8b6d9 100644 --- a/selfdrive/controls/lib/latcontrol_pid.py +++ b/selfdrive/controls/lib/latcontrol_pid.py @@ -24,10 +24,6 @@ class LatControlPID(object): pid_log.active = False self.pid.reset() else: - # TODO: ideally we should interp, but for tuning reasons we keep the mpc solution - # constant for 0.05s. - #dt = min(cur_time - self.angle_steers_des_time, _DT_MPC + _DT) + _DT # no greater than dt mpc + dt, to prevent too high extraps - #self.angle_steers_des = self.angle_steers_des_prev + (dt / _DT_MPC) * (self.angle_steers_des_mpc - self.angle_steers_des_prev) self.angle_steers_des = path_plan.angleSteers # get from MPC/PathPlanner steers_max = get_steer_max(CP, v_ego) diff --git a/selfdrive/controls/lib/lateral_mpc/Makefile b/selfdrive/controls/lib/lateral_mpc/Makefile index 97579e751c..42970efd66 100644 --- a/selfdrive/controls/lib/lateral_mpc/Makefile +++ b/selfdrive/controls/lib/lateral_mpc/Makefile @@ -15,11 +15,13 @@ QPOASES_FLAGS = -I$(PHONELIBS)/qpoases -I$(PHONELIBS)/qpoases/INCLUDE -I$(PHONEL ACADO_FLAGS = -I$(PHONELIBS)/acado/include -I$(PHONELIBS)/acado/include/acado ifeq ($(UNAME_S),Darwin) - ACADO_LIBS := -lacado_toolkit_s +ACADO_LIBS := -lacado_toolkit_s else ifeq ($(UNAME_M),aarch64) - ACADO_LIBS := -L $(PHONELIBS)/acado/aarch64/lib -l:libacado_toolkit.a -l:libacado_casadi.a -l:libacado_csparse.a +ACADO_LIBS := -L $(PHONELIBS)/acado/aarch64/lib -l:libacado_toolkit.a -l:libacado_casadi.a -l:libacado_csparse.a +CFLAGS += -mcpu=cortex-a57 +CXXFLAGS += -mcpu=cortex-a57 else - ACADO_LIBS := -L $(PHONELIBS)/acado/x64/lib -l:libacado_toolkit.a -l:libacado_casadi.a -l:libacado_csparse.a +ACADO_LIBS := -L $(PHONELIBS)/acado/x64/lib -l:libacado_toolkit.a -l:libacado_casadi.a -l:libacado_csparse.a endif OBJS = \ diff --git a/selfdrive/controls/lib/lateral_mpc/generator.cpp b/selfdrive/controls/lib/lateral_mpc/generator.cpp index 9af88f9dc8..523ed8ac84 100644 --- a/selfdrive/controls/lib/lateral_mpc/generator.cpp +++ b/selfdrive/controls/lib/lateral_mpc/generator.cpp @@ -46,20 +46,22 @@ int main( ) auto angle_p = atan(3*p_poly_r0*xx*xx + 2*p_poly_r1*xx + p_poly_r2); // given the lane width estimate, this is where we estimate the path given lane lines - auto l_phantom = poly_l - lane_width/2.0; - auto r_phantom = poly_r + lane_width/2.0; + auto path_from_left_lane = poly_l - lane_width/2.0; + auto path_from_right_lane = poly_r + lane_width/2.0; - // best path estimate path is a linear combination of poly_p and the path estimate - // given the lane lines - auto path = lr_prob * (l_prob * l_phantom + r_prob * r_phantom) / (l_prob + r_prob + 0.0001) - + (1-lr_prob) * poly_p; + // if the lanes are visible, drive in the center, otherwise follow the path + auto path = lr_prob * (l_prob * path_from_left_lane + r_prob * path_from_right_lane) / (l_prob + r_prob + 0.0001) + + (1-lr_prob) * poly_p; - auto angle = lr_prob * (l_prob * angle_l + r_prob * angle_r) / (l_prob + r_prob + 0.0001) - + (1-lr_prob) * angle_p; + auto angle = lr_prob * (l_prob * angle_l + r_prob * angle_r) / (l_prob + r_prob + 0.0001) + + (1-lr_prob) * angle_p; - // instead of using actual lane lines, use their estimated distance from path given lane_width - auto c_left_lane = exp(-(path + lane_width/2.0 - yy)); - auto c_right_lane = exp(path - lane_width/2.0 - yy); + // When the lane is not visible, use an estimate of its position + auto weighted_left_lane = l_prob * poly_l + (1 - l_prob) * (path + lane_width/2.0); + auto weighted_right_lane = r_prob * poly_r + (1 - r_prob) * (path - lane_width/2.0); + + auto c_left_lane = exp(-(weighted_left_lane - yy)); + auto c_right_lane = exp(weighted_right_lane - yy); // Running cost Function h; diff --git a/selfdrive/controls/lib/lateral_mpc/lateral_mpc.c b/selfdrive/controls/lib/lateral_mpc/lateral_mpc.c index e5adf02cf4..ea6f85b304 100644 --- a/selfdrive/controls/lib/lateral_mpc/lateral_mpc.c +++ b/selfdrive/controls/lib/lateral_mpc/lateral_mpc.c @@ -26,7 +26,7 @@ typedef struct { double y[N+1]; double psi[N+1]; double delta[N+1]; - double rate[N+1]; + double rate[N]; double cost; } log_t; @@ -51,16 +51,17 @@ void init(double pathCost, double laneCost, double headingCost, double steerRate if (i > 4){ f = STEP_MULTIPLIER; } - acadoVariables.W[25 * i + 0] = pathCost * f; - acadoVariables.W[25 * i + 6] = laneCost * f; - acadoVariables.W[25 * i + 12] = laneCost * f; - acadoVariables.W[25 * i + 18] = headingCost * f; - acadoVariables.W[25 * i + 24] = steerRateCost * f; + // Setup diagonal entries + acadoVariables.W[NY*NY*i + (NY+1)*0] = pathCost * f; + acadoVariables.W[NY*NY*i + (NY+1)*1] = laneCost * f; + acadoVariables.W[NY*NY*i + (NY+1)*2] = laneCost * f; + acadoVariables.W[NY*NY*i + (NY+1)*3] = headingCost * f; + acadoVariables.W[NY*NY*i + (NY+1)*4] = steerRateCost * f; } - acadoVariables.WN[0] = pathCost * STEP_MULTIPLIER; - acadoVariables.WN[5] = laneCost * STEP_MULTIPLIER; - acadoVariables.WN[10] = laneCost * STEP_MULTIPLIER; - acadoVariables.WN[15] = headingCost * STEP_MULTIPLIER; + acadoVariables.WN[(NYN+1)*0] = pathCost * STEP_MULTIPLIER; + acadoVariables.WN[(NYN+1)*1] = laneCost * STEP_MULTIPLIER; + acadoVariables.WN[(NYN+1)*2] = laneCost * STEP_MULTIPLIER; + acadoVariables.WN[(NYN+1)*3] = headingCost * STEP_MULTIPLIER; } int run_mpc(state_t * x0, log_t * solution, @@ -113,7 +114,9 @@ int run_mpc(state_t * x0, log_t * solution, solution->y[i] = acadoVariables.x[i*NX+1]; solution->psi[i] = acadoVariables.x[i*NX+2]; solution->delta[i] = acadoVariables.x[i*NX+3]; - solution->rate[i] = acadoVariables.u[i]; + if (i < N){ + solution->rate[i] = acadoVariables.u[i]; + } } solution->cost = acado_getObjective(); diff --git a/selfdrive/controls/lib/lateral_mpc/lateral_mpc.d b/selfdrive/controls/lib/lateral_mpc/lateral_mpc.d deleted file mode 100644 index 6cac7c2e14..0000000000 --- a/selfdrive/controls/lib/lateral_mpc/lateral_mpc.d +++ /dev/null @@ -1,3 +0,0 @@ -lateral_mpc.o: lateral_mpc.c lib_mpc_export/acado_common.h \ - lib_mpc_export/acado_qpoases_interface.hpp \ - lib_mpc_export/acado_auxiliary_functions.h diff --git a/selfdrive/controls/lib/lateral_mpc/lateral_mpc.o b/selfdrive/controls/lib/lateral_mpc/lateral_mpc.o deleted file mode 100644 index fdd82d242c..0000000000 Binary files a/selfdrive/controls/lib/lateral_mpc/lateral_mpc.o and /dev/null differ diff --git a/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_auxiliary_functions.d b/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_auxiliary_functions.d deleted file mode 100644 index 50c6a60d1f..0000000000 --- a/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_auxiliary_functions.d +++ /dev/null @@ -1,5 +0,0 @@ -lib_mpc_export/acado_auxiliary_functions.o: \ - lib_mpc_export/acado_auxiliary_functions.c \ - lib_mpc_export/acado_auxiliary_functions.h \ - lib_mpc_export/acado_common.h \ - lib_mpc_export/acado_qpoases_interface.hpp diff --git a/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_auxiliary_functions.o b/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_auxiliary_functions.o deleted file mode 100644 index 07d92429b2..0000000000 Binary files a/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_auxiliary_functions.o and /dev/null differ diff --git a/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_integrator.d b/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_integrator.d deleted file mode 100644 index 7c057e5ec0..0000000000 --- a/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_integrator.d +++ /dev/null @@ -1,3 +0,0 @@ -lib_mpc_export/acado_integrator.o: lib_mpc_export/acado_integrator.c \ - lib_mpc_export/acado_common.h \ - lib_mpc_export/acado_qpoases_interface.hpp diff --git a/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_integrator.o b/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_integrator.o deleted file mode 100644 index d08f1e4127..0000000000 Binary files a/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_integrator.o and /dev/null differ diff --git a/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_qpoases_interface.d b/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_qpoases_interface.d deleted file mode 100644 index ba3c6ef1c8..0000000000 --- a/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_qpoases_interface.d +++ /dev/null @@ -1,24 +0,0 @@ -lib_mpc_export/acado_qpoases_interface.o: \ - lib_mpc_export/acado_qpoases_interface.cpp \ - lib_mpc_export/acado_common.h \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/QProblem.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/QProblemB.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Bounds.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/SubjectTo.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Indexlist.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp \ - ../../../../phonelibs/qpoases/SRC/Indexlist.ipp \ - ../../../../phonelibs/qpoases/SRC/SubjectTo.ipp \ - ../../../../phonelibs/qpoases/SRC/Bounds.ipp \ - ../../../../phonelibs/qpoases/SRC/QProblemB.ipp \ - ../../../../phonelibs/qpoases/INCLUDE/Constraints.hpp \ - ../../../../phonelibs/qpoases/SRC/Constraints.ipp \ - ../../../../phonelibs/qpoases/INCLUDE/CyclingManager.hpp \ - ../../../../phonelibs/qpoases/SRC/CyclingManager.ipp \ - ../../../../phonelibs/qpoases/SRC/QProblem.ipp diff --git a/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_qpoases_interface.o b/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_qpoases_interface.o deleted file mode 100644 index e10c9772ab..0000000000 Binary files a/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_qpoases_interface.o and /dev/null differ diff --git a/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_solver.c b/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_solver.c index 85b67db8a1..014c19a01a 100644 --- a/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_solver.c +++ b/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_solver.c @@ -103,19 +103,19 @@ const real_t* od = in + 5; real_t* a = acadoWorkspace.objAuxVar; /* Compute intermediate quantities: */ -a[0] = (exp(((real_t)(0.0000000000000000e+00)-(((((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5])-(od[17]/(real_t)(2.0000000000000000e+00))))+(od[15]*(((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9])+(od[17]/(real_t)(2.0000000000000000e+00))))))/((od[14]+od[15])+(real_t)(1.0000000000000000e-04)))+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*((((od[10]*((xd[0]*xd[0])*xd[0]))+(od[11]*(xd[0]*xd[0])))+(od[12]*xd[0]))+od[13])))+(od[17]/(real_t)(2.0000000000000000e+00)))-xd[1])))); -a[1] = (exp((((((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5])-(od[17]/(real_t)(2.0000000000000000e+00))))+(od[15]*(((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9])+(od[17]/(real_t)(2.0000000000000000e+00))))))/((od[14]+od[15])+(real_t)(1.0000000000000000e-04)))+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*((((od[10]*((xd[0]*xd[0])*xd[0]))+(od[11]*(xd[0]*xd[0])))+(od[12]*xd[0]))+od[13])))-(od[17]/(real_t)(2.0000000000000000e+00)))-xd[1]))); +a[0] = (exp(((real_t)(0.0000000000000000e+00)-(((od[14]*((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5]))+(((real_t)(1.0000000000000000e+00)-od[14])*((((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5])-(od[17]/(real_t)(2.0000000000000000e+00))))+(od[15]*(((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9])+(od[17]/(real_t)(2.0000000000000000e+00))))))/((od[14]+od[15])+(real_t)(1.0000000000000000e-04)))+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*((((od[10]*((xd[0]*xd[0])*xd[0]))+(od[11]*(xd[0]*xd[0])))+(od[12]*xd[0]))+od[13])))+(od[17]/(real_t)(2.0000000000000000e+00)))))-xd[1])))); +a[1] = (exp((((od[15]*((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9]))+(((real_t)(1.0000000000000000e+00)-od[15])*((((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5])-(od[17]/(real_t)(2.0000000000000000e+00))))+(od[15]*(((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9])+(od[17]/(real_t)(2.0000000000000000e+00))))))/((od[14]+od[15])+(real_t)(1.0000000000000000e-04)))+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*((((od[10]*((xd[0]*xd[0])*xd[0]))+(od[11]*(xd[0]*xd[0])))+(od[12]*xd[0]))+od[13])))-(od[17]/(real_t)(2.0000000000000000e+00)))))-xd[1]))); a[2] = (atan(((((((real_t)(3.0000000000000000e+00)*od[2])*xd[0])*xd[0])+(((real_t)(2.0000000000000000e+00)*od[3])*xd[0]))+od[4]))); a[3] = (atan(((((((real_t)(3.0000000000000000e+00)*od[6])*xd[0])*xd[0])+(((real_t)(2.0000000000000000e+00)*od[7])*xd[0]))+od[8]))); a[4] = (atan(((((((real_t)(3.0000000000000000e+00)*od[10])*xd[0])*xd[0])+(((real_t)(2.0000000000000000e+00)*od[11])*xd[0]))+od[12]))); a[5] = ((real_t)(1.0000000000000000e+00)/((od[14]+od[15])+(real_t)(1.0000000000000000e-04))); a[6] = ((real_t)(1.0000000000000000e+00)/((od[14]+od[15])+(real_t)(1.0000000000000000e-04))); -a[7] = (exp(((real_t)(0.0000000000000000e+00)-(((((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5])-(od[17]/(real_t)(2.0000000000000000e+00))))+(od[15]*(((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9])+(od[17]/(real_t)(2.0000000000000000e+00))))))/((od[14]+od[15])+(real_t)(1.0000000000000000e-04)))+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*((((od[10]*((xd[0]*xd[0])*xd[0]))+(od[11]*(xd[0]*xd[0])))+(od[12]*xd[0]))+od[13])))+(od[17]/(real_t)(2.0000000000000000e+00)))-xd[1])))); -a[8] = (((real_t)(0.0000000000000000e+00)-(((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((od[2]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[3]*(xd[0]+xd[0])))+od[4]))+(od[15]*(((od[6]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[7]*(xd[0]+xd[0])))+od[8]))))*a[6])+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*(((od[10]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[11]*(xd[0]+xd[0])))+od[12]))))*a[7]); +a[7] = (exp(((real_t)(0.0000000000000000e+00)-(((od[14]*((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5]))+(((real_t)(1.0000000000000000e+00)-od[14])*((((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5])-(od[17]/(real_t)(2.0000000000000000e+00))))+(od[15]*(((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9])+(od[17]/(real_t)(2.0000000000000000e+00))))))/((od[14]+od[15])+(real_t)(1.0000000000000000e-04)))+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*((((od[10]*((xd[0]*xd[0])*xd[0]))+(od[11]*(xd[0]*xd[0])))+(od[12]*xd[0]))+od[13])))+(od[17]/(real_t)(2.0000000000000000e+00)))))-xd[1])))); +a[8] = (((real_t)(0.0000000000000000e+00)-((od[14]*(((od[2]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[3]*(xd[0]+xd[0])))+od[4]))+(((real_t)(1.0000000000000000e+00)-od[14])*(((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((od[2]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[3]*(xd[0]+xd[0])))+od[4]))+(od[15]*(((od[6]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[7]*(xd[0]+xd[0])))+od[8]))))*a[6])+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*(((od[10]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[11]*(xd[0]+xd[0])))+od[12]))))))*a[7]); a[9] = (((real_t)(0.0000000000000000e+00)-((real_t)(0.0000000000000000e+00)-(real_t)(1.0000000000000000e+00)))*a[7]); a[10] = ((real_t)(1.0000000000000000e+00)/((od[14]+od[15])+(real_t)(1.0000000000000000e-04))); -a[11] = (exp((((((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5])-(od[17]/(real_t)(2.0000000000000000e+00))))+(od[15]*(((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9])+(od[17]/(real_t)(2.0000000000000000e+00))))))/((od[14]+od[15])+(real_t)(1.0000000000000000e-04)))+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*((((od[10]*((xd[0]*xd[0])*xd[0]))+(od[11]*(xd[0]*xd[0])))+(od[12]*xd[0]))+od[13])))-(od[17]/(real_t)(2.0000000000000000e+00)))-xd[1]))); -a[12] = ((((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((od[2]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[3]*(xd[0]+xd[0])))+od[4]))+(od[15]*(((od[6]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[7]*(xd[0]+xd[0])))+od[8]))))*a[10])+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*(((od[10]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[11]*(xd[0]+xd[0])))+od[12])))*a[11]); +a[11] = (exp((((od[15]*((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9]))+(((real_t)(1.0000000000000000e+00)-od[15])*((((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5])-(od[17]/(real_t)(2.0000000000000000e+00))))+(od[15]*(((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9])+(od[17]/(real_t)(2.0000000000000000e+00))))))/((od[14]+od[15])+(real_t)(1.0000000000000000e-04)))+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*((((od[10]*((xd[0]*xd[0])*xd[0]))+(od[11]*(xd[0]*xd[0])))+(od[12]*xd[0]))+od[13])))-(od[17]/(real_t)(2.0000000000000000e+00)))))-xd[1]))); +a[12] = (((od[15]*(((od[6]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[7]*(xd[0]+xd[0])))+od[8]))+(((real_t)(1.0000000000000000e+00)-od[15])*(((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((od[2]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[3]*(xd[0]+xd[0])))+od[4]))+(od[15]*(((od[6]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[7]*(xd[0]+xd[0])))+od[8]))))*a[10])+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*(((od[10]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[11]*(xd[0]+xd[0])))+od[12])))))*a[11]); a[13] = (((real_t)(0.0000000000000000e+00)-(real_t)(1.0000000000000000e+00))*a[11]); a[14] = ((real_t)(1.0000000000000000e+00)/((real_t)(1.0000000000000000e+00)+(pow(((((((real_t)(3.0000000000000000e+00)*od[2])*xd[0])*xd[0])+(((real_t)(2.0000000000000000e+00)*od[3])*xd[0]))+od[4]),2)))); a[15] = ((((((real_t)(3.0000000000000000e+00)*od[2])*xd[0])+(((real_t)(3.0000000000000000e+00)*od[2])*xd[0]))+((real_t)(2.0000000000000000e+00)*od[3]))*a[14]); @@ -166,19 +166,19 @@ const real_t* od = in + 4; real_t* a = acadoWorkspace.objAuxVar; /* Compute intermediate quantities: */ -a[0] = (exp(((real_t)(0.0000000000000000e+00)-(((((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5])-(od[17]/(real_t)(2.0000000000000000e+00))))+(od[15]*(((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9])+(od[17]/(real_t)(2.0000000000000000e+00))))))/((od[14]+od[15])+(real_t)(1.0000000000000000e-04)))+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*((((od[10]*((xd[0]*xd[0])*xd[0]))+(od[11]*(xd[0]*xd[0])))+(od[12]*xd[0]))+od[13])))+(od[17]/(real_t)(2.0000000000000000e+00)))-xd[1])))); -a[1] = (exp((((((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5])-(od[17]/(real_t)(2.0000000000000000e+00))))+(od[15]*(((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9])+(od[17]/(real_t)(2.0000000000000000e+00))))))/((od[14]+od[15])+(real_t)(1.0000000000000000e-04)))+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*((((od[10]*((xd[0]*xd[0])*xd[0]))+(od[11]*(xd[0]*xd[0])))+(od[12]*xd[0]))+od[13])))-(od[17]/(real_t)(2.0000000000000000e+00)))-xd[1]))); +a[0] = (exp(((real_t)(0.0000000000000000e+00)-(((od[14]*((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5]))+(((real_t)(1.0000000000000000e+00)-od[14])*((((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5])-(od[17]/(real_t)(2.0000000000000000e+00))))+(od[15]*(((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9])+(od[17]/(real_t)(2.0000000000000000e+00))))))/((od[14]+od[15])+(real_t)(1.0000000000000000e-04)))+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*((((od[10]*((xd[0]*xd[0])*xd[0]))+(od[11]*(xd[0]*xd[0])))+(od[12]*xd[0]))+od[13])))+(od[17]/(real_t)(2.0000000000000000e+00)))))-xd[1])))); +a[1] = (exp((((od[15]*((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9]))+(((real_t)(1.0000000000000000e+00)-od[15])*((((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5])-(od[17]/(real_t)(2.0000000000000000e+00))))+(od[15]*(((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9])+(od[17]/(real_t)(2.0000000000000000e+00))))))/((od[14]+od[15])+(real_t)(1.0000000000000000e-04)))+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*((((od[10]*((xd[0]*xd[0])*xd[0]))+(od[11]*(xd[0]*xd[0])))+(od[12]*xd[0]))+od[13])))-(od[17]/(real_t)(2.0000000000000000e+00)))))-xd[1]))); a[2] = (atan(((((((real_t)(3.0000000000000000e+00)*od[2])*xd[0])*xd[0])+(((real_t)(2.0000000000000000e+00)*od[3])*xd[0]))+od[4]))); a[3] = (atan(((((((real_t)(3.0000000000000000e+00)*od[6])*xd[0])*xd[0])+(((real_t)(2.0000000000000000e+00)*od[7])*xd[0]))+od[8]))); a[4] = (atan(((((((real_t)(3.0000000000000000e+00)*od[10])*xd[0])*xd[0])+(((real_t)(2.0000000000000000e+00)*od[11])*xd[0]))+od[12]))); a[5] = ((real_t)(1.0000000000000000e+00)/((od[14]+od[15])+(real_t)(1.0000000000000000e-04))); a[6] = ((real_t)(1.0000000000000000e+00)/((od[14]+od[15])+(real_t)(1.0000000000000000e-04))); -a[7] = (exp(((real_t)(0.0000000000000000e+00)-(((((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5])-(od[17]/(real_t)(2.0000000000000000e+00))))+(od[15]*(((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9])+(od[17]/(real_t)(2.0000000000000000e+00))))))/((od[14]+od[15])+(real_t)(1.0000000000000000e-04)))+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*((((od[10]*((xd[0]*xd[0])*xd[0]))+(od[11]*(xd[0]*xd[0])))+(od[12]*xd[0]))+od[13])))+(od[17]/(real_t)(2.0000000000000000e+00)))-xd[1])))); -a[8] = (((real_t)(0.0000000000000000e+00)-(((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((od[2]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[3]*(xd[0]+xd[0])))+od[4]))+(od[15]*(((od[6]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[7]*(xd[0]+xd[0])))+od[8]))))*a[6])+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*(((od[10]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[11]*(xd[0]+xd[0])))+od[12]))))*a[7]); +a[7] = (exp(((real_t)(0.0000000000000000e+00)-(((od[14]*((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5]))+(((real_t)(1.0000000000000000e+00)-od[14])*((((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5])-(od[17]/(real_t)(2.0000000000000000e+00))))+(od[15]*(((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9])+(od[17]/(real_t)(2.0000000000000000e+00))))))/((od[14]+od[15])+(real_t)(1.0000000000000000e-04)))+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*((((od[10]*((xd[0]*xd[0])*xd[0]))+(od[11]*(xd[0]*xd[0])))+(od[12]*xd[0]))+od[13])))+(od[17]/(real_t)(2.0000000000000000e+00)))))-xd[1])))); +a[8] = (((real_t)(0.0000000000000000e+00)-((od[14]*(((od[2]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[3]*(xd[0]+xd[0])))+od[4]))+(((real_t)(1.0000000000000000e+00)-od[14])*(((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((od[2]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[3]*(xd[0]+xd[0])))+od[4]))+(od[15]*(((od[6]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[7]*(xd[0]+xd[0])))+od[8]))))*a[6])+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*(((od[10]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[11]*(xd[0]+xd[0])))+od[12]))))))*a[7]); a[9] = (((real_t)(0.0000000000000000e+00)-((real_t)(0.0000000000000000e+00)-(real_t)(1.0000000000000000e+00)))*a[7]); a[10] = ((real_t)(1.0000000000000000e+00)/((od[14]+od[15])+(real_t)(1.0000000000000000e-04))); -a[11] = (exp((((((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5])-(od[17]/(real_t)(2.0000000000000000e+00))))+(od[15]*(((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9])+(od[17]/(real_t)(2.0000000000000000e+00))))))/((od[14]+od[15])+(real_t)(1.0000000000000000e-04)))+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*((((od[10]*((xd[0]*xd[0])*xd[0]))+(od[11]*(xd[0]*xd[0])))+(od[12]*xd[0]))+od[13])))-(od[17]/(real_t)(2.0000000000000000e+00)))-xd[1]))); -a[12] = ((((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((od[2]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[3]*(xd[0]+xd[0])))+od[4]))+(od[15]*(((od[6]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[7]*(xd[0]+xd[0])))+od[8]))))*a[10])+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*(((od[10]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[11]*(xd[0]+xd[0])))+od[12])))*a[11]); +a[11] = (exp((((od[15]*((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9]))+(((real_t)(1.0000000000000000e+00)-od[15])*((((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((((od[2]*((xd[0]*xd[0])*xd[0]))+(od[3]*(xd[0]*xd[0])))+(od[4]*xd[0]))+od[5])-(od[17]/(real_t)(2.0000000000000000e+00))))+(od[15]*(((((od[6]*((xd[0]*xd[0])*xd[0]))+(od[7]*(xd[0]*xd[0])))+(od[8]*xd[0]))+od[9])+(od[17]/(real_t)(2.0000000000000000e+00))))))/((od[14]+od[15])+(real_t)(1.0000000000000000e-04)))+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*((((od[10]*((xd[0]*xd[0])*xd[0]))+(od[11]*(xd[0]*xd[0])))+(od[12]*xd[0]))+od[13])))-(od[17]/(real_t)(2.0000000000000000e+00)))))-xd[1]))); +a[12] = (((od[15]*(((od[6]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[7]*(xd[0]+xd[0])))+od[8]))+(((real_t)(1.0000000000000000e+00)-od[15])*(((((od[14]+od[15])-(od[14]*od[15]))*((od[14]*(((od[2]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[3]*(xd[0]+xd[0])))+od[4]))+(od[15]*(((od[6]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[7]*(xd[0]+xd[0])))+od[8]))))*a[10])+(((real_t)(1.0000000000000000e+00)-((od[14]+od[15])-(od[14]*od[15])))*(((od[10]*(((xd[0]+xd[0])*xd[0])+(xd[0]*xd[0])))+(od[11]*(xd[0]+xd[0])))+od[12])))))*a[11]); a[13] = (((real_t)(0.0000000000000000e+00)-(real_t)(1.0000000000000000e+00))*a[11]); a[14] = ((real_t)(1.0000000000000000e+00)/((real_t)(1.0000000000000000e+00)+(pow(((((((real_t)(3.0000000000000000e+00)*od[2])*xd[0])*xd[0])+(((real_t)(2.0000000000000000e+00)*od[3])*xd[0]))+od[4]),2)))); a[15] = ((((((real_t)(3.0000000000000000e+00)*od[2])*xd[0])+(((real_t)(3.0000000000000000e+00)*od[2])*xd[0]))+((real_t)(2.0000000000000000e+00)*od[3]))*a[14]); diff --git a/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_solver.d b/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_solver.d deleted file mode 100644 index 2dae4b9438..0000000000 --- a/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_solver.d +++ /dev/null @@ -1,3 +0,0 @@ -lib_mpc_export/acado_solver.o: lib_mpc_export/acado_solver.c \ - lib_mpc_export/acado_common.h \ - lib_mpc_export/acado_qpoases_interface.hpp diff --git a/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_solver.o b/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_solver.o deleted file mode 100644 index f91ea40ab5..0000000000 Binary files a/selfdrive/controls/lib/lateral_mpc/lib_mpc_export/acado_solver.o and /dev/null differ diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/Bounds.d b/selfdrive/controls/lib/lateral_mpc/lib_qp/Bounds.d deleted file mode 100644 index 752ec5e9f3..0000000000 --- a/selfdrive/controls/lib/lateral_mpc/lib_qp/Bounds.d +++ /dev/null @@ -1,14 +0,0 @@ -lib_qp/Bounds.o: ../../../../phonelibs/qpoases/SRC/Bounds.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/Bounds.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/SubjectTo.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Indexlist.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp \ - ../../../../phonelibs/qpoases/SRC/Indexlist.ipp \ - ../../../../phonelibs/qpoases/SRC/SubjectTo.ipp \ - ../../../../phonelibs/qpoases/SRC/Bounds.ipp diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/Bounds.o b/selfdrive/controls/lib/lateral_mpc/lib_qp/Bounds.o deleted file mode 100644 index ba30572669..0000000000 Binary files a/selfdrive/controls/lib/lateral_mpc/lib_qp/Bounds.o and /dev/null differ diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/Constraints.d b/selfdrive/controls/lib/lateral_mpc/lib_qp/Constraints.d deleted file mode 100644 index 60295bc07b..0000000000 --- a/selfdrive/controls/lib/lateral_mpc/lib_qp/Constraints.d +++ /dev/null @@ -1,14 +0,0 @@ -lib_qp/Constraints.o: ../../../../phonelibs/qpoases/SRC/Constraints.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constraints.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/SubjectTo.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Indexlist.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp \ - ../../../../phonelibs/qpoases/SRC/Indexlist.ipp \ - ../../../../phonelibs/qpoases/SRC/SubjectTo.ipp \ - ../../../../phonelibs/qpoases/SRC/Constraints.ipp diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/Constraints.o b/selfdrive/controls/lib/lateral_mpc/lib_qp/Constraints.o deleted file mode 100644 index d892c66866..0000000000 Binary files a/selfdrive/controls/lib/lateral_mpc/lib_qp/Constraints.o and /dev/null differ diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/CyclingManager.d b/selfdrive/controls/lib/lateral_mpc/lib_qp/CyclingManager.d deleted file mode 100644 index 24145d8ed3..0000000000 --- a/selfdrive/controls/lib/lateral_mpc/lib_qp/CyclingManager.d +++ /dev/null @@ -1,11 +0,0 @@ -lib_qp/CyclingManager.o: \ - ../../../../phonelibs/qpoases/SRC/CyclingManager.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/CyclingManager.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp \ - ../../../../phonelibs/qpoases/SRC/CyclingManager.ipp diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/CyclingManager.o b/selfdrive/controls/lib/lateral_mpc/lib_qp/CyclingManager.o deleted file mode 100644 index 685e25d56b..0000000000 Binary files a/selfdrive/controls/lib/lateral_mpc/lib_qp/CyclingManager.o and /dev/null differ diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/EXTRAS/SolutionAnalysis.d b/selfdrive/controls/lib/lateral_mpc/lib_qp/EXTRAS/SolutionAnalysis.d deleted file mode 100644 index 77c09376ee..0000000000 --- a/selfdrive/controls/lib/lateral_mpc/lib_qp/EXTRAS/SolutionAnalysis.d +++ /dev/null @@ -1,24 +0,0 @@ -lib_qp/EXTRAS/SolutionAnalysis.o: \ - ../../../../phonelibs/qpoases/SRC/EXTRAS/SolutionAnalysis.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/EXTRAS/SolutionAnalysis.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/QProblem.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/QProblemB.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Bounds.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/SubjectTo.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Indexlist.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp \ - ../../../../phonelibs/qpoases/SRC/Indexlist.ipp \ - ../../../../phonelibs/qpoases/SRC/SubjectTo.ipp \ - ../../../../phonelibs/qpoases/SRC/Bounds.ipp \ - ../../../../phonelibs/qpoases/SRC/QProblemB.ipp \ - ../../../../phonelibs/qpoases/INCLUDE/Constraints.hpp \ - ../../../../phonelibs/qpoases/SRC/Constraints.ipp \ - ../../../../phonelibs/qpoases/INCLUDE/CyclingManager.hpp \ - ../../../../phonelibs/qpoases/SRC/CyclingManager.ipp \ - ../../../../phonelibs/qpoases/SRC/QProblem.ipp diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/EXTRAS/SolutionAnalysis.o b/selfdrive/controls/lib/lateral_mpc/lib_qp/EXTRAS/SolutionAnalysis.o deleted file mode 100644 index 987f1e5636..0000000000 Binary files a/selfdrive/controls/lib/lateral_mpc/lib_qp/EXTRAS/SolutionAnalysis.o and /dev/null differ diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/Indexlist.d b/selfdrive/controls/lib/lateral_mpc/lib_qp/Indexlist.d deleted file mode 100644 index 6ead64cb9d..0000000000 --- a/selfdrive/controls/lib/lateral_mpc/lib_qp/Indexlist.d +++ /dev/null @@ -1,10 +0,0 @@ -lib_qp/Indexlist.o: ../../../../phonelibs/qpoases/SRC/Indexlist.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/Indexlist.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp \ - ../../../../phonelibs/qpoases/SRC/Indexlist.ipp diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/Indexlist.o b/selfdrive/controls/lib/lateral_mpc/lib_qp/Indexlist.o deleted file mode 100644 index bd77188d45..0000000000 Binary files a/selfdrive/controls/lib/lateral_mpc/lib_qp/Indexlist.o and /dev/null differ diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/MessageHandling.d b/selfdrive/controls/lib/lateral_mpc/lib_qp/MessageHandling.d deleted file mode 100644 index b5c6166aba..0000000000 --- a/selfdrive/controls/lib/lateral_mpc/lib_qp/MessageHandling.d +++ /dev/null @@ -1,9 +0,0 @@ -lib_qp/MessageHandling.o: \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/MessageHandling.o b/selfdrive/controls/lib/lateral_mpc/lib_qp/MessageHandling.o deleted file mode 100644 index 87b200d047..0000000000 Binary files a/selfdrive/controls/lib/lateral_mpc/lib_qp/MessageHandling.o and /dev/null differ diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/QProblem.d b/selfdrive/controls/lib/lateral_mpc/lib_qp/QProblem.d deleted file mode 100644 index 1f6e188af5..0000000000 --- a/selfdrive/controls/lib/lateral_mpc/lib_qp/QProblem.d +++ /dev/null @@ -1,22 +0,0 @@ -lib_qp/QProblem.o: ../../../../phonelibs/qpoases/SRC/QProblem.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/QProblem.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/QProblemB.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Bounds.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/SubjectTo.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Indexlist.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp \ - ../../../../phonelibs/qpoases/SRC/Indexlist.ipp \ - ../../../../phonelibs/qpoases/SRC/SubjectTo.ipp \ - ../../../../phonelibs/qpoases/SRC/Bounds.ipp \ - ../../../../phonelibs/qpoases/SRC/QProblemB.ipp \ - ../../../../phonelibs/qpoases/INCLUDE/Constraints.hpp \ - ../../../../phonelibs/qpoases/SRC/Constraints.ipp \ - ../../../../phonelibs/qpoases/INCLUDE/CyclingManager.hpp \ - ../../../../phonelibs/qpoases/SRC/CyclingManager.ipp \ - ../../../../phonelibs/qpoases/SRC/QProblem.ipp diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/QProblem.o b/selfdrive/controls/lib/lateral_mpc/lib_qp/QProblem.o deleted file mode 100644 index 8c179beae1..0000000000 Binary files a/selfdrive/controls/lib/lateral_mpc/lib_qp/QProblem.o and /dev/null differ diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/QProblemB.d b/selfdrive/controls/lib/lateral_mpc/lib_qp/QProblemB.d deleted file mode 100644 index 7878a825ce..0000000000 --- a/selfdrive/controls/lib/lateral_mpc/lib_qp/QProblemB.d +++ /dev/null @@ -1,16 +0,0 @@ -lib_qp/QProblemB.o: ../../../../phonelibs/qpoases/SRC/QProblemB.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/QProblemB.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Bounds.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/SubjectTo.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Indexlist.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp \ - ../../../../phonelibs/qpoases/SRC/Indexlist.ipp \ - ../../../../phonelibs/qpoases/SRC/SubjectTo.ipp \ - ../../../../phonelibs/qpoases/SRC/Bounds.ipp \ - ../../../../phonelibs/qpoases/SRC/QProblemB.ipp diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/QProblemB.o b/selfdrive/controls/lib/lateral_mpc/lib_qp/QProblemB.o deleted file mode 100644 index 9c75cb8322..0000000000 Binary files a/selfdrive/controls/lib/lateral_mpc/lib_qp/QProblemB.o and /dev/null differ diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/SubjectTo.d b/selfdrive/controls/lib/lateral_mpc/lib_qp/SubjectTo.d deleted file mode 100644 index c896d9a9fa..0000000000 --- a/selfdrive/controls/lib/lateral_mpc/lib_qp/SubjectTo.d +++ /dev/null @@ -1,12 +0,0 @@ -lib_qp/SubjectTo.o: ../../../../phonelibs/qpoases/SRC/SubjectTo.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/SubjectTo.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Indexlist.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp \ - ../../../../phonelibs/qpoases/SRC/Indexlist.ipp \ - ../../../../phonelibs/qpoases/SRC/SubjectTo.ipp diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/SubjectTo.o b/selfdrive/controls/lib/lateral_mpc/lib_qp/SubjectTo.o deleted file mode 100644 index 820c930ce3..0000000000 Binary files a/selfdrive/controls/lib/lateral_mpc/lib_qp/SubjectTo.o and /dev/null differ diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/Utils.d b/selfdrive/controls/lib/lateral_mpc/lib_qp/Utils.d deleted file mode 100644 index 58f35a0653..0000000000 --- a/selfdrive/controls/lib/lateral_mpc/lib_qp/Utils.d +++ /dev/null @@ -1,8 +0,0 @@ -lib_qp/Utils.o: ../../../../phonelibs/qpoases/SRC/Utils.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp diff --git a/selfdrive/controls/lib/lateral_mpc/lib_qp/Utils.o b/selfdrive/controls/lib/lateral_mpc/lib_qp/Utils.o deleted file mode 100644 index ef645ef188..0000000000 Binary files a/selfdrive/controls/lib/lateral_mpc/lib_qp/Utils.o and /dev/null differ diff --git a/selfdrive/controls/lib/lateral_mpc/libmpc.so b/selfdrive/controls/lib/lateral_mpc/libmpc.so deleted file mode 100755 index 3fd1325502..0000000000 Binary files a/selfdrive/controls/lib/lateral_mpc/libmpc.so and /dev/null differ diff --git a/selfdrive/controls/lib/lateral_mpc/libmpc_py.py b/selfdrive/controls/lib/lateral_mpc/libmpc_py.py index 3af46c304e..6b86d9565a 100644 --- a/selfdrive/controls/lib/lateral_mpc/libmpc_py.py +++ b/selfdrive/controls/lib/lateral_mpc/libmpc_py.py @@ -18,7 +18,7 @@ typedef struct { double y[21]; double psi[21]; double delta[21]; - double rate[21]; + double rate[20]; double cost; } log_t; diff --git a/selfdrive/controls/lib/long_mpc.py b/selfdrive/controls/lib/long_mpc.py index 19fb706deb..9d43e97f26 100644 --- a/selfdrive/controls/lib/long_mpc.py +++ b/selfdrive/controls/lib/long_mpc.py @@ -1,3 +1,4 @@ +import os import numpy as np import selfdrive.messaging as messaging @@ -7,6 +8,8 @@ from selfdrive.controls.lib.radar_helpers import _LEAD_ACCEL_TAU from selfdrive.controls.lib.longitudinal_mpc import libmpc_py from selfdrive.controls.lib.drive_helpers import MPC_COST_LONG +LOG_MPC = os.environ.get('LOG_MPC', False) + class LongitudinalMpc(object): def __init__(self, mpc_id, live_longitudinal_mpc): @@ -56,7 +59,7 @@ class LongitudinalMpc(object): self.cur_state[0].a_ego = a def update(self, CS, lead, v_cruise_setpoint): - v_ego = CS.carState.vEgo + v_ego = CS.vEgo # Setup current mpc state self.cur_state[0].x_ego = 0.0 @@ -92,7 +95,9 @@ class LongitudinalMpc(object): t = sec_since_boot() n_its = self.libmpc.run_mpc(self.cur_state, self.mpc_solution, self.a_lead_tau, a_lead) duration = int((sec_since_boot() - t) * 1e9) - self.send_mpc_solution(n_its, duration) + + if LOG_MPC: + self.send_mpc_solution(n_its, duration) # Get solution. MPC timestep is 0.2 s, so interpolation to 0.05 s is needed self.v_mpc = self.mpc_solution[0].v_ego[1] @@ -116,5 +121,5 @@ class LongitudinalMpc(object): self.cur_state[0].v_ego = v_ego self.cur_state[0].a_ego = 0.0 self.v_mpc = v_ego - self.a_mpc = CS.carState.aEgo + self.a_mpc = CS.aEgo self.prev_lead_status = False diff --git a/selfdrive/controls/lib/longitudinal_mpc/Makefile b/selfdrive/controls/lib/longitudinal_mpc/Makefile index 17f78eada9..e00914c214 100644 --- a/selfdrive/controls/lib/longitudinal_mpc/Makefile +++ b/selfdrive/controls/lib/longitudinal_mpc/Makefile @@ -14,11 +14,13 @@ QPOASES_FLAGS = -I$(PHONELIBS)/qpoases -I$(PHONELIBS)/qpoases/INCLUDE -I$(PHONEL ACADO_FLAGS = -I$(PHONELIBS)/acado/include -I$(PHONELIBS)/acado/include/acado ifeq ($(UNAME_S),Darwin) - ACADO_LIBS := -lacado_toolkit_s +ACADO_LIBS := -lacado_toolkit_s else ifeq ($(UNAME_M),aarch64) - ACADO_LIBS := -L $(PHONELIBS)/acado/aarch64/lib -l:libacado_toolkit.a -l:libacado_casadi.a -l:libacado_csparse.a +ACADO_LIBS := -L $(PHONELIBS)/acado/aarch64/lib -l:libacado_toolkit.a -l:libacado_casadi.a -l:libacado_csparse.a +CFLAGS += -mcpu=cortex-a57 +CXXFLAGS += -mcpu=cortex-a57 else - ACADO_LIBS := -L $(PHONELIBS)/acado/x64/lib -l:libacado_toolkit.a -l:libacado_casadi.a -l:libacado_csparse.a +ACADO_LIBS := -L $(PHONELIBS)/acado/x64/lib -l:libacado_toolkit.a -l:libacado_casadi.a -l:libacado_csparse.a endif OBJS = \ diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_auxiliary_functions.d b/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_auxiliary_functions.d deleted file mode 100644 index 50c6a60d1f..0000000000 --- a/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_auxiliary_functions.d +++ /dev/null @@ -1,5 +0,0 @@ -lib_mpc_export/acado_auxiliary_functions.o: \ - lib_mpc_export/acado_auxiliary_functions.c \ - lib_mpc_export/acado_auxiliary_functions.h \ - lib_mpc_export/acado_common.h \ - lib_mpc_export/acado_qpoases_interface.hpp diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_auxiliary_functions.o b/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_auxiliary_functions.o deleted file mode 100644 index 5466ca143b..0000000000 Binary files a/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_auxiliary_functions.o and /dev/null differ diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_integrator.d b/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_integrator.d deleted file mode 100644 index 7c057e5ec0..0000000000 --- a/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_integrator.d +++ /dev/null @@ -1,3 +0,0 @@ -lib_mpc_export/acado_integrator.o: lib_mpc_export/acado_integrator.c \ - lib_mpc_export/acado_common.h \ - lib_mpc_export/acado_qpoases_interface.hpp diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_integrator.o b/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_integrator.o deleted file mode 100644 index 2ee2d13004..0000000000 Binary files a/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_integrator.o and /dev/null differ diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_qpoases_interface.d b/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_qpoases_interface.d deleted file mode 100644 index ba3c6ef1c8..0000000000 --- a/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_qpoases_interface.d +++ /dev/null @@ -1,24 +0,0 @@ -lib_mpc_export/acado_qpoases_interface.o: \ - lib_mpc_export/acado_qpoases_interface.cpp \ - lib_mpc_export/acado_common.h \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/QProblem.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/QProblemB.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Bounds.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/SubjectTo.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Indexlist.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp \ - ../../../../phonelibs/qpoases/SRC/Indexlist.ipp \ - ../../../../phonelibs/qpoases/SRC/SubjectTo.ipp \ - ../../../../phonelibs/qpoases/SRC/Bounds.ipp \ - ../../../../phonelibs/qpoases/SRC/QProblemB.ipp \ - ../../../../phonelibs/qpoases/INCLUDE/Constraints.hpp \ - ../../../../phonelibs/qpoases/SRC/Constraints.ipp \ - ../../../../phonelibs/qpoases/INCLUDE/CyclingManager.hpp \ - ../../../../phonelibs/qpoases/SRC/CyclingManager.ipp \ - ../../../../phonelibs/qpoases/SRC/QProblem.ipp diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_qpoases_interface.o b/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_qpoases_interface.o deleted file mode 100644 index 897e0e0fbd..0000000000 Binary files a/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_qpoases_interface.o and /dev/null differ diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_solver.d b/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_solver.d deleted file mode 100644 index 2dae4b9438..0000000000 --- a/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_solver.d +++ /dev/null @@ -1,3 +0,0 @@ -lib_mpc_export/acado_solver.o: lib_mpc_export/acado_solver.c \ - lib_mpc_export/acado_common.h \ - lib_mpc_export/acado_qpoases_interface.hpp diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_solver.o b/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_solver.o deleted file mode 100644 index bcdc5b9e81..0000000000 Binary files a/selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/acado_solver.o and /dev/null differ diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Bounds.d b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Bounds.d deleted file mode 100644 index 752ec5e9f3..0000000000 --- a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Bounds.d +++ /dev/null @@ -1,14 +0,0 @@ -lib_qp/Bounds.o: ../../../../phonelibs/qpoases/SRC/Bounds.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/Bounds.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/SubjectTo.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Indexlist.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp \ - ../../../../phonelibs/qpoases/SRC/Indexlist.ipp \ - ../../../../phonelibs/qpoases/SRC/SubjectTo.ipp \ - ../../../../phonelibs/qpoases/SRC/Bounds.ipp diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Bounds.o b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Bounds.o deleted file mode 100644 index 28794f8185..0000000000 Binary files a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Bounds.o and /dev/null differ diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Constraints.d b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Constraints.d deleted file mode 100644 index 60295bc07b..0000000000 --- a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Constraints.d +++ /dev/null @@ -1,14 +0,0 @@ -lib_qp/Constraints.o: ../../../../phonelibs/qpoases/SRC/Constraints.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constraints.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/SubjectTo.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Indexlist.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp \ - ../../../../phonelibs/qpoases/SRC/Indexlist.ipp \ - ../../../../phonelibs/qpoases/SRC/SubjectTo.ipp \ - ../../../../phonelibs/qpoases/SRC/Constraints.ipp diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Constraints.o b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Constraints.o deleted file mode 100644 index 81352513fd..0000000000 Binary files a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Constraints.o and /dev/null differ diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/CyclingManager.d b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/CyclingManager.d deleted file mode 100644 index 24145d8ed3..0000000000 --- a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/CyclingManager.d +++ /dev/null @@ -1,11 +0,0 @@ -lib_qp/CyclingManager.o: \ - ../../../../phonelibs/qpoases/SRC/CyclingManager.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/CyclingManager.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp \ - ../../../../phonelibs/qpoases/SRC/CyclingManager.ipp diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/CyclingManager.o b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/CyclingManager.o deleted file mode 100644 index 321db37ef2..0000000000 Binary files a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/CyclingManager.o and /dev/null differ diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/EXTRAS/SolutionAnalysis.d b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/EXTRAS/SolutionAnalysis.d deleted file mode 100644 index 77c09376ee..0000000000 --- a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/EXTRAS/SolutionAnalysis.d +++ /dev/null @@ -1,24 +0,0 @@ -lib_qp/EXTRAS/SolutionAnalysis.o: \ - ../../../../phonelibs/qpoases/SRC/EXTRAS/SolutionAnalysis.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/EXTRAS/SolutionAnalysis.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/QProblem.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/QProblemB.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Bounds.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/SubjectTo.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Indexlist.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp \ - ../../../../phonelibs/qpoases/SRC/Indexlist.ipp \ - ../../../../phonelibs/qpoases/SRC/SubjectTo.ipp \ - ../../../../phonelibs/qpoases/SRC/Bounds.ipp \ - ../../../../phonelibs/qpoases/SRC/QProblemB.ipp \ - ../../../../phonelibs/qpoases/INCLUDE/Constraints.hpp \ - ../../../../phonelibs/qpoases/SRC/Constraints.ipp \ - ../../../../phonelibs/qpoases/INCLUDE/CyclingManager.hpp \ - ../../../../phonelibs/qpoases/SRC/CyclingManager.ipp \ - ../../../../phonelibs/qpoases/SRC/QProblem.ipp diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/EXTRAS/SolutionAnalysis.o b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/EXTRAS/SolutionAnalysis.o deleted file mode 100644 index 1816ece0ed..0000000000 Binary files a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/EXTRAS/SolutionAnalysis.o and /dev/null differ diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Indexlist.d b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Indexlist.d deleted file mode 100644 index 6ead64cb9d..0000000000 --- a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Indexlist.d +++ /dev/null @@ -1,10 +0,0 @@ -lib_qp/Indexlist.o: ../../../../phonelibs/qpoases/SRC/Indexlist.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/Indexlist.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp \ - ../../../../phonelibs/qpoases/SRC/Indexlist.ipp diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Indexlist.o b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Indexlist.o deleted file mode 100644 index c8bdbe979b..0000000000 Binary files a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Indexlist.o and /dev/null differ diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/MessageHandling.d b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/MessageHandling.d deleted file mode 100644 index b5c6166aba..0000000000 --- a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/MessageHandling.d +++ /dev/null @@ -1,9 +0,0 @@ -lib_qp/MessageHandling.o: \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/MessageHandling.o b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/MessageHandling.o deleted file mode 100644 index 87b200d047..0000000000 Binary files a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/MessageHandling.o and /dev/null differ diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/QProblem.d b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/QProblem.d deleted file mode 100644 index 1f6e188af5..0000000000 --- a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/QProblem.d +++ /dev/null @@ -1,22 +0,0 @@ -lib_qp/QProblem.o: ../../../../phonelibs/qpoases/SRC/QProblem.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/QProblem.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/QProblemB.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Bounds.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/SubjectTo.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Indexlist.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp \ - ../../../../phonelibs/qpoases/SRC/Indexlist.ipp \ - ../../../../phonelibs/qpoases/SRC/SubjectTo.ipp \ - ../../../../phonelibs/qpoases/SRC/Bounds.ipp \ - ../../../../phonelibs/qpoases/SRC/QProblemB.ipp \ - ../../../../phonelibs/qpoases/INCLUDE/Constraints.hpp \ - ../../../../phonelibs/qpoases/SRC/Constraints.ipp \ - ../../../../phonelibs/qpoases/INCLUDE/CyclingManager.hpp \ - ../../../../phonelibs/qpoases/SRC/CyclingManager.ipp \ - ../../../../phonelibs/qpoases/SRC/QProblem.ipp diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/QProblem.o b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/QProblem.o deleted file mode 100644 index 0d79872a24..0000000000 Binary files a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/QProblem.o and /dev/null differ diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/QProblemB.d b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/QProblemB.d deleted file mode 100644 index 7878a825ce..0000000000 --- a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/QProblemB.d +++ /dev/null @@ -1,16 +0,0 @@ -lib_qp/QProblemB.o: ../../../../phonelibs/qpoases/SRC/QProblemB.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/QProblemB.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Bounds.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/SubjectTo.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Indexlist.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp \ - ../../../../phonelibs/qpoases/SRC/Indexlist.ipp \ - ../../../../phonelibs/qpoases/SRC/SubjectTo.ipp \ - ../../../../phonelibs/qpoases/SRC/Bounds.ipp \ - ../../../../phonelibs/qpoases/SRC/QProblemB.ipp diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/QProblemB.o b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/QProblemB.o deleted file mode 100644 index 9ad8900182..0000000000 Binary files a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/QProblemB.o and /dev/null differ diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/SubjectTo.d b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/SubjectTo.d deleted file mode 100644 index c896d9a9fa..0000000000 --- a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/SubjectTo.d +++ /dev/null @@ -1,12 +0,0 @@ -lib_qp/SubjectTo.o: ../../../../phonelibs/qpoases/SRC/SubjectTo.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/SubjectTo.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Indexlist.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp \ - ../../../../phonelibs/qpoases/SRC/Indexlist.ipp \ - ../../../../phonelibs/qpoases/SRC/SubjectTo.ipp diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/SubjectTo.o b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/SubjectTo.o deleted file mode 100644 index f5b1695e75..0000000000 Binary files a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/SubjectTo.o and /dev/null differ diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Utils.d b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Utils.d deleted file mode 100644 index 58f35a0653..0000000000 --- a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Utils.d +++ /dev/null @@ -1,8 +0,0 @@ -lib_qp/Utils.o: ../../../../phonelibs/qpoases/SRC/Utils.cpp \ - ../../../../phonelibs/qpoases/INCLUDE/Utils.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/MessageHandling.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Types.hpp \ - ../../../../phonelibs/qpoases/INCLUDE/Constants.hpp \ - lib_mpc_export/acado_qpoases_interface.hpp \ - ../../../../phonelibs/qpoases/SRC/MessageHandling.ipp \ - ../../../../phonelibs/qpoases/SRC/Utils.ipp diff --git a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Utils.o b/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Utils.o deleted file mode 100644 index ef645ef188..0000000000 Binary files a/selfdrive/controls/lib/longitudinal_mpc/lib_qp/Utils.o and /dev/null differ diff --git a/selfdrive/controls/lib/longitudinal_mpc/libmpc1.so b/selfdrive/controls/lib/longitudinal_mpc/libmpc1.so deleted file mode 100755 index 30f7be05ac..0000000000 Binary files a/selfdrive/controls/lib/longitudinal_mpc/libmpc1.so and /dev/null differ diff --git a/selfdrive/controls/lib/longitudinal_mpc/libmpc_py.py b/selfdrive/controls/lib/longitudinal_mpc/libmpc_py.py index 354a4a493e..95e9135a81 100644 --- a/selfdrive/controls/lib/longitudinal_mpc/libmpc_py.py +++ b/selfdrive/controls/lib/longitudinal_mpc/libmpc_py.py @@ -29,7 +29,7 @@ def _get_libmpc(mpc_id): double x_ego[21]; double v_ego[21]; double a_ego[21]; - double j_ego[21]; + double j_ego[20]; double x_l[21]; double v_l[21]; double a_l[21]; diff --git a/selfdrive/controls/lib/longitudinal_mpc/longitudinal_mpc.c b/selfdrive/controls/lib/longitudinal_mpc/longitudinal_mpc.c index e903ccc758..d4bfee8c8a 100644 --- a/selfdrive/controls/lib/longitudinal_mpc/longitudinal_mpc.c +++ b/selfdrive/controls/lib/longitudinal_mpc/longitudinal_mpc.c @@ -26,12 +26,12 @@ typedef struct { double x_ego[N+1]; double v_ego[N+1]; double a_ego[N+1]; - double j_ego[N+1]; - double x_l[N+1]; - double v_l[N+1]; - double a_l[N+1]; - double t[N+1]; - double cost; + double j_ego[N]; + double x_l[N+1]; + double v_l[N+1]; + double a_l[N+1]; + double t[N+1]; + double cost; } log_t; void init(double ttcCost, double distanceCost, double accelerationCost, double jerkCost){ @@ -56,14 +56,15 @@ void init(double ttcCost, double distanceCost, double accelerationCost, double j if (i > 4){ f = STEP_MULTIPLIER; } - acadoVariables.W[16 * i + 0] = ttcCost * f; // exponential cost for time-to-collision (ttc) - acadoVariables.W[16 * i + 5] = distanceCost * f; // desired distance - acadoVariables.W[16 * i + 10] = accelerationCost * f; // acceleration - acadoVariables.W[16 * i + 15] = jerkCost * f; // jerk + // Setup diagonal entries + acadoVariables.W[NY*NY*i + (NY+1)*0] = ttcCost * f; // exponential cost for time-to-collision (ttc) + acadoVariables.W[NY*NY*i + (NY+1)*1] = distanceCost * f; // desired distance + acadoVariables.W[NY*NY*i + (NY+1)*2] = accelerationCost * f; // acceleration + acadoVariables.W[NY*NY*i + (NY+1)*3] = jerkCost * f; // jerk } - acadoVariables.WN[0] = ttcCost * STEP_MULTIPLIER; // exponential cost for danger zone - acadoVariables.WN[4] = distanceCost * STEP_MULTIPLIER; // desired distance - acadoVariables.WN[8] = accelerationCost * STEP_MULTIPLIER; // acceleration + acadoVariables.WN[(NYN+1)*0] = ttcCost * STEP_MULTIPLIER; // exponential cost for danger zone + acadoVariables.WN[(NYN+1)*1] = distanceCost * STEP_MULTIPLIER; // desired distance + acadoVariables.WN[(NYN+1)*2] = accelerationCost * STEP_MULTIPLIER; // acceleration } @@ -154,12 +155,15 @@ int run_mpc(state_t * x0, log_t * solution, double l, double a_l_0){ acado_preparationStep(); acado_feedbackStep(); - for (i = 0; i <= N; i++){ + for (i = 0; i <= N; i++){ solution->x_ego[i] = acadoVariables.x[i*NX]; - solution->v_ego[i] = acadoVariables.x[i*NX+1]; + solution->v_ego[i] = acadoVariables.x[i*NX+1]; solution->a_ego[i] = acadoVariables.x[i*NX+2]; - solution->j_ego[i] = acadoVariables.u[i]; - } + + if (i < N){ + solution->j_ego[i] = acadoVariables.u[i]; + } + } solution->cost = acado_getObjective(); // Dont shift states here. Current solution is closer to next timestep than if diff --git a/selfdrive/controls/lib/longitudinal_mpc/longitudinal_mpc.d b/selfdrive/controls/lib/longitudinal_mpc/longitudinal_mpc.d deleted file mode 100644 index 34a2a0d20c..0000000000 --- a/selfdrive/controls/lib/longitudinal_mpc/longitudinal_mpc.d +++ /dev/null @@ -1,3 +0,0 @@ -longitudinal_mpc.o: longitudinal_mpc.c lib_mpc_export/acado_common.h \ - lib_mpc_export/acado_qpoases_interface.hpp \ - lib_mpc_export/acado_auxiliary_functions.h diff --git a/selfdrive/controls/lib/longitudinal_mpc/longitudinal_mpc.o b/selfdrive/controls/lib/longitudinal_mpc/longitudinal_mpc.o deleted file mode 100644 index f10c23217a..0000000000 Binary files a/selfdrive/controls/lib/longitudinal_mpc/longitudinal_mpc.o and /dev/null differ diff --git a/selfdrive/controls/lib/model_parser.py b/selfdrive/controls/lib/model_parser.py index 747e918f75..0b4bb241db 100644 --- a/selfdrive/controls/lib/model_parser.py +++ b/selfdrive/controls/lib/model_parser.py @@ -1,4 +1,5 @@ from common.numpy_fast import interp +import numpy as np from selfdrive.controls.lib.latcontrol_helpers import model_polyfit, calc_desired_path, compute_path_pinv CAMERA_OFFSET = 0.06 # m from center car to camera @@ -18,48 +19,48 @@ class ModelParser(object): self.lane_width = 3.7 self.l_prob = 0. self.r_prob = 0. + self.x_points = np.arange(50) def update(self, v_ego, md): - if md is not None: - p_poly = model_polyfit(md.model.path.points, self._path_pinv) # predicted path - l_poly = model_polyfit(md.model.leftLane.points, self._path_pinv) # left line - r_poly = model_polyfit(md.model.rightLane.points, self._path_pinv) # right line + if len(md.leftLane.poly): + l_poly = np.array(md.leftLane.poly) + r_poly = np.array(md.rightLane.poly) + p_poly = np.array(md.path.poly) + else: + l_poly = model_polyfit(md.leftLane.points, self._path_pinv) # left line + r_poly = model_polyfit(md.rightLane.points, self._path_pinv) # right line + p_poly = model_polyfit(md.path.points, self._path_pinv) # predicted path - # only offset left and right lane lines; offsetting p_poly does not make sense - l_poly[3] += CAMERA_OFFSET - r_poly[3] += CAMERA_OFFSET + # only offset left and right lane lines; offsetting p_poly does not make sense + l_poly[3] += CAMERA_OFFSET + r_poly[3] += CAMERA_OFFSET - p_prob = 1. # model does not tell this probability yet, so set to 1 for now - l_prob = md.model.leftLane.prob # left line prob - r_prob = md.model.rightLane.prob # right line prob + p_prob = 1. # model does not tell this probability yet, so set to 1 for now + l_prob = md.leftLane.prob # left line prob + r_prob = md.rightLane.prob # right line prob - # Find current lanewidth - lr_prob = l_prob * r_prob - self.lane_width_certainty += 0.05 * (lr_prob - self.lane_width_certainty) - current_lane_width = abs(l_poly[3] - r_poly[3]) - self.lane_width_estimate += 0.005 * (current_lane_width - self.lane_width_estimate) - speed_lane_width = interp(v_ego, [0., 31.], [3., 3.8]) - self.lane_width = self.lane_width_certainty * self.lane_width_estimate + \ - (1 - self.lane_width_certainty) * speed_lane_width + # Find current lanewidth + lr_prob = l_prob * r_prob + self.lane_width_certainty += 0.05 * (lr_prob - self.lane_width_certainty) + current_lane_width = abs(l_poly[3] - r_poly[3]) + self.lane_width_estimate += 0.005 * (current_lane_width - self.lane_width_estimate) + speed_lane_width = interp(v_ego, [0., 31.], [3., 3.8]) + self.lane_width = self.lane_width_certainty * self.lane_width_estimate + \ + (1 - self.lane_width_certainty) * speed_lane_width - lane_width_diff = abs(self.lane_width - current_lane_width) - lane_r_prob = interp(lane_width_diff, [0.3, 1.0], [1.0, 0.0]) + self.lead_dist = md.lead.dist + self.lead_prob = md.lead.prob + self.lead_var = md.lead.std**2 - r_prob *= lane_r_prob + # compute target path + self.d_poly, self.c_poly, self.c_prob = calc_desired_path( + l_poly, r_poly, p_poly, l_prob, r_prob, p_prob, v_ego, self.lane_width) - self.lead_dist = md.model.lead.dist - self.lead_prob = md.model.lead.prob - self.lead_var = md.model.lead.std**2 + self.r_poly = r_poly + self.r_prob = r_prob - # compute target path - self.d_poly, self.c_poly, self.c_prob = calc_desired_path( - l_poly, r_poly, p_poly, l_prob, r_prob, p_prob, v_ego, self.lane_width) + self.l_poly = l_poly + self.l_prob = l_prob - self.r_poly = r_poly - self.r_prob = r_prob - - self.l_poly = l_poly - self.l_prob = l_prob - - self.p_poly = p_poly - self.p_prob = p_prob + self.p_poly = p_poly + self.p_prob = p_prob diff --git a/selfdrive/controls/lib/pathplanner.py b/selfdrive/controls/lib/pathplanner.py index f3cdffdfd2..cbd144edcd 100644 --- a/selfdrive/controls/lib/pathplanner.py +++ b/selfdrive/controls/lib/pathplanner.py @@ -1,4 +1,4 @@ -import zmq +import os import math import numpy as np @@ -10,6 +10,8 @@ from selfdrive.controls.lib.drive_helpers import MPC_COST_LAT from selfdrive.controls.lib.model_parser import ModelParser import selfdrive.messaging as messaging +LOG_MPC = os.environ.get('LOG_MPC', False) + def calc_states_after_delay(states, v_ego, steer_angle, curvature_factor, steer_ratio, delay): states[0].x = v_ego * delay @@ -26,12 +28,11 @@ class PathPlanner(object): self.last_cloudlog_t = 0 - context = zmq.Context() - self.plan = messaging.pub_sock(context, service_list['pathPlan'].port) - self.livempc = messaging.pub_sock(context, service_list['liveMpc'].port) + self.plan = messaging.pub_sock(service_list['pathPlan'].port) + self.livempc = messaging.pub_sock(service_list['liveMpc'].port) self.setup_mpc(CP.steerRateCost) - self.invalid_counter = 0 + self.solution_invalid_cnt = 0 def setup_mpc(self, steer_rate_cost): self.libmpc = libmpc_py.libmpc @@ -49,31 +50,34 @@ class PathPlanner(object): self.angle_steers_des_prev = 0.0 self.angle_steers_des_time = 0.0 - def update(self, rcv_times, CP, VM, CS, md, controls_state, live_parameters): - v_ego = CS.carState.vEgo - angle_steers = CS.carState.steeringAngle - active = controls_state.controlsState.active + self.l_poly = libmpc_py.ffi.new("double[4]") + self.r_poly = libmpc_py.ffi.new("double[4]") + self.p_poly = libmpc_py.ffi.new("double[4]") + + def update(self, sm, CP, VM): + v_ego = sm['carState'].vEgo + angle_steers = sm['carState'].steeringAngle + active = sm['controlsState'].active - angle_offset_average = live_parameters.liveParameters.angleOffsetAverage - angle_offset_bias = controls_state.controlsState.angleModelBias + angle_offset_average + angle_offset_average = sm['liveParameters'].angleOffsetAverage + angle_offset_bias = sm['controlsState'].angleModelBias + angle_offset_average - self.MP.update(v_ego, md) + self.MP.update(v_ego, sm['model']) # Run MPC self.angle_steers_des_prev = self.angle_steers_des_mpc - VM.update_params(live_parameters.liveParameters.stiffnessFactor, live_parameters.liveParameters.steerRatio) + VM.update_params(sm['liveParameters'].stiffnessFactor, sm['liveParameters'].steerRatio) curvature_factor = VM.curvature_factor(v_ego) - - l_poly = libmpc_py.ffi.new("double[4]", list(self.MP.l_poly)) - r_poly = libmpc_py.ffi.new("double[4]", list(self.MP.r_poly)) - p_poly = libmpc_py.ffi.new("double[4]", list(self.MP.p_poly)) + self.l_poly = list(self.MP.l_poly) + self.r_poly = list(self.MP.r_poly) + self.p_poly = list(self.MP.p_poly) # account for actuation delay self.cur_state = calc_states_after_delay(self.cur_state, v_ego, angle_steers - angle_offset_average, curvature_factor, VM.sR, CP.steerActuatorDelay) v_ego_mpc = max(v_ego, 5.0) # avoid mpc roughness due to low speed self.libmpc.run_mpc(self.cur_state, self.mpc_solution, - l_poly, r_poly, p_poly, + self.l_poly, self.r_poly, self.p_poly, self.MP.l_prob, self.MP.r_prob, self.MP.p_prob, curvature_factor, v_ego_mpc, self.MP.lane_width) # reset to current steer angle if not active or overriding @@ -93,46 +97,44 @@ class PathPlanner(object): t = sec_since_boot() if mpc_nans: self.libmpc.init(MPC_COST_LAT.PATH, MPC_COST_LAT.LANE, MPC_COST_LAT.HEADING, CP.steerRateCost) - self.cur_state[0].delta = math.radians(angle_steers) / VM.sR + self.cur_state[0].delta = math.radians(angle_steers - angle_offset_bias) / VM.sR if t > self.last_cloudlog_t + 5.0: self.last_cloudlog_t = t cloudlog.warning("Lateral mpc - nan: True") if self.mpc_solution[0].cost > 20000. or mpc_nans: # TODO: find a better way to detect when MPC did not converge - self.invalid_counter += 1 + self.solution_invalid_cnt += 1 else: - self.invalid_counter = 0 - - cur_time = sec_since_boot() - model_dead = cur_time - rcv_times['model'] > 0.5 - plan_valid = self.invalid_counter < 2 + self.solution_invalid_cnt = 0 + plan_solution_valid = self.solution_invalid_cnt < 2 plan_send = messaging.new_message() plan_send.init('pathPlan') + plan_send.valid = sm.all_alive_and_valid(service_list=['carState', 'controlsState', 'liveParameters', 'model']) plan_send.pathPlan.laneWidth = float(self.MP.lane_width) plan_send.pathPlan.dPoly = [float(x) for x in self.MP.d_poly] plan_send.pathPlan.cPoly = [float(x) for x in self.MP.c_poly] plan_send.pathPlan.cProb = float(self.MP.c_prob) - plan_send.pathPlan.lPoly = [float(x) for x in l_poly] + plan_send.pathPlan.lPoly = [float(x) for x in self.l_poly] plan_send.pathPlan.lProb = float(self.MP.l_prob) - plan_send.pathPlan.rPoly = [float(x) for x in r_poly] + plan_send.pathPlan.rPoly = [float(x) for x in self.r_poly] plan_send.pathPlan.rProb = float(self.MP.r_prob) plan_send.pathPlan.angleSteers = float(self.angle_steers_des_mpc) plan_send.pathPlan.rateSteers = float(rate_desired) plan_send.pathPlan.angleOffset = float(angle_offset_average) - plan_send.pathPlan.valid = bool(plan_valid) - plan_send.pathPlan.paramsValid = bool(live_parameters.liveParameters.valid) - plan_send.pathPlan.sensorValid = bool(live_parameters.liveParameters.sensorValid) - plan_send.pathPlan.modelValid = bool(not model_dead) + plan_send.pathPlan.mpcSolutionValid = bool(plan_solution_valid) + plan_send.pathPlan.paramsValid = bool(sm['liveParameters'].valid) + plan_send.pathPlan.sensorValid = bool(sm['liveParameters'].sensorValid) self.plan.send(plan_send.to_bytes()) - dat = messaging.new_message() - dat.init('liveMpc') - dat.liveMpc.x = list(self.mpc_solution[0].x) - dat.liveMpc.y = list(self.mpc_solution[0].y) - dat.liveMpc.psi = list(self.mpc_solution[0].psi) - dat.liveMpc.delta = list(self.mpc_solution[0].delta) - dat.liveMpc.cost = self.mpc_solution[0].cost - self.livempc.send(dat.to_bytes()) + if LOG_MPC: + dat = messaging.new_message() + dat.init('liveMpc') + dat.liveMpc.x = list(self.mpc_solution[0].x) + dat.liveMpc.y = list(self.mpc_solution[0].y) + dat.liveMpc.psi = list(self.mpc_solution[0].psi) + dat.liveMpc.delta = list(self.mpc_solution[0].delta) + dat.liveMpc.cost = self.mpc_solution[0].cost + self.livempc.send(dat.to_bytes()) diff --git a/selfdrive/controls/lib/planner.py b/selfdrive/controls/lib/planner.py index c8c3d1805a..9aaec513be 100755 --- a/selfdrive/controls/lib/planner.py +++ b/selfdrive/controls/lib/planner.py @@ -7,7 +7,7 @@ from common.numpy_fast import interp import selfdrive.messaging as messaging from cereal import car -from common.realtime import sec_since_boot +from common.realtime import sec_since_boot, DT_PLAN from selfdrive.swaglog import cloudlog from selfdrive.config import Conversions as CV from selfdrive.services import service_list @@ -18,7 +18,7 @@ from selfdrive.controls.lib.long_mpc import LongitudinalMpc NO_CURVATURE_SPEED = 200. * CV.MPH_TO_MS -_DT_MPC = 0.2 # 5Hz +LON_MPC_STEP = 0.2 # first step is 0.2s MAX_SPEED_ERROR = 2.0 AWARENESS_DECEL = -0.2 # car smoothly decel at .2m/s^2 when user is distracted @@ -64,12 +64,11 @@ def limit_accel_in_turns(v_ego, angle_steers, a_target, CP): class Planner(object): def __init__(self, CP, fcw_enabled): - context = zmq.Context() self.CP = CP self.poller = zmq.Poller() - self.plan = messaging.pub_sock(context, service_list['plan'].port) - self.live_longitudinal_mpc = messaging.pub_sock(context, service_list['liveLongitudinalMpc'].port) + self.plan = messaging.pub_sock(service_list['plan'].port) + self.live_longitudinal_mpc = messaging.pub_sock(service_list['liveLongitudinalMpc'].port) self.mpc1 = LongitudinalMpc(1, self.live_longitudinal_mpc) self.mpc2 = LongitudinalMpc(2, self.live_longitudinal_mpc) @@ -114,18 +113,18 @@ class Planner(object): self.v_acc_future = min([self.mpc1.v_mpc_future, self.mpc2.v_mpc_future, v_cruise_setpoint]) - def update(self, rcv_times, CS, CP, VM, PP, radar_state, controls_state, md, live_map_data): + def update(self, sm, CP, VM, PP, live_map_data): """Gets called when new radarState is available""" cur_time = sec_since_boot() - v_ego = CS.carState.vEgo + v_ego = sm['carState'].vEgo - long_control_state = controls_state.controlsState.longControlState - v_cruise_kph = controls_state.controlsState.vCruise - force_slow_decel = controls_state.controlsState.forceDecel + long_control_state = sm['controlsState'].longControlState + v_cruise_kph = sm['controlsState'].vCruise + force_slow_decel = sm['controlsState'].forceDecel v_cruise_setpoint = v_cruise_kph * CV.KPH_TO_MS - lead_1 = radar_state.radarState.leadOne - lead_2 = radar_state.radarState.leadTwo + lead_1 = sm['radarState'].leadOne + lead_2 = sm['radarState'].leadTwo enabled = (long_control_state == LongCtrlState.pid) or (long_control_state == LongCtrlState.stopping) following = lead_1.status and lead_1.dRel < 45.0 and lead_1.vLeadK > v_ego and lead_1.aLeadK > 0.0 @@ -133,8 +132,8 @@ class Planner(object): v_speedlimit = NO_CURVATURE_SPEED v_curvature = NO_CURVATURE_SPEED - map_age = cur_time - rcv_times['liveMapData'] - map_valid = live_map_data.liveMapData.mapValid and map_age < 10.0 + #map_age = cur_time - rcv_times['liveMapData'] + map_valid = False # live_map_data.liveMapData.mapValid and map_age < 10.0 # Speed limit and curvature set_speed_limit_active = self.params.get("LimitSetSpeed") == "1" and self.params.get("SpeedLimitOffset") is not None @@ -157,7 +156,7 @@ class Planner(object): if enabled: accel_limits = [float(x) for x in calc_cruise_accel_limits(v_ego, following)] jerk_limits = [min(-0.1, accel_limits[0]), max(0.1, accel_limits[1])] # TODO: make a separate lookup for jerk tuning - accel_limits = limit_accel_in_turns(v_ego, CS.carState.steeringAngle, accel_limits, self.CP) + accel_limits = limit_accel_in_turns(v_ego, sm['carState'].steeringAngle, accel_limits, self.CP) if force_slow_decel: # if required so, force a smooth deceleration @@ -174,12 +173,12 @@ class Planner(object): v_cruise_setpoint, accel_limits[1], accel_limits[0], jerk_limits[1], jerk_limits[0], - _DT_MPC) + LON_MPC_STEP) # cruise speed can't be negative even is user is distracted self.v_cruise = max(self.v_cruise, 0.) else: starting = long_control_state == LongCtrlState.starting - a_ego = min(CS.carState.aEgo, 0.0) + a_ego = min(sm['carState'].aEgo, 0.0) reset_speed = MIN_CAN_SPEED if starting else v_ego reset_accel = self.CP.startAccel if starting else a_ego self.v_acc = reset_speed @@ -192,8 +191,8 @@ class Planner(object): self.mpc1.set_cur_state(self.v_acc_start, self.a_acc_start) self.mpc2.set_cur_state(self.v_acc_start, self.a_acc_start) - self.mpc1.update(CS, lead_1, v_cruise_setpoint) - self.mpc2.update(CS, lead_2, v_cruise_setpoint) + self.mpc1.update(sm['carState'], lead_1, v_cruise_setpoint) + self.mpc2.update(sm['carState'], lead_2, v_cruise_setpoint) self.choose_solution(v_cruise_setpoint, enabled) @@ -201,26 +200,28 @@ class Planner(object): if self.mpc1.new_lead: self.fcw_checker.reset_lead(cur_time) - blinkers = CS.carState.leftBlinker or CS.carState.rightBlinker - fcw = self.fcw_checker.update(self.mpc1.mpc_solution, cur_time, v_ego, CS.carState.aEgo, + blinkers = sm['carState'].leftBlinker or sm['carState'].rightBlinker + fcw = self.fcw_checker.update(self.mpc1.mpc_solution, cur_time, v_ego, sm['carState'].aEgo, lead_1.dRel, lead_1.vLead, lead_1.aLeadK, lead_1.yRel, lead_1.vLat, - lead_1.fcw, blinkers) and not CS.carState.brakePressed + lead_1.fcw, blinkers) and not sm['carState'].brakePressed if fcw: cloudlog.info("FCW triggered %s", self.fcw_checker.counters) - radar_dead = cur_time - rcv_times['radarState'] > 0.5 + radar_dead = not sm.alive['radarState'] - radar_errors = list(radar_state.radarState.radarErrors) + radar_errors = list(sm['radarState'].radarErrors) radar_fault = car.RadarData.Error.fault in radar_errors - radar_comm_issue = car.RadarData.Error.commIssue in radar_errors + radar_can_error = car.RadarData.Error.canError in radar_errors # **** send the plan **** plan_send = messaging.new_message() plan_send.init('plan') - plan_send.plan.mdMonoTime = md.logMonoTime - plan_send.plan.radarStateMonoTime = radar_state.logMonoTime + plan_send.valid = sm.all_alive_and_valid(service_list=['carState', 'controlsState', 'radarState']) + + plan_send.plan.mdMonoTime = sm.logMonoTime['model'] + plan_send.plan.radarStateMonoTime = sm.logMonoTime['radarState'] # longitudal plan plan_send.plan.vCruise = self.v_cruise @@ -239,9 +240,9 @@ class Planner(object): radar_valid = not (radar_dead or radar_fault) plan_send.plan.radarValid = bool(radar_valid) - plan_send.plan.radarCommIssue = bool(radar_comm_issue) + plan_send.plan.radarCanError = bool(radar_can_error) - plan_send.plan.processingDelay = (plan_send.logMonoTime / 1e9) - rcv_times['radarState'] + plan_send.plan.processingDelay = (plan_send.logMonoTime / 1e9) - sm.rcv_time['radarState'] # Send out fcw fcw = fcw and (self.fcw_enabled or long_control_state != LongCtrlState.off) @@ -250,8 +251,7 @@ class Planner(object): self.plan.send(plan_send.to_bytes()) # Interpolate 0.05 seconds and save as starting point for next iteration - dt = 0.05 # s - a_acc_sol = self.a_acc_start + (dt / _DT_MPC) * (self.a_acc - self.a_acc_start) - v_acc_sol = self.v_acc_start + dt * (a_acc_sol + self.a_acc_start) / 2.0 + a_acc_sol = self.a_acc_start + (DT_PLAN / LON_MPC_STEP) * (self.a_acc - self.a_acc_start) + v_acc_sol = self.v_acc_start + DT_PLAN * (a_acc_sol + self.a_acc_start) / 2.0 self.v_acc_start = v_acc_sol self.a_acc_start = a_acc_sol diff --git a/selfdrive/controls/plannerd.py b/selfdrive/controls/plannerd.py index c152d01fd3..306dab05ba 100755 --- a/selfdrive/controls/plannerd.py +++ b/selfdrive/controls/plannerd.py @@ -1,13 +1,10 @@ #!/usr/bin/env python import gc -import zmq -from collections import defaultdict from cereal import car from common.params import Params -from common.realtime import sec_since_boot, set_realtime_priority +from common.realtime import set_realtime_priority from selfdrive.swaglog import cloudlog -from selfdrive.services import service_list from selfdrive.controls.lib.planner import Planner from selfdrive.controls.lib.vehicle_model import VehicleModel from selfdrive.controls.lib.pathplanner import PathPlanner @@ -20,7 +17,6 @@ def plannerd_thread(): # start the loop set_realtime_priority(2) - context = zmq.Context() params = Params() # Get FCW toggle from settings @@ -35,53 +31,24 @@ def plannerd_thread(): VM = VehicleModel(CP) - poller = zmq.Poller() - car_state_sock = messaging.sub_sock(context, service_list['carState'].port, conflate=True, poller=poller) - controls_state_sock = messaging.sub_sock(context, service_list['controlsState'].port, conflate=True, poller=poller) - radar_state_sock = messaging.sub_sock(context, service_list['radarState'].port, conflate=True, poller=poller) - model_sock = messaging.sub_sock(context, service_list['model'].port, conflate=True, poller=poller) - live_parameters_sock = messaging.sub_sock(context, service_list['liveParameters'].port, conflate=True, poller=poller) - # live_map_data_sock = messaging.sub_sock(context, service_list['liveMapData'].port, conflate=True, poller=poller) - - car_state = messaging.new_message() - car_state.init('carState') - controls_state = messaging.new_message() - controls_state.init('controlsState') - model = messaging.new_message() - model.init('model') - radar_state = messaging.new_message() - radar_state.init('radarState') + sm = messaging.SubMaster(['carState', 'controlsState', 'radarState', 'model', 'liveParameters']) + + sm['liveParameters'].valid = True + sm['liveParameters'].sensorValid = True + sm['liveParameters'].steerRatio = CP.steerRatio + sm['liveParameters'].stiffnessFactor = 1.0 live_map_data = messaging.new_message() live_map_data.init('liveMapData') - live_parameters = messaging.new_message() - live_parameters.init('liveParameters') - live_parameters.liveParameters.valid = True - live_parameters.liveParameters.sensorValid = True - live_parameters.liveParameters.steerRatio = CP.steerRatio - live_parameters.liveParameters.stiffnessFactor = 1.0 - - rcv_times = defaultdict(int) - while True: - for socket, event in poller.poll(): - msg = messaging.recv_one(socket) - rcv_times[msg.which()] = sec_since_boot() - - if socket is controls_state_sock: - controls_state = msg - elif socket is car_state_sock: - car_state = msg - elif socket is live_parameters_sock: - live_parameters = msg - elif socket is model_sock: - model = msg - PP.update(rcv_times, CP, VM, car_state, model, controls_state, live_parameters) - elif socket is radar_state_sock: - radar_state = msg - PL.update(rcv_times, car_state, CP, VM, PP, radar_state, controls_state, model, live_map_data) - # elif socket is live_map_data_sock: - # live_map_data = msg + sm.update() + + if sm.updated['model']: + PP.update(sm, CP, VM) + if sm.updated['radarState']: + PL.update(sm, CP, VM, PP, live_map_data.liveMapData) + # elif socket is live_map_data_sock: + # live_map_data = msg def main(gctx=None): diff --git a/selfdrive/controls/radard.py b/selfdrive/controls/radard.py index c4c135c1c4..b37ed8f755 100755 --- a/selfdrive/controls/radard.py +++ b/selfdrive/controls/radard.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -import zmq import numpy as np import numpy.matlib import importlib @@ -17,7 +16,7 @@ from selfdrive.controls.lib.vehicle_model import VehicleModel from selfdrive.swaglog import cloudlog from cereal import car from common.params import Params -from common.realtime import set_realtime_priority, Ratekeeper +from common.realtime import set_realtime_priority, Ratekeeper, DT_MDL from common.kalman.ekf import EKF, SimpleSensor DEBUG = False @@ -59,13 +58,8 @@ def radard_thread(gctx=None): # import the radar from the fingerprint cloudlog.info("radard is importing %s", CP.carName) RadarInterface = importlib.import_module('selfdrive.car.%s.radar_interface' % CP.carName).RadarInterface - context = zmq.Context() - # *** subscribe to features and model from visiond - poller = zmq.Poller() - model = messaging.sub_sock(context, service_list['model'].port, conflate=True, poller=poller) - controls_state_sock = messaging.sub_sock(context, service_list['controlsState'].port, conflate=True, poller=poller) - live_parameters_sock = messaging.sub_sock(context, service_list['liveParameters'].port, conflate=True, poller=poller) + sm = messaging.SubMaster(['model', 'controlsState', 'liveParameters']) # Default parameters live_parameters = messaging.new_message() @@ -81,15 +75,14 @@ def radard_thread(gctx=None): last_controls_state_ts = 0 # *** publish radarState and liveTracks - radarState = messaging.pub_sock(context, service_list['radarState'].port) - liveTracks = messaging.pub_sock(context, service_list['liveTracks'].port) + radarState = messaging.pub_sock(service_list['radarState'].port) + liveTracks = messaging.pub_sock(service_list['liveTracks'].port) path_x = np.arange(0.0, 140.0, 0.1) # 140 meters is max # Time-alignment - rate = 20. # model and radar are both at 20Hz - tsv = 1./rate - v_len = 20 # how many speed data points to remember for t alignment with rdr data + rate = 1. / DT_MDL # model and radar are both at 20Hz + v_len = 20 # how many speed data points to remember for t alignment with rdr data active = 0 steer_angle = 0. @@ -102,9 +95,9 @@ def radard_thread(gctx=None): speedSensorV = SimpleSensor(XV, 1, 2) # v_ego - v_ego = None - v_ego_hist_t = deque(maxlen=v_len) - v_ego_hist_v = deque(maxlen=v_len) + v_ego = 0. + v_ego_hist_t = deque([0], maxlen=v_len) + v_ego_hist_v = deque([0], maxlen=v_len) v_ego_t_aligned = 0. rk = Ratekeeper(rate, print_delay_threshold=None) @@ -115,44 +108,32 @@ def radard_thread(gctx=None): for pt in rr.points: ar_pts[pt.trackId] = [pt.dRel + RDR_TO_LDR, pt.yRel, pt.vRel, pt.measured] - # receive the controlsStates - controls_state = None - md = None - - for socket, event in poller.poll(0): - if socket is controls_state_sock: - controls_state = messaging.recv_one(socket) - elif socket is model: - md = messaging.recv_one(socket) - elif socket is live_parameters_sock: - live_parameters = messaging.recv_one(socket) - VM.update_params(live_parameters.liveParameters.stiffnessFactor, live_parameters.liveParameters.steerRatio) - - if controls_state is not None: - active = controls_state.controlsState.active - v_ego = controls_state.controlsState.vEgo - steer_angle = controls_state.controlsState.angleSteers - steer_override = controls_state.controlsState.steerOverride + sm.update(0) + + if sm.updated['liveParameters']: + VM.update_params(sm['liveParameters'].stiffnessFactor, sm['liveParameters'].steerRatio) + + if sm.updated['controlsState']: + active = sm['controlsState'].active + v_ego = sm['controlsState'].vEgo + steer_angle = sm['controlsState'].angleSteers + steer_override = sm['controlsState'].steerOverride v_ego_hist_v.append(v_ego) v_ego_hist_t.append(float(rk.frame)/rate) - last_controls_state_ts = controls_state.logMonoTime - - if v_ego is None: - continue + last_controls_state_ts = sm.logMonoTime['controlsState'] - if md is not None: - last_md_ts = md.logMonoTime + if sm.updated['model']: + last_md_ts = sm.logMonoTime['model'] + MP.update(v_ego, sm['model']) - # *** get path prediction from the model *** - MP.update(v_ego, md) # run kalman filter only if prob is high enough if MP.lead_prob > 0.7: reading = speedSensorV.read(MP.lead_dist, covar=np.matrix(MP.lead_var)) ekfv.update_scalar(reading) - ekfv.predict(tsv) + ekfv.predict(DT_MDL) # When changing lanes the distance to the lead car can suddenly change, # which makes the Kalman filter output large relative acceleration @@ -264,6 +245,7 @@ def radard_thread(gctx=None): # *** publish radarState *** dat = messaging.new_message() dat.init('radarState') + dat.valid = sm.all_alive_and_valid(service_list=['controlsState']) dat.radarState.mdMonoTime = last_md_ts dat.radarState.canMonoTimes = list(rr.canMonoTimes) dat.radarState.radarErrors = list(rr.errors) diff --git a/selfdrive/controls/tests/test_following_distance.py b/selfdrive/controls/tests/test_following_distance.py index 228636e671..994ea7ea5d 100644 --- a/selfdrive/controls/tests/test_following_distance.py +++ b/selfdrive/controls/tests/test_following_distance.py @@ -61,8 +61,8 @@ def run_following_distance_simulation(v_lead, t_end=200.0): mpc.set_cur_state(v_ego, a_ego) if first: # Make sure MPC is converged on first timestep for _ in range(20): - mpc.update(CS, lead, v_cruise_setpoint) - mpc.update(CS, lead, v_cruise_setpoint) + mpc.update(CS.carState, lead, v_cruise_setpoint) + mpc.update(CS.carState, lead, v_cruise_setpoint) # Choose slowest of two solutions if v_cruise < mpc.v_mpc: diff --git a/selfdrive/controls/tests/test_lateral_mpc.py b/selfdrive/controls/tests/test_lateral_mpc.py new file mode 100644 index 0000000000..77b37bb740 --- /dev/null +++ b/selfdrive/controls/tests/test_lateral_mpc.py @@ -0,0 +1,121 @@ +import unittest +import copy +import numpy as np +from selfdrive.car.honda.interface import CarInterface +from selfdrive.controls.lib.lateral_mpc import libmpc_py +from selfdrive.controls.lib.vehicle_model import VehicleModel + + +def run_mpc(v_ref=30., x_init=0., y_init=0., psi_init=0., delta_init=0., + l_prob=1., r_prob=1., p_prob=1., + poly_l=np.array([0., 0., 0., 1.8]), poly_r=np.array([0., 0., 0., -1.8]), poly_p=np.array([0., 0., 0., 0.]), + lane_width=3.6, poly_shift=0.): + + libmpc = libmpc_py.libmpc + libmpc.init(1.0, 3.0, 1.0, 1.0) + + mpc_solution = libmpc_py.ffi.new("log_t *") + + p_l = copy.copy(poly_l) + p_l[3] += poly_shift + p_r = copy.copy(poly_r) + p_r[3] += poly_shift + p_p = copy.copy(poly_p) + p_p[3] += poly_shift + + CP = CarInterface.get_params("HONDA CIVIC 2016 TOURING", {}) + VM = VehicleModel(CP) + + v_ref = v_ref + curvature_factor = VM.curvature_factor(v_ref) + + l_poly = libmpc_py.ffi.new("double[4]", map(float, p_l)) + r_poly = libmpc_py.ffi.new("double[4]", map(float, p_r)) + p_poly = libmpc_py.ffi.new("double[4]", map(float, p_p)) + + cur_state = libmpc_py.ffi.new("state_t *") + cur_state[0].x = x_init + cur_state[0].y = y_init + cur_state[0].psi = psi_init + cur_state[0].delta = delta_init + + # converge in no more than 20 iterations + for _ in range(20): + libmpc.run_mpc(cur_state, mpc_solution, l_poly, r_poly, p_poly, l_prob, r_prob, p_prob, + curvature_factor, v_ref, lane_width) + + return mpc_solution + + +class TestLateralMpc(unittest.TestCase): + + def _assert_null(self, sol, delta=1e-6): + for i in range(len(sol[0].y)): + self.assertAlmostEqual(sol[0].y[i], 0., delta=delta) + self.assertAlmostEqual(sol[0].psi[i], 0., delta=delta) + self.assertAlmostEqual(sol[0].delta[i], 0., delta=delta) + + def _assert_simmetry(self, sol, delta=1e-6): + for i in range(len(sol[0][0].y)): + self.assertAlmostEqual(sol[0][0].y[i], -sol[1][0].y[i], delta=delta) + self.assertAlmostEqual(sol[0][0].psi[i], -sol[1][0].psi[i], delta=delta) + self.assertAlmostEqual(sol[0][0].delta[i], -sol[1][0].delta[i], delta=delta) + self.assertAlmostEqual(sol[0][0].x[i], sol[1][0].x[i], delta=delta) + + def _assert_identity(self, sol, ignore_y=False, delta=1e-6): + for i in range(len(sol[0][0].y)): + self.assertAlmostEqual(sol[0][0].psi[i], sol[1][0].psi[i], delta=delta) + self.assertAlmostEqual(sol[0][0].delta[i], sol[1][0].delta[i], delta=delta) + self.assertAlmostEqual(sol[0][0].x[i], sol[1][0].x[i], delta=delta) + if not ignore_y: + self.assertAlmostEqual(sol[0][0].y[i], sol[1][0].y[i], delta=delta) + + def test_straight(self): + sol = run_mpc() + self._assert_null(sol) + + def test_y_symmetry(self): + sol = [] + for y_init in [-0.5, 0.5]: + sol.append(run_mpc(y_init=y_init)) + self._assert_simmetry(sol) + + def test_poly_symmetry(self): + sol = [] + for poly_shift in [-1., 1.]: + sol.append(run_mpc(poly_shift=poly_shift)) + self._assert_simmetry(sol) + + def test_delta_symmetry(self): + sol = [] + for delta_init in [-0.1, 0.1]: + sol.append(run_mpc(delta_init=delta_init)) + self._assert_simmetry(sol) + + def test_psi_symmetry(self): + sol = [] + for psi_init in [-0.1, 0.1]: + sol.append(run_mpc(psi_init=psi_init)) + self._assert_simmetry(sol) + + def test_prob_symmetry(self): + sol = [] + lane_width = 3. + for r_prob in [0., 1.]: + sol.append(run_mpc(r_prob=r_prob, l_prob=1.-r_prob, lane_width=lane_width)) + self._assert_simmetry(sol) + + def test_y_shift_vs_poly_shift(self): + shift = 1. + sol = [] + sol.append(run_mpc(y_init=shift)) + sol.append(run_mpc(poly_shift=-shift)) + # need larger delta than standard, otherwise it false triggers. + # this is acceptable because the 2 cases are very different from the optimizer standpoint + self._assert_identity(sol, ignore_y=True, delta=1e-5) + + def test_no_overshoot(self): + y_init = 1. + sol = run_mpc(y_init=y_init) + for y in list(sol[0].y): + self.assertGreaterEqual(y_init, abs(y)) diff --git a/selfdrive/crash.py b/selfdrive/crash.py index 94bdfd125b..6ceb56b627 100644 --- a/selfdrive/crash.py +++ b/selfdrive/crash.py @@ -2,6 +2,7 @@ import os import sys import threading +import capnp from selfdrive.version import version, dirty from selfdrive.swaglog import cloudlog @@ -22,7 +23,9 @@ else: install_sys_hook=False, transport=HTTPTransport, release=version, tags={'dirty': dirty}) def capture_exception(*args, **kwargs): - client.captureException(*args, **kwargs) + exc_info = sys.exc_info() + if not exc_info[0] is capnp.lib.capnp.KjException: + client.captureException(*args, **kwargs) cloudlog.error("crash", exc_info=kwargs.get('exc_info', 1)) def bind_user(**kwargs): diff --git a/selfdrive/debug/can_printer.py b/selfdrive/debug/can_printer.py index 876b2ab808..daa0500b2f 100755 --- a/selfdrive/debug/can_printer.py +++ b/selfdrive/debug/can_printer.py @@ -3,14 +3,12 @@ import os import sys from collections import defaultdict from common.realtime import sec_since_boot -import zmq import selfdrive.messaging as messaging from selfdrive.services import service_list def can_printer(bus=0, max_msg=None, addr="127.0.0.1"): - context = zmq.Context() - logcan = messaging.sub_sock(context, service_list['can'].port, addr=addr) + logcan = messaging.sub_sock(service_list['can'].port, addr=addr) start = sec_since_boot() lp = sec_since_boot() diff --git a/selfdrive/debug/cpu_usage_stat.py b/selfdrive/debug/cpu_usage_stat.py index 55723ff354..7adf7ef78e 100755 --- a/selfdrive/debug/cpu_usage_stat.py +++ b/selfdrive/debug/cpu_usage_stat.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2 import psutil import time import os @@ -30,7 +30,7 @@ SLEEP_INTERVAL = 0.2 monitored_proc_names = [ 'ubloxd', 'thermald', 'uploader', 'deleter', 'controlsd', 'plannerd', 'radard', 'mapd', 'loggerd' , 'logmessaged', 'tombstoned', - 'logcatd', 'proclogd', 'boardd', 'pandad', './ui', 'calibrationd', 'locationd', 'visiond', 'sensord', 'updated', 'gpsd', 'athena'] + 'logcatd', 'proclogd', 'boardd', 'pandad', './ui', 'calibrationd', 'params_learner', 'visiond', 'sensord', 'updated', 'gpsd', 'athena'] cpu_time_names = ['user', 'system', 'children_user', 'children_system'] timer = getattr(time, 'monotonic', time.time) diff --git a/selfdrive/debug/dump.py b/selfdrive/debug/dump.py index 0434023f71..7fd8a7cf4f 100755 --- a/selfdrive/debug/dump.py +++ b/selfdrive/debug/dump.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2 import sys import argparse import zmq @@ -14,7 +14,6 @@ def run_server(socketio): socketio.run(app, host='0.0.0.0', port=4000) if __name__ == "__main__": - context = zmq.Context() poller = zmq.Poller() parser = argparse.ArgumentParser(description='Sniff a communcation socket') @@ -40,9 +39,9 @@ if __name__ == "__main__": else: print("service not found") sys.exit(-1) - sock = messaging.sub_sock(context, port, poller, addr=args.addr) + sock = messaging.sub_sock(port, poller, addr=args.addr) if args.proxy: - republish_socks[sock] = messaging.pub_sock(context, port) + republish_socks[sock] = messaging.pub_sock(port) if args.map: from flask.ext.socketio import SocketIO #pylint: disable=no-name-in-module, import-error diff --git a/selfdrive/debug/get_fingerprint.py b/selfdrive/debug/get_fingerprint.py index ed877ff508..e528d9826c 100755 --- a/selfdrive/debug/get_fingerprint.py +++ b/selfdrive/debug/get_fingerprint.py @@ -11,12 +11,10 @@ # - since some messages are published at low frequency, keep this script running for at least 30s, # until all messages are received at least once -import zmq import selfdrive.messaging as messaging from selfdrive.services import service_list -context = zmq.Context() -logcan = messaging.sub_sock(context, service_list['can'].port) +logcan = messaging.sub_sock(service_list['can'].port) msgs = {} while True: lc = messaging.recv_sock(logcan, True) diff --git a/selfdrive/locationd/.gitignore b/selfdrive/locationd/.gitignore index 6c8271a885..8cdb0d2305 100644 --- a/selfdrive/locationd/.gitignore +++ b/selfdrive/locationd/.gitignore @@ -1,2 +1,3 @@ ubloxd ubloxd_test +params_learner \ No newline at end of file diff --git a/selfdrive/locationd/Makefile b/selfdrive/locationd/Makefile index 110c1457ee..f7652648e1 100644 --- a/selfdrive/locationd/Makefile +++ b/selfdrive/locationd/Makefile @@ -13,28 +13,47 @@ WARN_FLAGS = -Werror=implicit-function-declaration \ -Werror=return-type \ -Werror=format-extra-args -CFLAGS = -std=gnu11 -g -fPIC -I../ -I../../ -O2 $(WARN_FLAGS) -CXXFLAGS = -std=c++11 -g -fPIC -I../ -I../../ -O2 $(WARN_FLAGS) +CFLAGS = -std=gnu11 -g -fPIC -I../ -I../../ -O2 $(WARN_FLAGS) -Wall +CXXFLAGS = -std=c++11 -g -fPIC -I../ -I../../ -O2 $(WARN_FLAGS) -Wall +ZMQ_LIBS = -l:libczmq.a -l:libzmq.a + +ifeq ($(ARCH),aarch64) +CFLAGS += -mcpu=cortex-a57 +CXXFLAGS += -mcpu=cortex-a57 +ZMQ_LIBS += -lgnustl_shared +endif -ZMQ_FLAGS = -I$(PHONELIBS)/zmq/aarch64/include -ZMQ_LIBS = -L$(PHONELIBS)/zmq/aarch64/lib \ - -l:libczmq.a -l:libzmq.a \ - -lgnustl_shared JSON_FLAGS = -I$(PHONELIBS)/json/src +JSON11_FLAGS = -I$(PHONELIBS)/json11 EXTRA_LIBS = -lpthread ifeq ($(ARCH),x86_64) +ZMQ_FLAGS = -I$(BASEDIR)/phonelibs/zmq/x64/include ZMQ_LIBS = -L$(BASEDIR)/external/zmq/lib \ -l:libczmq.a -l:libzmq.a +ZMQ_SHARED_LIBS = -L$(BASEDIR)/external/zmq/lib \ + -lczmq -lzmq +else +EXTRA_LIBS += -llog -luuid endif .PHONY: all -all: ubloxd +all: ubloxd params_learner include ../common/cereal.mk +LOC_OBJS = locationd_yawrate.o params_learner.o \ + ../common/swaglog.o \ + ../common/params.o \ + ../common/util.o \ + $(PHONELIBS)/json11/json11.o \ + $(PHONELIBS)/json/src/json.o \ + $(CEREAL_OBJS) + +LOC_DEPS := $(LOC_OBJS:.o=.d) + OBJS = ublox_msg.o \ ubloxd_main.o \ ../common/swaglog.o \ @@ -45,6 +64,20 @@ OBJS = ublox_msg.o \ DEPS := $(OBJS:.o=.d) ubloxd.d ubloxd_test.d +liblocationd.so: $(LOC_OBJS) + @echo "[ LINK ] $@" + $(CXX) -shared -o '$@' $^ \ + $(CEREAL_LIBS) \ + $(ZMQ_SHARED_LIBS) \ + $(EXTRA_LIBS) + +params_learner: $(LOC_OBJS) + @echo "[ LINK ] $@" + $(CXX) -fPIC -o '$@' $^ \ + $(CEREAL_LIBS) \ + $(ZMQ_LIBS) \ + $(EXTRA_LIBS) + ubloxd: ubloxd.o $(OBJS) @echo "[ LINK ] $@" $(CXX) -fPIC -o '$@' $^ \ @@ -65,6 +98,7 @@ ubloxd_test: ubloxd_test.o $(OBJS) -Iinclude -I.. -I../.. \ $(CEREAL_CXXFLAGS) \ $(ZMQ_FLAGS) \ + $(JSON11_FLAGS) \ $(JSON_FLAGS) \ -I../ \ -I../../ \ @@ -81,6 +115,7 @@ ubloxd_test: ubloxd_test.o $(OBJS) .PHONY: clean clean: - rm -f ubloxd ubloxd.d ubloxd.o ubloxd_test ubloxd_test.o ubloxd_test.d $(OBJS) $(DEPS) + rm -f ubloxd params_learner liblocationd.so ubloxd.d ubloxd.o ubloxd_test ubloxd_test.o ubloxd_test.d $(OBJS) $(LOC_OBJS) $(DEPS) -include $(DEPS) +-include $(LOC_DEPS) diff --git a/selfdrive/locationd/calibrationd.py b/selfdrive/locationd/calibrationd.py index 61c6e4553e..e3a0b10ad0 100755 --- a/selfdrive/locationd/calibrationd.py +++ b/selfdrive/locationd/calibrationd.py @@ -1,6 +1,5 @@ #!/usr/bin/env python import os -import zmq import copy import json import numpy as np @@ -9,7 +8,7 @@ from selfdrive.locationd.calibration_helpers import Calibration from selfdrive.swaglog import cloudlog from selfdrive.services import service_list from common.params import Params -from common.transformations.model import model_height, get_camera_frame_from_model_frame, get_camera_frame_from_bigmodel_frame +from common.transformations.model import model_height, get_camera_frame_from_model_frame, get_camera_frame_from_medmodel_frame from common.transformations.camera import view_frame_from_device_frame, get_view_frame_from_road_frame, \ eon_intrinsics, get_calib_from_vp, H, W @@ -85,7 +84,7 @@ class Calibrator(object): extrinsic_matrix = get_view_frame_from_road_frame(0, calib[1], calib[2], model_height) ke = eon_intrinsics.dot(extrinsic_matrix) warp_matrix = get_camera_frame_from_model_frame(ke) - warp_matrix_big = get_camera_frame_from_bigmodel_frame(ke) + warp_matrix_big = get_camera_frame_from_medmodel_frame(ke) cal_send = messaging.new_message() cal_send.init('liveCalibration') @@ -99,10 +98,8 @@ class Calibrator(object): def calibrationd_thread(gctx=None, addr="127.0.0.1"): - context = zmq.Context() - - cameraodometry = messaging.sub_sock(context, service_list['cameraOdometry'].port, addr=addr, conflate=True) - livecalibration = messaging.pub_sock(context, service_list['liveCalibration'].port) + cameraodometry = messaging.sub_sock(service_list['cameraOdometry'].port, addr=addr, conflate=True) + livecalibration = messaging.pub_sock(service_list['liveCalibration'].port) calibrator = Calibrator(param_put=True) # buffer with all the messages that still need to be input into the kalman diff --git a/selfdrive/locationd/kalman/.gitignore b/selfdrive/locationd/kalman/.gitignore deleted file mode 100644 index 9d357c72cc..0000000000 --- a/selfdrive/locationd/kalman/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -lane.cpp -gnss.cpp -loc*.cpp -pos_computer*.cpp diff --git a/selfdrive/locationd/kalman/__init__.py b/selfdrive/locationd/kalman/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/selfdrive/locationd/kalman/chi2_lookup.py b/selfdrive/locationd/kalman/chi2_lookup.py deleted file mode 100644 index f45b4577f5..0000000000 --- a/selfdrive/locationd/kalman/chi2_lookup.py +++ /dev/null @@ -1,21 +0,0 @@ -import numpy as np -import os - - -def gen_chi2_ppf_lookup(max_dim=200): - from scipy.stats import chi2 - table = np.zeros((max_dim, 98)) - for dim in range(1,max_dim): - table[dim] = chi2.ppf(np.arange(.01, .99, .01), dim) - #outfile = open('chi2_lookup_table', 'w') - np.save('chi2_lookup_table', table) - - -def chi2_ppf(p, dim): - table = np.load(os.path.dirname(os.path.realpath(__file__)) + '/chi2_lookup_table.npy') - result = np.interp(p, np.arange(.01, .99, .01), table[dim]) - return result - - -if __name__== "__main__": - gen_chi2_ppf_lookup() diff --git a/selfdrive/locationd/kalman/chi2_lookup_table.npy b/selfdrive/locationd/kalman/chi2_lookup_table.npy deleted file mode 100644 index 6f1bd959c1..0000000000 Binary files a/selfdrive/locationd/kalman/chi2_lookup_table.npy and /dev/null differ diff --git a/selfdrive/locationd/kalman/ekf_c.c b/selfdrive/locationd/kalman/ekf_c.c deleted file mode 100644 index 1331036de3..0000000000 --- a/selfdrive/locationd/kalman/ekf_c.c +++ /dev/null @@ -1,124 +0,0 @@ -#include -#include - -typedef Eigen::Matrix DDM; -typedef Eigen::Matrix EEM; -typedef Eigen::Matrix DEM; - -void predict(double *in_x, double *in_P, double *in_Q, double dt) { - typedef Eigen::Matrix RRM; - - double nx[DIM] = {0}; - double in_F[EDIM*EDIM] = {0}; - - // functions from sympy - f_fun(in_x, dt, nx); - F_fun(in_x, dt, in_F); - - - EEM F(in_F); - EEM P(in_P); - EEM Q(in_Q); - - RRM F_main = F.topLeftCorner(MEDIM, MEDIM); - P.topLeftCorner(MEDIM, MEDIM) = (F_main * P.topLeftCorner(MEDIM, MEDIM)) * F_main.transpose(); - P.topRightCorner(MEDIM, EDIM - MEDIM) = F_main * P.topRightCorner(MEDIM, EDIM - MEDIM); - P.bottomLeftCorner(EDIM - MEDIM, MEDIM) = P.bottomLeftCorner(EDIM - MEDIM, MEDIM) * F_main.transpose(); - - P = P + dt*Q; - - // copy out state - memcpy(in_x, nx, DIM * sizeof(double)); - memcpy(in_P, P.data(), EDIM * EDIM * sizeof(double)); -} - -// note: extra_args dim only correct when null space projecting -// otherwise 1 -template -void update(double *in_x, double *in_P, Hfun h_fun, Hfun H_fun, Hfun Hea_fun, double *in_z, double *in_R, double *in_ea, double MAHA_THRESHOLD) { - typedef Eigen::Matrix ZZM; - typedef Eigen::Matrix ZDM; - typedef Eigen::Matrix ZEM; - typedef Eigen::Matrix XEM; - typedef Eigen::Matrix EZM; - typedef Eigen::Matrix X1M; - typedef Eigen::Matrix XXM; - - double in_hx[ZDIM] = {0}; - double in_H[ZDIM * DIM] = {0}; - double in_H_mod[EDIM * DIM] = {0}; - double delta_x[EDIM] = {0}; - double x_new[DIM] = {0}; - - - // state x, P - Eigen::Matrix z(in_z); - EEM P(in_P); - ZZM pre_R(in_R); - - // functions from sympy - h_fun(in_x, in_ea, in_hx); - H_fun(in_x, in_ea, in_H); - ZDM pre_H(in_H); - - // get y (y = z - hx) - Eigen::Matrix pre_y(in_hx); pre_y = z - pre_y; - X1M y; XXM H; XXM R; - if (Hea_fun){ - typedef Eigen::Matrix ZAM; - double in_Hea[ZDIM * EADIM] = {0}; - Hea_fun(in_x, in_ea, in_Hea); - ZAM Hea(in_Hea); - XXM A = Hea.transpose().fullPivLu().kernel(); - - - y = A.transpose() * pre_y; - H = A.transpose() * pre_H; - R = A.transpose() * pre_R * A; - } else { - y = pre_y; - H = pre_H; - R = pre_R; - } - // get modified H - H_mod_fun(in_x, in_H_mod); - DEM H_mod(in_H_mod); - XEM H_err = H * H_mod; - - // Do mahalobis distance test - if (MAHA_TEST){ - XXM a = (H_err * P * H_err.transpose() + R).inverse(); - double maha_dist = y.transpose() * a * y; - if (maha_dist > MAHA_THRESHOLD){ - R = 1.0e16 * R; - } - } - - // Outlier resilient weighting - double weight = 1;//(1.5)/(1 + y.squaredNorm()/R.sum()); - - // kalman gains and I_KH - XXM S = ((H_err * P) * H_err.transpose()) + R/weight; - XEM KT = S.fullPivLu().solve(H_err * P.transpose()); - //EZM K = KT.transpose(); TODO: WHY DOES THIS NOT COMPILE? - //EZM K = S.fullPivLu().solve(H_err * P.transpose()).transpose(); - //std::cout << "Here is the matrix rot:\n" << K << std::endl; - EEM I_KH = Eigen::Matrix::Identity() - (KT.transpose() * H_err); - - // update state by injecting dx - Eigen::Matrix dx(delta_x); - dx = (KT.transpose() * y); - memcpy(delta_x, dx.data(), EDIM * sizeof(double)); - err_fun(in_x, delta_x, x_new); - Eigen::Matrix x(x_new); - - // update cov - P = ((I_KH * P) * I_KH.transpose()) + ((KT.transpose() * R) * KT); - - // copy out state - memcpy(in_x, x.data(), DIM * sizeof(double)); - memcpy(in_P, P.data(), EDIM * EDIM * sizeof(double)); - memcpy(in_z, y.data(), y.rows() * sizeof(double)); -} - - diff --git a/selfdrive/locationd/kalman/ekf_sym.py b/selfdrive/locationd/kalman/ekf_sym.py deleted file mode 100644 index a1f282ab05..0000000000 --- a/selfdrive/locationd/kalman/ekf_sym.py +++ /dev/null @@ -1,562 +0,0 @@ -import os -from bisect import bisect_right -import sympy as sp -import numpy as np -from numpy import dot -from common.ffi_wrapper import compile_code, wrap_compiled -from common.sympy_helpers import sympy_into_c -from chi2_lookup import chi2_ppf - - -EXTERNAL_PATH = os.path.dirname(os.path.abspath(__file__)) - -def solve(a, b): - if a.shape[0] == 1 and a.shape[1] == 1: - #assert np.allclose(b/a[0][0], np.linalg.solve(a, b)) - return b/a[0][0] - else: - return np.linalg.solve(a, b) - -def null(H, eps=1e-12): - u, s, vh = np.linalg.svd(H) - padding = max(0,np.shape(H)[1]-np.shape(s)[0]) - null_mask = np.concatenate(((s <= eps), np.ones((padding,),dtype=bool)),axis=0) - null_space = np.compress(null_mask, vh, axis=0) - return np.transpose(null_space) - -def gen_code(name, f_sym, dt_sym, x_sym, obs_eqs, dim_x, dim_err, eskf_params=None, msckf_params=None, maha_test_kinds=[]): - # optional state transition matrix, H modifier - # and err_function if an error-state kalman filter (ESKF) - # is desired. Best described in "Quaternion kinematics - # for the error-state Kalman filter" by Joan Sola - - if eskf_params: - err_eqs = eskf_params[0] - inv_err_eqs = eskf_params[1] - H_mod_sym = eskf_params[2] - f_err_sym = eskf_params[3] - x_err_sym = eskf_params[4] - else: - nom_x = sp.MatrixSymbol('nom_x',dim_x,1) - true_x = sp.MatrixSymbol('true_x',dim_x,1) - delta_x = sp.MatrixSymbol('delta_x',dim_x,1) - err_function_sym = sp.Matrix(nom_x + delta_x) - inv_err_function_sym = sp.Matrix(true_x - nom_x) - err_eqs = [err_function_sym, nom_x, delta_x] - inv_err_eqs = [inv_err_function_sym, nom_x, true_x] - - H_mod_sym = sp.Matrix(np.eye(dim_x)) - f_err_sym = f_sym - x_err_sym = x_sym - - # This configures the multi-state augmentation - # needed for EKF-SLAM with MSCKF (Mourikis et al 2007) - if msckf_params: - msckf = True - dim_main = msckf_params[0] # size of the main state - dim_augment = msckf_params[1] # size of one augment state chunk - dim_main_err = msckf_params[2] - dim_augment_err = msckf_params[3] - N = msckf_params[4] - feature_track_kinds = msckf_params[5] - assert dim_main + dim_augment*N == dim_x - assert dim_main_err + dim_augment_err*N == dim_err - else: - msckf = False - dim_main = dim_x - dim_augment = 0 - dim_main_err = dim_err - dim_augment_err = 0 - N = 0 - - # linearize with jacobians - F_sym = f_err_sym.jacobian(x_err_sym) - for sym in x_err_sym: - F_sym = F_sym.subs(sym, 0) - for i in xrange(len(obs_eqs)): - obs_eqs[i].append(obs_eqs[i][0].jacobian(x_sym)) - if msckf and obs_eqs[i][1] in feature_track_kinds: - obs_eqs[i].append(obs_eqs[i][0].jacobian(obs_eqs[i][2])) - else: - obs_eqs[i].append(None) - - # collect sympy functions - sympy_functions = [] - - # error functions - sympy_functions.append(('err_fun', err_eqs[0], [err_eqs[1], err_eqs[2]])) - sympy_functions.append(('inv_err_fun', inv_err_eqs[0], [inv_err_eqs[1], inv_err_eqs[2]])) - - # H modifier for ESKF updates - sympy_functions.append(('H_mod_fun', H_mod_sym, [x_sym])) - - # state propagation function - sympy_functions.append(('f_fun', f_sym, [x_sym, dt_sym])) - sympy_functions.append(('F_fun', F_sym, [x_sym, dt_sym])) - - # observation functions - for h_sym, kind, ea_sym, H_sym, He_sym in obs_eqs: - sympy_functions.append(('h_%d' % kind, h_sym, [x_sym, ea_sym])) - sympy_functions.append(('H_%d' % kind, H_sym, [x_sym, ea_sym])) - if msckf and kind in feature_track_kinds: - sympy_functions.append(('He_%d' % kind, He_sym, [x_sym, ea_sym])) - - # Generate and wrap all th c code - header, code = sympy_into_c(sympy_functions) - extra_header = "#define DIM %d\n" % dim_x - extra_header += "#define EDIM %d\n" % dim_err - extra_header += "#define MEDIM %d\n" % dim_main_err - extra_header += "typedef void (*Hfun)(double *, double *, double *);\n" - - extra_header += "\nvoid predict(double *x, double *P, double *Q, double dt);" - - extra_post = "" - - for h_sym, kind, ea_sym, H_sym, He_sym in obs_eqs: - if msckf and kind in feature_track_kinds: - He_str = 'He_%d' % kind - # ea_dim = ea_sym.shape[0] - else: - He_str = 'NULL' - # ea_dim = 1 # not really dim of ea but makes c function work - maha_thresh = chi2_ppf(0.95, int(h_sym.shape[0])) # mahalanobis distance for outlier detection - maha_test = kind in maha_test_kinds - extra_post += """ - void update_%d(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea) { - update<%d,%d,%d>(in_x, in_P, h_%d, H_%d, %s, in_z, in_R, in_ea, MAHA_THRESH_%d); - } - """ % (kind, h_sym.shape[0], 3, maha_test, kind, kind, He_str, kind) - extra_header += "\nconst static double MAHA_THRESH_%d = %f;" % (kind, maha_thresh) - extra_header += "\nvoid update_%d(double *, double *, double *, double *, double *);" % kind - - code += "\n" + extra_header - code += "\n" + open(os.path.join(EXTERNAL_PATH, "ekf_c.c")).read() - code += "\n" + extra_post - header += "\n" + extra_header - compile_code(name, code, header, EXTERNAL_PATH) - -class EKF_sym(object): - def __init__(self, name, Q, x_initial, P_initial, dim_main, dim_main_err, - N=0, dim_augment=0, dim_augment_err=0, maha_test_kinds=[]): - ''' - Generates process function and all - observation functions for the kalman - filter. - ''' - if N > 0: - self.msckf = True - else: - self.msckf = False - self.N = N - self.dim_augment = dim_augment - self.dim_augment_err = dim_augment_err - self.dim_main = dim_main - self.dim_main_err = dim_main_err - - # state - x_initial = x_initial.reshape((-1, 1)) - self.dim_x = x_initial.shape[0] - self.dim_err = P_initial.shape[0] - assert dim_main + dim_augment*N == self.dim_x - assert dim_main_err + dim_augment_err*N == self.dim_err - - # kinds that should get mahalanobis distance - # tested for outlier rejection - self.maha_test_kinds = maha_test_kinds - - # process noise - self.Q = Q - - # rewind stuff - self.rewind_t = [] - self.rewind_states = [] - self.rewind_obscache = [] - self.init_state(x_initial, P_initial, None) - - ffi, lib = wrap_compiled(name, EXTERNAL_PATH) - kinds, self.feature_track_kinds = [], [] - for func in dir(lib): - if func[:2] == 'h_': - kinds.append(int(func[2:])) - if func[:3] == 'He_': - self.feature_track_kinds.append(int(func[3:])) - - # wrap all the sympy functions - def wrap_1lists(name): - func = eval("lib.%s" % name, {"lib":lib}) - def ret(lst1, out): - func(ffi.cast("double *", lst1.ctypes.data), - ffi.cast("double *", out.ctypes.data)) - return ret - def wrap_2lists(name): - func = eval("lib.%s" % name, {"lib":lib}) - def ret(lst1, lst2, out): - func(ffi.cast("double *", lst1.ctypes.data), - ffi.cast("double *", lst2.ctypes.data), - ffi.cast("double *", out.ctypes.data)) - return ret - def wrap_1list_1float(name): - func = eval("lib.%s" % name, {"lib":lib}) - def ret(lst1, fl, out): - func(ffi.cast("double *", lst1.ctypes.data), - ffi.cast("double", fl), - ffi.cast("double *", out.ctypes.data)) - return ret - - self.f = wrap_1list_1float("f_fun") - self.F = wrap_1list_1float("F_fun") - - self.err_function = wrap_2lists("err_fun") - self.inv_err_function = wrap_2lists("inv_err_fun") - self.H_mod = wrap_1lists("H_mod_fun") - - self.hs, self.Hs, self.Hes = {}, {}, {} - for kind in kinds: - self.hs[kind] = wrap_2lists("h_%d" % kind) - self.Hs[kind] = wrap_2lists("H_%d" % kind) - if self.msckf and kind in self.feature_track_kinds: - self.Hes[kind] = wrap_2lists("He_%d" % kind) - - # wrap the C++ predict function - def _predict_blas(x, P, dt): - lib.predict(ffi.cast("double *", x.ctypes.data), - ffi.cast("double *", P.ctypes.data), - ffi.cast("double *", self.Q.ctypes.data), - ffi.cast("double", dt)) - return x, P - - # wrap the C++ update function - def fun_wrapper(f, kind): - f = eval("lib.%s" % f, {"lib": lib}) - def _update_inner_blas(x, P, z, R, extra_args): - f(ffi.cast("double *", x.ctypes.data), - ffi.cast("double *", P.ctypes.data), - ffi.cast("double *", z.ctypes.data), - ffi.cast("double *", R.ctypes.data), - ffi.cast("double *", extra_args.ctypes.data)) - if self.msckf and kind in self.feature_track_kinds: - y = z[:-len(extra_args)] - else: - y = z - return x, P, y - return _update_inner_blas - - self._updates = {} - for kind in kinds: - self._updates[kind] = fun_wrapper("update_%d" % kind, kind) - - def _update_blas(x, P, kind, z, R, extra_args=[]): - return self._updates[kind](x, P, z, R, extra_args) - - # assign the functions - self._predict = _predict_blas - #self._predict = self._predict_python - self._update = _update_blas - #self._update = self._update_python - - - def init_state(self, state, covs, filter_time): - self.x = np.array(state.reshape((-1, 1))).astype(np.float64) - self.P = np.array(covs).astype(np.float64) - self.filter_time = filter_time - self.augment_times = [0]*self.N - self.rewind_obscache = [] - self.rewind_t = [] - self.rewind_states = [] - - def augment(self): - # TODO this is not a generalized way of doing - # this and implies that the augmented states - # are simply the first (dim_augment_state) - # elements of the main state. - assert self.msckf - d1 = self.dim_main - d2 = self.dim_main_err - d3 = self.dim_augment - d4 = self.dim_augment_err - # push through augmented states - self.x[d1:-d3] = self.x[d1+d3:] - self.x[-d3:] = self.x[:d3] - assert self.x.shape == (self.dim_x, 1) - # push through augmented covs - assert self.P.shape == (self.dim_err, self.dim_err) - P_reduced = self.P - P_reduced = np.delete(P_reduced, np.s_[d2:d2+d4], axis=1) - P_reduced = np.delete(P_reduced, np.s_[d2:d2+d4], axis=0) - assert P_reduced.shape == (self.dim_err -d4, self.dim_err -d4) - to_mult = np.zeros((self.dim_err, self.dim_err - d4)) - to_mult[:-d4,:] = np.eye(self.dim_err - d4) - to_mult[-d4:,:d4] = np.eye(d4) - self.P = to_mult.dot(P_reduced.dot(to_mult.T)) - self.augment_times = self.augment_times[1:] - self.augment_times.append(self.filter_time) - assert self.P.shape == (self.dim_err, self.dim_err) - - def state(self): - return np.array(self.x).flatten() - - def covs(self): - return self.P - - def rewind(self, t): - # find where we are rewinding to - idx = bisect_right(self.rewind_t, t) - assert self.rewind_t[idx-1] <= t - assert self.rewind_t[idx] > t # must be true, or rewind wouldn't be called - - # set the state to the time right before that - self.filter_time = self.rewind_t[idx-1] - self.x[:] = self.rewind_states[idx-1][0] - self.P[:] = self.rewind_states[idx-1][1] - - # return the observations we rewound over for fast forwarding - ret = self.rewind_obscache[idx:] - - # throw away the old future - # TODO: is this making a copy? - self.rewind_t = self.rewind_t[:idx] - self.rewind_states = self.rewind_states[:idx] - self.rewind_obscache = self.rewind_obscache[:idx] - - return ret - - def checkpoint(self, obs): - # push to rewinder - self.rewind_t.append(self.filter_time) - self.rewind_states.append((np.copy(self.x), np.copy(self.P))) - self.rewind_obscache.append(obs) - - # only keep a certain number around - REWIND_TO_KEEP = 512 - self.rewind_t = self.rewind_t[-REWIND_TO_KEEP:] - self.rewind_states = self.rewind_states[-REWIND_TO_KEEP:] - self.rewind_obscache = self.rewind_obscache[-REWIND_TO_KEEP:] - - def predict_and_update_batch(self, t, kind, z, R, extra_args=[[]], augment=False): - # TODO handle rewinding at this level" - - # rewind - if t < self.filter_time: - if len(self.rewind_t) == 0 or t < self.rewind_t[0] or t < self.rewind_t[-1] -1.0: - print("observation too old at %.3f with filter at %.3f, ignoring" % (t, self.filter_time)) - return None - rewound = self.rewind(t) - else: - rewound = [] - - ret = self._predict_and_update_batch(t, kind, z, R, extra_args, augment) - - # optional fast forward - for r in rewound: - self._predict_and_update_batch(*r) - - return ret - - def _predict_and_update_batch(self, t, kind, z, R, extra_args, augment=False): - """The main kalman filter function - Predicts the state and then updates a batch of observations - - dim_x: dimensionality of the state space - dim_z: dimensionality of the observation and depends on kind - n: number of observations - - Args: - t (float): Time of observation - kind (int): Type of observation - z (vec [n,dim_z]): Measurements - R (mat [n,dim_z, dim_z]): Measurement Noise - extra_args (list, [n]): Values used in H computations - """ - # initialize time - if self.filter_time is None: - self.filter_time = t - - # predict - dt = t - self.filter_time - assert dt >= 0 - self.x, self.P = self._predict(self.x, self.P, dt) - self.filter_time = t - xk_km1, Pk_km1 = np.copy(self.x).flatten(), np.copy(self.P) - - # update batch - y = [] - for i in xrange(len(z)): - # these are from the user, so we canonicalize them - z_i = np.array(z[i], dtype=np.float64, order='F') - R_i = np.array(R[i], dtype=np.float64, order='F') - extra_args_i = np.array(extra_args[i], dtype=np.float64, order='F') - # update - self.x, self.P, y_i = self._update(self.x, self.P, kind, z_i, R_i, extra_args=extra_args_i) - y.append(y_i) - xk_k, Pk_k = np.copy(self.x).flatten(), np.copy(self.P) - - if augment: - self.augment() - - # checkpoint - self.checkpoint((t, kind, z, R, extra_args)) - - return xk_km1, xk_k, Pk_km1, Pk_k, t, kind, y, z, extra_args - - def _predict_python(self, x, P, dt): - x_new = np.zeros(x.shape, dtype=np.float64) - self.f(x, dt, x_new) - - F = np.zeros(P.shape, dtype=np.float64) - self.F(x, dt, F) - - if not self.msckf: - P = dot(dot(F, P), F.T) - else: - # Update the predicted state covariance: - # Pk+1|k = |F*Pii*FT + Q*dt F*Pij | - # |PijT*FT Pjj | - # Where F is the jacobian of the main state - # predict function, Pii is the main state's - # covariance and Q its process noise. Pij - # is the covariance between the augmented - # states and the main state. - # - d2 = self.dim_main_err # known at compile time - F_curr = F[:d2, :d2] - P[:d2, :d2] = (F_curr.dot(P[:d2, :d2])).dot(F_curr.T) - P[:d2, d2:] = F_curr.dot(P[:d2, d2:]) - P[d2:, :d2] = P[d2:, :d2].dot(F_curr.T) - - P += dt*self.Q - return x_new, P - - def _update_python(self, x, P, kind, z, R, extra_args=[]): - # init vars - z = z.reshape((-1, 1)) - h = np.zeros(z.shape, dtype=np.float64) - H = np.zeros((z.shape[0], self.dim_x), dtype=np.float64) - - # C functions - self.hs[kind](x, extra_args, h) - self.Hs[kind](x, extra_args, H) - - # y is the "loss" - y = z - h - - # *** same above this line *** - - if self.msckf and kind in self.Hes: - # Do some algebraic magic to decorrelate - He = np.zeros((z.shape[0], len(extra_args)), dtype=np.float64) - self.Hes[kind](x, extra_args, He) - - # TODO: Don't call a function here, do projection locally - A = null(He.T) - - y = A.T.dot(y) - H = A.T.dot(H) - R = A.T.dot(R.dot(A)) - - # TODO If nullspace isn't the dimension we want - if A.shape[1] + He.shape[1] != A.shape[0]: - print('Warning: null space projection failed, measurement ignored') - return x, P, np.zeros(A.shape[0] - He.shape[1]) - - # if using eskf - H_mod = np.zeros((x.shape[0], P.shape[0]), dtype=np.float64) - self.H_mod(x, H_mod) - H = H.dot(H_mod) - - # Do mahalobis distance test - # currently just runs on msckf observations - # could run on anything if needed - if self.msckf and kind in self.maha_test_kinds: - a = np.linalg.inv(H.dot(P).dot(H.T) + R) - maha_dist = y.T.dot(a.dot(y)) - if maha_dist > chi2_ppf(0.95, y.shape[0]): - R = 10e16*R - - # *** same below this line *** - - # Outlier resilient weighting as described in: - # "A Kalman Filter for Robust Outlier Detection - Jo-Anne Ting, ..." - weight = 1 #(1.5)/(1 + np.sum(y**2)/np.sum(R)) - - S = dot(dot(H, P), H.T) + R/weight - K = solve(S, dot(H, P.T)).T - I_KH = np.eye(P.shape[0]) - dot(K, H) - - # update actual state - delta_x = dot(K, y) - P = dot(dot(I_KH, P), I_KH.T) + dot(dot(K, R), K.T) - - # inject observed error into state - x_new = np.zeros(x.shape, dtype=np.float64) - self.err_function(x, delta_x, x_new) - return x_new, P, y.flatten() - - def maha_test(self, x, P, kind, z, R, extra_args=[], maha_thresh=0.95): - # init vars - z = z.reshape((-1, 1)) - h = np.zeros(z.shape, dtype=np.float64) - H = np.zeros((z.shape[0], self.dim_x), dtype=np.float64) - - # C functions - self.hs[kind](x, extra_args, h) - self.Hs[kind](x, extra_args, H) - - # y is the "loss" - y = z - h - - # if using eskf - H_mod = np.zeros((x.shape[0], P.shape[0]), dtype=np.float64) - self.H_mod(x, H_mod) - H = H.dot(H_mod) - - a = np.linalg.inv(H.dot(P).dot(H.T) + R) - maha_dist = y.T.dot(a.dot(y)) - if maha_dist > chi2_ppf(maha_thresh, y.shape[0]): - return False - else: - return True - - - - - def rts_smooth(self, estimates, norm_quats=False): - ''' - Returns rts smoothed results of - kalman filter estimates - - If the kalman state is augmented with - old states only the main state is smoothed - ''' - xk_n = estimates[-1][0] - Pk_n = estimates[-1][2] - Fk_1 = np.zeros(Pk_n.shape, dtype=np.float64) - - states_smoothed = [xk_n] - covs_smoothed = [Pk_n] - for k in xrange(len(estimates) - 2, -1, -1): - xk1_n = xk_n - if norm_quats: - xk1_n[3:7] /= np.linalg.norm(xk1_n[3:7]) - Pk1_n = Pk_n - - xk1_k, _, Pk1_k, _, t2, _, _, _, _ = estimates[k + 1] - _, xk_k, _, Pk_k, t1, _, _, _, _ = estimates[k] - dt = t2 - t1 - self.F(xk_k, dt, Fk_1) - - d1 = self.dim_main - d2 = self.dim_main_err - Ck = np.linalg.solve(Pk1_k[:d2,:d2], Fk_1[:d2,:d2].dot(Pk_k[:d2,:d2].T)).T - xk_n = xk_k - delta_x = np.zeros((Pk_n.shape[0], 1), dtype=np.float64) - self.inv_err_function(xk1_k, xk1_n, delta_x) - delta_x[:d2] = Ck.dot(delta_x[:d2]) - x_new = np.zeros((xk_n.shape[0], 1), dtype=np.float64) - self.err_function(xk_k, delta_x, x_new) - xk_n[:d1] = x_new[:d1,0] - Pk_n = Pk_k - Pk_n[:d2,:d2] = Pk_k[:d2,:d2] + Ck.dot(Pk1_n[:d2,:d2] - Pk1_k[:d2,:d2]).dot(Ck.T) - states_smoothed.append(xk_n) - covs_smoothed.append(Pk_n) - - return np.flipud(np.vstack(states_smoothed)), np.stack(covs_smoothed, 0)[::-1] diff --git a/selfdrive/locationd/kalman/kalman_helpers.py b/selfdrive/locationd/kalman/kalman_helpers.py deleted file mode 100644 index ded1fd3fd3..0000000000 --- a/selfdrive/locationd/kalman/kalman_helpers.py +++ /dev/null @@ -1,165 +0,0 @@ -import numpy as np -import os -from bisect import bisect -from tqdm import tqdm - - -class ObservationKind(object): - UNKNOWN = 0 - NO_OBSERVATION = 1 - GPS_NED = 2 - ODOMETRIC_SPEED = 3 - PHONE_GYRO = 4 - GPS_VEL = 5 - PSEUDORANGE_GPS = 6 - PSEUDORANGE_RATE_GPS = 7 - SPEED = 8 - NO_ROT = 9 - PHONE_ACCEL = 10 - ORB_POINT = 11 - ECEF_POS = 12 - CAMERA_ODO_TRANSLATION = 13 - CAMERA_ODO_ROTATION = 14 - ORB_FEATURES = 15 - MSCKF_TEST = 16 - FEATURE_TRACK_TEST = 17 - LANE_PT = 18 - IMU_FRAME = 19 - PSEUDORANGE_GLONASS = 20 - PSEUDORANGE_RATE_GLONASS = 21 - PSEUDORANGE = 22 - PSEUDORANGE_RATE = 23 - - names = ['Unknown', - 'No observation', - 'GPS NED', - 'Odometric speed', - 'Phone gyro', - 'GPS velocity', - 'GPS pseudorange', - 'GPS pseudorange rate', - 'Speed', - 'No rotation', - 'Phone acceleration', - 'ORB point', - 'ECEF pos', - 'camera odometric translation', - 'camera odometric rotation', - 'ORB features', - 'MSCKF test', - 'Feature track test', - 'Lane ecef point', - 'imu frame eulers', - 'GLONASS pseudorange', - 'GLONASS pseudorange rate'] - - @classmethod - def to_string(cls, kind): - return cls.names[kind] - - - -SAT_OBS = [ObservationKind.PSEUDORANGE_GPS, - ObservationKind.PSEUDORANGE_RATE_GPS, - ObservationKind.PSEUDORANGE_GLONASS, - ObservationKind.PSEUDORANGE_RATE_GLONASS] - - -def run_car_ekf_offline(kf, observations_by_kind): - from laika.raw_gnss import GNSSMeasurement # pylint: disable=import-error - observations = [] - # create list of observations with element format: [kind, time, data] - for kind in observations_by_kind: - for t, data in zip(observations_by_kind[kind][0], observations_by_kind[kind][1]): - observations.append([t, kind, data]) - observations.sort(key=lambda obs: obs[0]) - - times, estimates = run_observations_through_filter(kf, observations) - - forward_states = np.stack(e[1] for e in estimates) - forward_covs = np.stack(e[3] for e in estimates) - smoothed_states, smoothed_covs = kf.rts_smooth(estimates) - - observations_dict = {} - # TODO assuming observations and estimates - # are same length may not work with VO - for e in estimates: - t = e[4] - kind = str(int(e[5])) - res = e[6] - z = e[7] - ea = e[8] - if len(z) == 0: - continue - if kind not in observations_dict: - observations_dict[kind] = {} - observations_dict[kind]['t'] = np.array(len(z)*[t]) - observations_dict[kind]['z'] = np.array(z) - observations_dict[kind]['ea'] = np.array(ea) - observations_dict[kind]['residual'] = np.array(res) - else: - observations_dict[kind]['t'] = np.append(observations_dict[kind]['t'], np.array(len(z)*[t])) - observations_dict[kind]['z'] = np.vstack((observations_dict[kind]['z'], np.array(z))) - observations_dict[kind]['ea'] = np.vstack((observations_dict[kind]['ea'], np.array(ea))) - observations_dict[kind]['residual'] = np.vstack((observations_dict[kind]['residual'], np.array(res))) - - # add svIds to gnss data - for kind in map(str, SAT_OBS): - if int(kind) in observations_by_kind and kind in observations_dict: - observations_dict[kind]['svIds'] = np.array([]) - observations_dict[kind]['CNO'] = np.array([]) - observations_dict[kind]['std'] = np.array([]) - for obs in observations_by_kind[int(kind)][1]: - observations_dict[kind]['svIds'] = np.append(observations_dict[kind]['svIds'], - np.array([obs[:,GNSSMeasurement.PRN]])) - observations_dict[kind]['std'] = np.append(observations_dict[kind]['std'], - np.array([obs[:,GNSSMeasurement.PR_STD]])) - return smoothed_states, smoothed_covs, forward_states, forward_covs, times, observations_dict - - -def run_observations_through_filter(kf, observations, filter_time=None): - estimates = [] - - for obs in tqdm(observations): - t = obs[0] - kind = obs[1] - data = obs[2] - estimates.append(kf.predict_and_observe(t, kind, data)) - times = [x[4] for x in estimates] - return times, estimates - - -def save_residuals_plot(obs, save_path, data_name): - import matplotlib.pyplot as plt - import mpld3 # pylint: disable=import-error - fig = plt.figure(figsize=(10,20)) - fig.suptitle('Residuals of ' + data_name, fontsize=24) - n = len(obs.keys()) - start_times = [obs[kind]['t'][0] for kind in obs] - start_time = min(start_times) - xlims = [start_time + 3, start_time + 60] - - for i, kind in enumerate(obs): - ax = fig.add_subplot(n, 1, i+1) - ax.set_xlim(xlims) - t = obs[kind]['t'] - res = obs[kind]['residual'] - start_idx = bisect(t, xlims[0]) - if len(res) == start_idx: - continue - ylim = max(np.linalg.norm(res[start_idx:], axis=1)) - ax.set_ylim([-ylim, ylim]) - if int(kind) in SAT_OBS: - svIds = obs[kind]['svIds'] - for svId in set(svIds): - svId_idx = (svIds == svId) - t = obs[kind]['t'][svId_idx] - res = obs[kind]['residual'][svId_idx] - ax.plot(t, res, label='SV ' + str(int(svId))) - ax.legend(loc='right') - else: - ax.plot(t, res) - plt.title('Residual of kind ' + ObservationKind.to_string(int(kind)), fontsize=20) - plt.tight_layout() - os.makedirs(save_path) - mpld3.save_html(fig, save_path + 'residuals_plot.html') diff --git a/selfdrive/locationd/kalman/loc_local_kf.py b/selfdrive/locationd/kalman/loc_local_kf.py deleted file mode 100755 index 331b7fee6f..0000000000 --- a/selfdrive/locationd/kalman/loc_local_kf.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python -import numpy as np -from selfdrive.locationd.kalman import loc_local_model - -from selfdrive.locationd.kalman.kalman_helpers import ObservationKind -from selfdrive.locationd.kalman.ekf_sym import EKF_sym - - - -class States(object): - VELOCITY = slice(0,3) # device frame velocity in m/s - ANGULAR_VELOCITY = slice(3, 6) # roll, pitch and yaw rates in device frame in radians/s - GYRO_BIAS = slice(6, 9) # roll, pitch and yaw biases - ODO_SCALE = slice(9, 10) # odometer scale - ACCELERATION = slice(10, 13) # Acceleration in device frame in m/s**2 - - -class LocLocalKalman(object): - def __init__(self): - x_initial = np.array([0, 0, 0, - 0, 0, 0, - 0, 0, 0, - 1, - 0, 0, 0]) - - # state covariance - P_initial = np.diag([10**2, 10**2, 10**2, - 1**2, 1**2, 1**2, - 0.05**2, 0.05**2, 0.05**2, - 0.02**2, - 1**2, 1**2, 1**2]) - - # process noise - Q = np.diag([0.0**2, 0.0**2, 0.0**2, - .01**2, .01**2, .01**2, - (0.005/100)**2, (0.005/100)**2, (0.005/100)**2, - (0.02/100)**2, - 3**2, 3**2, 3**2]) - - self.obs_noise = {ObservationKind.ODOMETRIC_SPEED: np.atleast_2d(0.2**2), - ObservationKind.PHONE_GYRO: np.diag([0.025**2, 0.025**2, 0.025**2])} - - # MSCKF stuff - self.dim_state = len(x_initial) - self.dim_main = self.dim_state - - name = 'loc_local' - loc_local_model.gen_model(name, self.dim_state) - - # init filter - self.filter = EKF_sym(name, Q, x_initial, P_initial, self.dim_main, self.dim_main) - - @property - def x(self): - return self.filter.state() - - @property - def t(self): - return self.filter.filter_time - - @property - def P(self): - return self.filter.covs() - - def predict(self, t): - if self.t: - # Does NOT modify filter state - return self.filter._predict(self.x, self.P, t - self.t)[0] - else: - raise RuntimeError("Request predict on filter with uninitialized time") - - def rts_smooth(self, estimates): - return self.filter.rts_smooth(estimates, norm_quats=True) - - - def init_state(self, state, covs_diag=None, covs=None, filter_time=None): - if covs_diag is not None: - P = np.diag(covs_diag) - elif covs is not None: - P = covs - else: - P = self.filter.covs() - self.filter.init_state(state, P, filter_time) - - def predict_and_observe(self, t, kind, data): - if len(data) > 0: - data = np.atleast_2d(data) - if kind == ObservationKind.CAMERA_ODO_TRANSLATION: - r = self.predict_and_update_odo_trans(data, t, kind) - elif kind == ObservationKind.CAMERA_ODO_ROTATION: - r = self.predict_and_update_odo_rot(data, t, kind) - elif kind == ObservationKind.ODOMETRIC_SPEED: - r = self.predict_and_update_odo_speed(data, t, kind) - else: - r = self.filter.predict_and_update_batch(t, kind, data, self.get_R(kind, len(data))) - return r - - def get_R(self, kind, n): - obs_noise = self.obs_noise[kind] - dim = obs_noise.shape[0] - R = np.zeros((n, dim, dim)) - for i in xrange(n): - R[i,:,:] = obs_noise - return R - - def predict_and_update_odo_speed(self, speed, t, kind): - z = np.array(speed) - R = np.zeros((len(speed), 1, 1)) - for i, _ in enumerate(z): - R[i,:,:] = np.diag([0.2**2]) - return self.filter.predict_and_update_batch(t, kind, z, R) - - def predict_and_update_odo_trans(self, trans, t, kind): - z = trans[:,:3] - R = np.zeros((len(trans), 3, 3)) - for i, _ in enumerate(z): - R[i,:,:] = np.diag(trans[i,3:]**2) - return self.filter.predict_and_update_batch(t, kind, z, R) - - def predict_and_update_odo_rot(self, rot, t, kind): - z = rot[:,:3] - R = np.zeros((len(rot), 3, 3)) - for i, _ in enumerate(z): - R[i,:,:] = np.diag(rot[i,3:]**2) - return self.filter.predict_and_update_batch(t, kind, z, R) - -if __name__ == "__main__": - LocLocalKalman() diff --git a/selfdrive/locationd/kalman/loc_local_model.py b/selfdrive/locationd/kalman/loc_local_model.py deleted file mode 100644 index bc80d9911f..0000000000 --- a/selfdrive/locationd/kalman/loc_local_model.py +++ /dev/null @@ -1,80 +0,0 @@ -import numpy as np -import sympy as sp -import os - -from selfdrive.locationd.kalman.kalman_helpers import ObservationKind -from selfdrive.locationd.kalman.ekf_sym import gen_code - - -def gen_model(name, dim_state): - - # check if rebuild is needed - try: - dir_path = os.path.dirname(__file__) - deps = [dir_path + '/' + 'ekf_c.c', - dir_path + '/' + 'ekf_sym.py', - dir_path + '/' + 'loc_local_model.py', - dir_path + '/' + 'loc_local_kf.py'] - - outs = [dir_path + '/' + name + '.o', - dir_path + '/' + name + '.so', - dir_path + '/' + name + '.cpp'] - out_times = map(os.path.getmtime, outs) - dep_times = map(os.path.getmtime, deps) - rebuild = os.getenv("REBUILD", False) - if min(out_times) > max(dep_times) and not rebuild: - return - map(os.remove, outs) - except OSError: - pass - - # make functions and jacobians with sympy - # state variables - state_sym = sp.MatrixSymbol('state', dim_state, 1) - state = sp.Matrix(state_sym) - v = state[0:3,:] - omega = state[3:6,:] - vroll, vpitch, vyaw = omega - vx, vy, vz = v - roll_bias, pitch_bias, yaw_bias = state[6:9,:] - odo_scale = state[9,:] - accel = state[10:13,:] - - dt = sp.Symbol('dt') - - # Time derivative of the state as a function of state - state_dot = sp.Matrix(np.zeros((dim_state, 1))) - state_dot[:3,:] = accel - - # Basic descretization, 1st order intergrator - # Can be pretty bad if dt is big - f_sym = sp.Matrix(state + dt*state_dot) - - # - # Observation functions - # - - # extra args - #imu_rot = euler_rotate(*imu_angles) - #h_gyro_sym = imu_rot*sp.Matrix([vroll + roll_bias, - # vpitch + pitch_bias, - # vyaw + yaw_bias]) - h_gyro_sym = sp.Matrix([vroll + roll_bias, - vpitch + pitch_bias, - vyaw + yaw_bias]) - - speed = vx**2 + vy**2 + vz**2 - h_speed_sym = sp.Matrix([sp.sqrt(speed)*odo_scale]) - - h_relative_motion = sp.Matrix(v) - h_phone_rot_sym = sp.Matrix([vroll, - vpitch, - vyaw]) - - - obs_eqs = [[h_speed_sym, ObservationKind.ODOMETRIC_SPEED, None], - [h_gyro_sym, ObservationKind.PHONE_GYRO, None], - [h_phone_rot_sym, ObservationKind.NO_ROT, None], - [h_relative_motion, ObservationKind.CAMERA_ODO_TRANSLATION, None], - [h_phone_rot_sym, ObservationKind.CAMERA_ODO_ROTATION, None]] - gen_code(name, f_sym, dt, state_sym, obs_eqs, dim_state, dim_state) diff --git a/selfdrive/locationd/locationd_local.py b/selfdrive/locationd/locationd_local.py deleted file mode 100755 index 627f873032..0000000000 --- a/selfdrive/locationd/locationd_local.py +++ /dev/null @@ -1,285 +0,0 @@ -#!/usr/bin/env python -import os -import zmq -import math -import json - -os.environ["OMP_NUM_THREADS"] = "1" -import numpy as np -from bisect import bisect_right - -from cereal import car -from common.params import Params -from common.numpy_fast import clip -import selfdrive.messaging as messaging -from selfdrive.swaglog import cloudlog -from selfdrive.controls.lib.vehicle_model import VehicleModel -from selfdrive.services import service_list -from selfdrive.locationd.kalman.loc_local_kf import LocLocalKalman -from selfdrive.locationd.kalman.kalman_helpers import ObservationKind - -DEBUG = False -kf = LocLocalKalman() # Make sure that model is generated on import time - -MAX_ANGLE_OFFSET = math.radians(10.) -MAX_ANGLE_OFFSET_TH = math.radians(9.) -MIN_STIFFNESS = 0.5 -MAX_STIFFNESS = 2.0 -MIN_SR = 0.5 -MAX_SR = 2.0 -MIN_SR_TH = 0.55 -MAX_SR_TH = 1.9 - -LEARNING_RATE = 3 - - -class Localizer(object): - def __init__(self, disabled_logs=None, dog=None): - self.kf = LocLocalKalman() - self.reset_kalman() - - self.sensor_data_t = 0.0 - self.max_age = .2 # seconds - self.calibration_valid = False - - if disabled_logs is None: - self.disabled_logs = list() - else: - self.disabled_logs = disabled_logs - - def reset_kalman(self): - self.filter_time = None - self.observation_buffer = [] - self.converter = None - self.speed_counter = 0 - self.sensor_counter = 0 - - def liveLocationMsg(self, time): - fix = messaging.log.KalmanOdometry.new_message() - - predicted_state = self.kf.x - fix.trans = [float(predicted_state[0]), float(predicted_state[1]), float(predicted_state[2])] - fix.rot = [float(predicted_state[3]), float(predicted_state[4]), float(predicted_state[5])] - - return fix - - def update_kalman(self, time, kind, meas): - idx = bisect_right([x[0] for x in self.observation_buffer], time) - self.observation_buffer.insert(idx, (time, kind, meas)) - while self.observation_buffer[-1][0] - self.observation_buffer[0][0] > self.max_age: - self.kf.predict_and_observe(*self.observation_buffer.pop(0)) - - def handle_cam_odo(self, log, current_time): - self.update_kalman(current_time, ObservationKind.CAMERA_ODO_ROTATION, np.concatenate([log.cameraOdometry.rot, - log.cameraOdometry.rotStd])) - self.update_kalman(current_time, ObservationKind.CAMERA_ODO_TRANSLATION, np.concatenate([log.cameraOdometry.trans, - log.cameraOdometry.transStd])) - - def handle_controls_state(self, log, current_time): - self.speed_counter += 1 - if self.speed_counter % 5 == 0: - self.update_kalman(current_time, ObservationKind.ODOMETRIC_SPEED, np.array([log.controlsState.vEgo])) - - def handle_sensors(self, log, current_time): - for sensor_reading in log.sensorEvents: - # TODO does not yet account for double sensor readings in the log - if sensor_reading.type == 4: - self.sensor_counter += 1 - if self.sensor_counter % LEARNING_RATE == 0: - self.update_kalman(current_time, ObservationKind.PHONE_GYRO, [-sensor_reading.gyro.v[2], -sensor_reading.gyro.v[1], -sensor_reading.gyro.v[0]]) - - def handle_log(self, log): - current_time = 1e-9 * log.logMonoTime - typ = log.which - if typ in self.disabled_logs: - return - if typ == "sensorEvents": - self.sensor_data_t = current_time - self.handle_sensors(log, current_time) - elif typ == "controlsState": - self.handle_controls_state(log, current_time) - elif typ == "cameraOdometry": - self.handle_cam_odo(log, current_time) - - -class ParamsLearner(object): - def __init__(self, VM, angle_offset=0., stiffness_factor=1.0, steer_ratio=None, learning_rate=1.0): - self.VM = VM - - self.ao = math.radians(angle_offset) - self.slow_ao = math.radians(angle_offset) - self.x = stiffness_factor - self.sR = VM.sR if steer_ratio is None else steer_ratio - self.MIN_SR = MIN_SR * self.VM.sR - self.MAX_SR = MAX_SR * self.VM.sR - self.MIN_SR_TH = MIN_SR_TH * self.VM.sR - self.MAX_SR_TH = MAX_SR_TH * self.VM.sR - - self.alpha1 = 0.01 * learning_rate - self.alpha2 = 0.0005 * learning_rate - self.alpha3 = 0.1 * learning_rate - self.alpha4 = 1.0 * learning_rate - - def get_values(self): - return { - 'angleOffsetAverage': math.degrees(self.slow_ao), - 'stiffnessFactor': self.x, - 'steerRatio': self.sR, - } - - def update(self, psi, u, sa): - cF0 = self.VM.cF - cR0 = self.VM.cR - aR = self.VM.aR - aF = self.VM.aF - l = self.VM.l - m = self.VM.m - - x = self.x - ao = self.ao - sR = self.sR - - # Gradient descent: learn angle offset, tire stiffness and steer ratio. - if u > 10.0 and abs(math.degrees(sa)) < 15.: - self.ao -= self.alpha1 * 2.0*cF0*cR0*l*u*x*(1.0*cF0*cR0*l*u*x*(ao - sa) + psi*sR*(cF0*cR0*l**2*x - m*u**2*(aF*cF0 - aR*cR0)))/(sR**2*(cF0*cR0*l**2*x - m*u**2*(aF*cF0 - aR*cR0))**2) - - ao = self.slow_ao - self.slow_ao -= self.alpha2 * 2.0*cF0*cR0*l*u*x*(1.0*cF0*cR0*l*u*x*(ao - sa) + psi*sR*(cF0*cR0*l**2*x - m*u**2*(aF*cF0 - aR*cR0)))/(sR**2*(cF0*cR0*l**2*x - m*u**2*(aF*cF0 - aR*cR0))**2) - - self.x -= self.alpha3 * -2.0*cF0*cR0*l*m*u**3*(ao - sa)*(aF*cF0 - aR*cR0)*(1.0*cF0*cR0*l*u*x*(ao - sa) + psi*sR*(cF0*cR0*l**2*x - m*u**2*(aF*cF0 - aR*cR0)))/(sR**2*(cF0*cR0*l**2*x - m*u**2*(aF*cF0 - aR*cR0))**3) - - self.sR -= self.alpha4 * -2.0*cF0*cR0*l*u*x*(ao - sa)*(1.0*cF0*cR0*l*u*x*(ao - sa) + psi*sR*(cF0*cR0*l**2*x - m*u**2*(aF*cF0 - aR*cR0)))/(sR**3*(cF0*cR0*l**2*x - m*u**2*(aF*cF0 - aR*cR0))**2) - - if DEBUG: - # s1 = "Measured yaw rate % .6f" % psi - # ao = 0. - # s2 = "Uncompensated yaw % .6f" % (1.0*u*(-ao + sa)/(l*sR*(1 - m*u**2*(aF*cF0*x - aR*cR0*x)/(cF0*cR0*l**2*x**2)))) - # instant_ao = aF*m*psi*sR*u/(cR0*l*x) - aR*m*psi*sR*u/(cF0*l*x) - l*psi*sR/u + sa - s4 = "Instant AO: % .2f Avg. AO % .2f" % (math.degrees(self.ao), math.degrees(self.slow_ao)) - s5 = "Stiffnes: % .3f x" % self.x - print("{0} {1}".format(s4, s5)) - - - self.ao = clip(self.ao, -MAX_ANGLE_OFFSET, MAX_ANGLE_OFFSET) - self.slow_ao = clip(self.slow_ao, -MAX_ANGLE_OFFSET, MAX_ANGLE_OFFSET) - self.x = clip(self.x, MIN_STIFFNESS, MAX_STIFFNESS) - self.sR = clip(self.sR, self.MIN_SR, self.MAX_SR) - - # don't check stiffness for validity, as it can change quickly if sR is off - valid = abs(self.slow_ao) < MAX_ANGLE_OFFSET_TH and \ - self.sR > self.MIN_SR_TH and self.sR < self.MAX_SR_TH - - return valid - - -def locationd_thread(gctx, addr, disabled_logs): - ctx = zmq.Context() - poller = zmq.Poller() - - controls_state_socket = messaging.sub_sock(ctx, service_list['controlsState'].port, poller, addr=addr, conflate=True) - sensor_events_socket = messaging.sub_sock(ctx, service_list['sensorEvents'].port, poller, addr=addr, conflate=True) - camera_odometry_socket = messaging.sub_sock(ctx, service_list['cameraOdometry'].port, poller, addr=addr, conflate=True) - - kalman_odometry_socket = messaging.pub_sock(ctx, service_list['kalmanOdometry'].port) - live_parameters_socket = messaging.pub_sock(ctx, service_list['liveParameters'].port) - - params_reader = Params() - cloudlog.info("Parameter learner is waiting for CarParams") - CP = car.CarParams.from_bytes(params_reader.get("CarParams", block=True)) - VM = VehicleModel(CP) - cloudlog.info("Parameter learner got CarParams: %s" % CP.carFingerprint) - - params = params_reader.get("LiveParameters") - - # Check if car model matches - if params is not None: - params = json.loads(params) - if (params.get('carFingerprint', None) != CP.carFingerprint) or (params.get('carVin', CP.carVin) != CP.carVin): - cloudlog.info("Parameter learner found parameters for wrong car.") - params = None - - if params is None: - params = { - 'carFingerprint': CP.carFingerprint, - 'carVin': CP.carVin, - 'angleOffsetAverage': 0.0, - 'stiffnessFactor': 1.0, - 'steerRatio': VM.sR, - } - params_reader.put("LiveParameters", json.dumps(params)) - cloudlog.info("Parameter learner resetting to default values") - - cloudlog.info("Parameter starting with: %s" % str(params)) - localizer = Localizer(disabled_logs=disabled_logs) - - learner = ParamsLearner(VM, - angle_offset=params['angleOffsetAverage'], - stiffness_factor=params['stiffnessFactor'], - steer_ratio=params['steerRatio'], - learning_rate=LEARNING_RATE) - - i = 1 - while True: - for socket, event in poller.poll(timeout=1000): - log = messaging.recv_one(socket) - localizer.handle_log(log) - - if socket is controls_state_socket: - if not localizer.kf.t: - continue - - if i % LEARNING_RATE == 0: - # controlsState is not updating the Kalman Filter, so update KF manually - localizer.kf.predict(1e-9 * log.logMonoTime) - - predicted_state = localizer.kf.x - yaw_rate = -float(predicted_state[5]) - - steering_angle = math.radians(log.controlsState.angleSteers) - params_valid = learner.update(yaw_rate, log.controlsState.vEgo, steering_angle) - - log_t = 1e-9 * log.logMonoTime - sensor_data_age = log_t - localizer.sensor_data_t - - params = messaging.new_message() - params.init('liveParameters') - params.liveParameters.valid = bool(params_valid) - params.liveParameters.sensorValid = bool(sensor_data_age < 5.0) - params.liveParameters.angleOffset = float(math.degrees(learner.ao)) - params.liveParameters.angleOffsetAverage = float(math.degrees(learner.slow_ao)) - params.liveParameters.stiffnessFactor = float(learner.x) - params.liveParameters.steerRatio = float(learner.sR) - live_parameters_socket.send(params.to_bytes()) - - if i % 6000 == 0: # once a minute - params = learner.get_values() - params['carFingerprint'] = CP.carFingerprint - params['carVin'] = CP.carVin - params_reader.put("LiveParameters", json.dumps(params)) - params_reader.put("ControlsParams", json.dumps({'angle_model_bias': log.controlsState.angleModelBias})) - - i += 1 - elif socket is camera_odometry_socket: - msg = messaging.new_message() - msg.init('kalmanOdometry') - msg.logMonoTime = log.logMonoTime - msg.kalmanOdometry = localizer.liveLocationMsg(log.logMonoTime * 1e-9) - kalman_odometry_socket.send(msg.to_bytes()) - elif socket is sensor_events_socket: - pass - - -def main(gctx=None, addr="127.0.0.1"): - IN_CAR = os.getenv("IN_CAR", False) - disabled_logs = os.getenv("DISABLED_LOGS", "").split(",") - - # No speed for now - disabled_logs.append('controlsState') - if IN_CAR: - addr = "192.168.5.11" - - locationd_thread(gctx, addr, disabled_logs) - - -if __name__ == "__main__": - main() diff --git a/selfdrive/locationd/locationd_yawrate.cc b/selfdrive/locationd/locationd_yawrate.cc new file mode 100644 index 0000000000..f03f808ffd --- /dev/null +++ b/selfdrive/locationd/locationd_yawrate.cc @@ -0,0 +1,311 @@ +#include +#include +#include + +#include +#include +#include +#include +#include "json11.hpp" + +#include "cereal/gen/cpp/log.capnp.h" +#include "common/swaglog.h" +#include "common/messaging.h" +#include "common/params.h" +#include "common/timing.h" +#include "params_learner.h" + +const int num_polls = 3; + +class Localizer +{ + Eigen::Matrix2d A; + Eigen::Matrix2d I; + Eigen::Matrix2d Q; + Eigen::Matrix2d P; + Eigen::Matrix C_posenet; + Eigen::Matrix C_gyro; + + double R_gyro; + + void update_state(const Eigen::Matrix &C, const double R, double current_time, double meas) { + double dt = current_time - prev_update_time; + prev_update_time = current_time; + if (dt < 1.0e-9) { + return; + } + + // x = A * x; + // P = A * P * A.transpose() + dt * Q; + // Simplify because A is unity + P = P + dt * Q; + + double y = meas - C * x; + double S = R + C * P * C.transpose(); + Eigen::Vector2d K = P * C.transpose() * (1.0 / S); + x = x + K * y; + P = (I - K * C) * P; + } + + void handle_sensor_events(capnp::List::Reader sensor_events, double current_time) { + for (cereal::SensorEventData::Reader sensor_event : sensor_events){ + if (sensor_event.getType() == 4) { + sensor_data_time = current_time; + + double meas = -sensor_event.getGyro().getV()[0]; + update_state(C_gyro, R_gyro, current_time, meas); + } + } + + } + + void handle_camera_odometry(cereal::CameraOdometry::Reader camera_odometry, double current_time) { + double R = 250.0 * pow(camera_odometry.getRotStd()[2], 2); + double meas = camera_odometry.getRot()[2]; + update_state(C_posenet, R, current_time, meas); + } + + void handle_controls_state(cereal::ControlsState::Reader controls_state, double current_time) { + steering_angle = controls_state.getAngleSteers() * DEGREES_TO_RADIANS; + car_speed = controls_state.getVEgo(); + controls_state_time = current_time; + } + + +public: + Eigen::Vector2d x; + double steering_angle = 0; + double car_speed = 0; + double prev_update_time = -1; + double controls_state_time = -1; + double sensor_data_time = -1; + + Localizer() { + A << 1, 0, 0, 1; + I << 1, 0, 0, 1; + + Q << pow(0.1, 2.0), 0, 0, pow(0.005 / 100.0, 2.0); + P << pow(1.0, 2.0), 0, 0, pow(0.05, 2.0); + + C_posenet << 1, 0; + C_gyro << 1, 1; + x << 0, 0; + + R_gyro = pow(0.05, 2.0); + } + + cereal::Event::Which handle_log(const unsigned char* msg_dat, size_t msg_size) { + const kj::ArrayPtr view((const capnp::word*)msg_dat, msg_size); + capnp::FlatArrayMessageReader msg(view); + cereal::Event::Reader event = msg.getRoot(); + double current_time = event.getLogMonoTime() / 1.0e9; + + if (prev_update_time < 0) { + prev_update_time = current_time; + } + + auto type = event.which(); + switch(type) { + case cereal::Event::CONTROLS_STATE: + handle_controls_state(event.getControlsState(), current_time); + break; + case cereal::Event::CAMERA_ODOMETRY: + handle_camera_odometry(event.getCameraOdometry(), current_time); + break; + case cereal::Event::SENSOR_EVENTS: + handle_sensor_events(event.getSensorEvents(), current_time); + break; + default: + break; + } + + return type; + } +}; + + + +int main(int argc, char *argv[]) { + auto ctx = zmq_ctx_new(); + auto controls_state_sock = sub_sock(ctx, "tcp://127.0.0.1:8007"); + auto sensor_events_sock = sub_sock(ctx, "tcp://127.0.0.1:8003"); + auto camera_odometry_sock = sub_sock(ctx, "tcp://127.0.0.1:8066"); + + auto live_parameters_sock = zsock_new_pub("@tcp://*:8064"); + assert(live_parameters_sock); + auto live_parameters_sock_raw = zsock_resolve(live_parameters_sock); + + int err; + Localizer localizer; + + zmq_pollitem_t polls[num_polls] = {{0}}; + polls[0].socket = controls_state_sock; + polls[0].events = ZMQ_POLLIN; + polls[1].socket = sensor_events_sock; + polls[1].events = ZMQ_POLLIN; + polls[2].socket = camera_odometry_sock; + polls[2].events = ZMQ_POLLIN; + + // Read car params + char *value; + size_t value_sz = 0; + + LOGW("waiting for params to set vehicle model"); + while (true) { + read_db_value(NULL, "CarParams", &value, &value_sz); + if (value_sz > 0) break; + usleep(100*1000); + } + LOGW("got %d bytes CarParams", value_sz); + + // make copy due to alignment issues + auto amsg = kj::heapArray((value_sz / sizeof(capnp::word)) + 1); + memcpy(amsg.begin(), value, value_sz); + free(value); + + capnp::FlatArrayMessageReader cmsg(amsg); + cereal::CarParams::Reader car_params = cmsg.getRoot(); + + // Read params from previous run + const int result = read_db_value(NULL, "LiveParameters", &value, &value_sz); + + std::string fingerprint = car_params.getCarFingerprint(); + std::string vin = car_params.getCarVin(); + double sR = car_params.getSteerRatio(); + double x = 1.0; + double ao = 0.0; + + if (result == 0){ + auto str = std::string(value, value_sz); + free(value); + + std::string err; + auto json = json11::Json::parse(str, err); + if (json.is_null() || !err.empty()) { + std::string log = "Error parsing json: " + err; + LOGW(log.c_str()); + } else { + std::string new_fingerprint = json["carFingerprint"].string_value(); + std::string new_vin = json["carVin"].string_value(); + + if (fingerprint == new_fingerprint && vin == new_vin) { + std::string log = "Parameter starting with: " + str; + LOGW(log.c_str()); + + sR = json["steerRatio"].number_value(); + x = json["stiffnessFactor"].number_value(); + ao = json["angleOffsetAverage"].number_value(); + } + } + } + + ParamsLearner learner(car_params, ao, x, sR, 1.0); + + // Main loop + int save_counter = 0; + while (true){ + int ret = zmq_poll(polls, num_polls, 100); + + if (ret == 0){ + continue; + } else if (ret < 0){ + break; + } + + for (int i=0; i < num_polls; i++) { + if (polls[i].revents) { + zmq_msg_t msg; + err = zmq_msg_init(&msg); + assert(err == 0); + err = zmq_msg_recv(&msg, polls[i].socket, 0); + assert(err >= 0); + // make copy due to alignment issues, will be freed on out of scope + auto amsg = kj::heapArray((zmq_msg_size(&msg) / sizeof(capnp::word)) + 1); + memcpy(amsg.begin(), zmq_msg_data(&msg), zmq_msg_size(&msg)); + + auto which = localizer.handle_log((const unsigned char*)amsg.begin(), amsg.size()); + zmq_msg_close(&msg); + + if (which == cereal::Event::CONTROLS_STATE){ + save_counter++; + + double yaw_rate = -localizer.x[0]; + bool valid = learner.update(yaw_rate, localizer.car_speed, localizer.steering_angle); + + // TODO: Fix in replay + double sensor_data_age = localizer.controls_state_time - localizer.sensor_data_time; + + double angle_offset_degrees = RADIANS_TO_DEGREES * learner.ao; + double angle_offset_average_degrees = RADIANS_TO_DEGREES * learner.slow_ao; + + // Send parameters at 10 Hz + if (save_counter % 10 == 0){ + capnp::MallocMessageBuilder msg; + cereal::Event::Builder event = msg.initRoot(); + event.setLogMonoTime(nanos_since_boot()); + auto live_params = event.initLiveParameters(); + live_params.setValid(valid); + live_params.setYawRate(localizer.x[0]); + live_params.setGyroBias(localizer.x[1]); + live_params.setSensorValid(sensor_data_age < 5.0); + live_params.setAngleOffset(angle_offset_degrees); + live_params.setAngleOffsetAverage(angle_offset_average_degrees); + live_params.setStiffnessFactor(learner.x); + live_params.setSteerRatio(learner.sR); + + auto words = capnp::messageToFlatArray(msg); + auto bytes = words.asBytes(); + zmq_send(live_parameters_sock_raw, bytes.begin(), bytes.size(), ZMQ_DONTWAIT); + } + + + // Save parameters every minute + if (save_counter % 6000 == 0) { + json11::Json json = json11::Json::object { + {"carVin", vin}, + {"carFingerprint", fingerprint}, + {"steerRatio", learner.sR}, + {"stiffnessFactor", learner.x}, + {"angleOffsetAverage", angle_offset_average_degrees}, + }; + + std::string out = json.dump(); + write_db_value(NULL, "LiveParameters", out.c_str(), out.length()); + } + } + } + } + } + + zmq_close(controls_state_sock); + zmq_close(sensor_events_sock); + zmq_close(camera_odometry_sock); + zmq_close(live_parameters_sock_raw); + return 0; +} + + +extern "C" { + void *localizer_init(void) { + Localizer * localizer = new Localizer; + return (void*)localizer; + } + + void localizer_handle_log(void * localizer, const unsigned char * data, size_t len) { + Localizer * loc = (Localizer*) localizer; + loc->handle_log(data, len); + } + + double localizer_get_yaw(void * localizer) { + Localizer * loc = (Localizer*) localizer; + return loc->x[0]; + } + double localizer_get_bias(void * localizer) { + Localizer * loc = (Localizer*) localizer; + return loc->x[1]; + } + double localizer_get_t(void * localizer) { + Localizer * loc = (Localizer*) localizer; + return loc->prev_update_time; + } +} diff --git a/selfdrive/locationd/params_learner.cc b/selfdrive/locationd/params_learner.cc new file mode 100644 index 0000000000..a150805d86 --- /dev/null +++ b/selfdrive/locationd/params_learner.cc @@ -0,0 +1,75 @@ +#include +#include +#include + +#include "cereal/gen/cpp/log.capnp.h" +#include "cereal/gen/cpp/car.capnp.h" +#include "params_learner.h" + +// #define DEBUG + +template +T clip(const T& n, const T& lower, const T& upper) { + return std::max(lower, std::min(n, upper)); +} + +ParamsLearner::ParamsLearner(cereal::CarParams::Reader car_params, + double angle_offset, + double stiffness_factor, + double steer_ratio, + double learning_rate) : + ao(angle_offset * DEGREES_TO_RADIANS), + slow_ao(angle_offset * DEGREES_TO_RADIANS), + x(stiffness_factor), + sR(steer_ratio) { + cF0 = car_params.getTireStiffnessFront(); + cR0 = car_params.getTireStiffnessRear(); + + l = car_params.getWheelbase(); + m = car_params.getMass(); + + aF = car_params.getCenterToFront(); + aR = l - aF; + + min_sr = MIN_SR * car_params.getSteerRatio(); + max_sr = MAX_SR * car_params.getSteerRatio(); + min_sr_th = MIN_SR_TH * car_params.getSteerRatio(); + max_sr_th = MAX_SR_TH * car_params.getSteerRatio(); + alpha1 = 0.01 * learning_rate; + alpha2 = 0.0005 * learning_rate; + alpha3 = 0.1 * learning_rate; + alpha4 = 1.0 * learning_rate; +} + +bool ParamsLearner::update(double psi, double u, double sa) { + if (u > 10.0 && fabs(sa) < (DEGREES_TO_RADIANS * 15.)) { + double ao_diff = 2.0*cF0*cR0*l*u*x*(1.0*cF0*cR0*l*u*x*(ao - sa) + psi*sR*(cF0*cR0*pow(l, 2)*x - m*pow(u, 2)*(aF*cF0 - aR*cR0)))/(pow(sR, 2)*pow(cF0*cR0*pow(l, 2)*x - m*pow(u, 2)*(aF*cF0 - aR*cR0), 2)); + double new_ao = ao - alpha1 * ao_diff; + + double slow_ao_diff = 2.0*cF0*cR0*l*u*x*(1.0*cF0*cR0*l*u*x*(slow_ao - sa) + psi*sR*(cF0*cR0*pow(l, 2)*x - m*pow(u, 2)*(aF*cF0 - aR*cR0)))/(pow(sR, 2)*pow(cF0*cR0*pow(l, 2)*x - m*pow(u, 2)*(aF*cF0 - aR*cR0), 2)); + double new_slow_ao = slow_ao - alpha2 * slow_ao_diff; + + double new_x = x - alpha3 * (-2.0*cF0*cR0*l*m*pow(u, 3)*(slow_ao - sa)*(aF*cF0 - aR*cR0)*(1.0*cF0*cR0*l*u*x*(slow_ao - sa) + psi*sR*(cF0*cR0*pow(l, 2)*x - m*pow(u, 2)*(aF*cF0 - aR*cR0)))/(pow(sR, 2)*pow(cF0*cR0*pow(l, 2)*x - m*pow(u, 2)*(aF*cF0 - aR*cR0), 3))); + double new_sR = sR - alpha4 * (-2.0*cF0*cR0*l*u*x*(slow_ao - sa)*(1.0*cF0*cR0*l*u*x*(slow_ao - sa) + psi*sR*(cF0*cR0*pow(l, 2)*x - m*pow(u, 2)*(aF*cF0 - aR*cR0)))/(pow(sR, 3)*pow(cF0*cR0*pow(l, 2)*x - m*pow(u, 2)*(aF*cF0 - aR*cR0), 2))); + + ao = new_ao; + slow_ao = new_slow_ao; + x = new_x; + sR = new_sR; + } + +#ifdef DEBUG + std::cout << "Instant AO: " << (RADIANS_TO_DEGREES * ao) << "\tAverage AO: " << (RADIANS_TO_DEGREES * slow_ao); + std::cout << "\tStiffness: " << x << "\t sR: " << sR << std::endl; +#endif + + ao = clip(ao, -MAX_ANGLE_OFFSET, MAX_ANGLE_OFFSET); + slow_ao = clip(slow_ao, -MAX_ANGLE_OFFSET, MAX_ANGLE_OFFSET); + x = clip(x, MIN_STIFFNESS, MAX_STIFFNESS); + sR = clip(sR, min_sr, max_sr); + + bool valid = fabs(slow_ao) < MAX_ANGLE_OFFSET_TH; + valid = valid && sR > min_sr_th; + valid = valid && sR < max_sr_th; + return valid; +} diff --git a/selfdrive/locationd/params_learner.h b/selfdrive/locationd/params_learner.h new file mode 100644 index 0000000000..4d97551b3b --- /dev/null +++ b/selfdrive/locationd/params_learner.h @@ -0,0 +1,35 @@ +#pragma once + +#define DEGREES_TO_RADIANS 0.017453292519943295 +#define RADIANS_TO_DEGREES (1.0 / DEGREES_TO_RADIANS) + +#define MAX_ANGLE_OFFSET (10.0 * DEGREES_TO_RADIANS) +#define MAX_ANGLE_OFFSET_TH (9.0 * DEGREES_TO_RADIANS) +#define MIN_STIFFNESS 0.5 +#define MAX_STIFFNESS 2.0 +#define MIN_SR 0.5 +#define MAX_SR 2.0 +#define MIN_SR_TH 0.55 +#define MAX_SR_TH 1.9 + +class ParamsLearner { + double cF0, cR0; + double aR, aF; + double l, m; + + double min_sr, max_sr, min_sr_th, max_sr_th; + double alpha1, alpha2, alpha3, alpha4; + +public: + double ao; + double slow_ao; + double x, sR; + + ParamsLearner(cereal::CarParams::Reader car_params, + double angle_offset, + double stiffness_factor, + double steer_ratio, + double learning_rate); + + bool update(double psi, double u, double sa); +}; diff --git a/selfdrive/locationd/test/ublox.py b/selfdrive/locationd/test/ublox.py index 945b05a122..175316fd81 100644 --- a/selfdrive/locationd/test/ublox.py +++ b/selfdrive/locationd/test/ublox.py @@ -719,14 +719,12 @@ class UBlox: self.dev = PandaSerial(self.panda, 1, self.baudrate) elif grey: - import zmq from selfdrive.services import service_list import selfdrive.messaging as messaging class BoarddSerial(object): def __init__(self): - context = zmq.Context() - self.ubloxRaw = messaging.sub_sock(context, service_list['ubloxRaw'].port) + self.ubloxRaw = messaging.sub_sock(service_list['ubloxRaw'].port) self.buf = "" def read(self, n): diff --git a/selfdrive/locationd/test/ubloxd.py b/selfdrive/locationd/test/ubloxd.py index 001d541360..388a69bf42 100755 --- a/selfdrive/locationd/test/ubloxd.py +++ b/selfdrive/locationd/test/ubloxd.py @@ -8,7 +8,6 @@ import struct import sys from cereal import log from common import realtime -import zmq import selfdrive.messaging as messaging from selfdrive.services import service_list from selfdrive.locationd.test.ephemeris import EphemerisData, GET_FIELD_U @@ -270,9 +269,8 @@ def main(gctx=None): nav_frame_buffer[0][i] = {} - context = zmq.Context() - gpsLocationExternal = messaging.pub_sock(context, service_list['gpsLocationExternal'].port) - ubloxGnss = messaging.pub_sock(context, service_list['ubloxGnss'].port) + gpsLocationExternal = messaging.pub_sock(service_list['gpsLocationExternal'].port) + ubloxGnss = messaging.pub_sock(service_list['ubloxGnss'].port) dev = init_reader() while True: diff --git a/selfdrive/locationd/test/ubloxd_easy.py b/selfdrive/locationd/test/ubloxd_easy.py index 96139ab61f..8bb16d403a 100755 --- a/selfdrive/locationd/test/ubloxd_easy.py +++ b/selfdrive/locationd/test/ubloxd_easy.py @@ -11,14 +11,12 @@ from selfdrive.services import service_list unlogger = os.getenv("UNLOGGER") is not None # debug prints def main(gctx=None): - context = zmq.Context() poller = zmq.Poller() - context = zmq.Context() - gpsLocationExternal = messaging.pub_sock(context, service_list['gpsLocationExternal'].port) - ubloxGnss = messaging.pub_sock(context, service_list['ubloxGnss'].port) + gpsLocationExternal = messaging.pub_sock(service_list['gpsLocationExternal'].port) + ubloxGnss = messaging.pub_sock(service_list['ubloxGnss'].port) - # ubloxRaw = messaging.sub_sock(context, service_list['ubloxRaw'].port, poller) + # ubloxRaw = messaging.sub_sock(service_list['ubloxRaw'].port, poller) # buffer with all the messages that still need to be input into the kalman while 1: diff --git a/selfdrive/logcatd/Makefile b/selfdrive/logcatd/Makefile index 077f20f8cd..fff9220dd3 100644 --- a/selfdrive/logcatd/Makefile +++ b/selfdrive/logcatd/Makefile @@ -1,6 +1,8 @@ CC = clang CXX = clang++ +ARCH := $(shell uname -m) + PHONELIBS = ../../phonelibs BASEDIR = ../.. @@ -12,11 +14,14 @@ WARN_FLAGS = -Werror=implicit-function-declaration \ CFLAGS = -std=gnu11 -g -fPIC -O2 $(WARN_FLAGS) CXXFLAGS = -std=c++11 -g -fPIC -O2 $(WARN_FLAGS) +ZMQ_LIBS = -l:libczmq.a -l:libzmq.a + +ifeq ($(ARCH),aarch64) +CFLAGS += -mcpu=cortex-a57 +CXXFLAGS += -mcpu=cortex-a57 +ZMQ_LIBS += -lgnustl_shared +endif -ZMQ_FLAGS = -I$(PHONELIBS)/zmq/aarch64/include -ZMQ_LIBS = -L$(PHONELIBS)/zmq/aarch64/lib \ - -l:libczmq.a -l:libzmq.a \ - -lgnustl_shared .PHONY: all all: logcatd diff --git a/selfdrive/logcatd/logcatd.cc b/selfdrive/logcatd/logcatd.cc index c2f688fd59..637c5e6c0a 100644 --- a/selfdrive/logcatd/logcatd.cc +++ b/selfdrive/logcatd/logcatd.cc @@ -1,8 +1,9 @@ #include #include #include +#include -#include +//#include #include #include @@ -24,8 +25,8 @@ int main() { assert(system_logger); struct logger *crash_logger = android_logger_open(logger_list, LOG_ID_CRASH); assert(crash_logger); - struct logger *kernel_logger = android_logger_open(logger_list, LOG_ID_KERNEL); - assert(kernel_logger); +// struct logger *kernel_logger = android_logger_open(logger_list, LOG_ID_KERNEL); +// assert(kernel_logger); void *context = zmq_ctx_new(); void *publisher = zmq_socket(context, ZMQ_PUB); @@ -65,4 +66,4 @@ int main() { android_logger_list_close(logger_list); return 0; -} \ No newline at end of file +} diff --git a/selfdrive/loggerd/build_from_src.mk b/selfdrive/loggerd/build_from_src.mk new file mode 100644 index 0000000000..47f4f9b265 --- /dev/null +++ b/selfdrive/loggerd/build_from_src.mk @@ -0,0 +1,132 @@ +CC = clang +CXX = clang++ + +ARCH := $(shell uname -m) + +PHONELIBS = ../../phonelibs +BASEDIR = ../.. + +WARN_FLAGS = -Werror=implicit-function-declaration \ + -Werror=incompatible-pointer-types \ + -Werror=int-conversion \ + -Werror=return-type \ + -Werror=format-extra-args \ + -Wno-deprecated-declarations + +CFLAGS = -std=gnu11 -g -fPIC -O2 $(WARN_FLAGS) \ + -I$(PHONELIBS)/android_frameworks_native/include \ + -I$(PHONELIBS)/android_system_core/include \ + -I$(PHONELIBS)/android_hardware_libhardware/include +CXXFLAGS = -std=c++11 -g -fPIC -O2 $(WARN_FLAGS) \ + -I$(PHONELIBS)/android_frameworks_native/include \ + -I$(PHONELIBS)/android_system_core/include \ + -I$(PHONELIBS)/android_hardware_libhardware/include + +ZMQ_LIBS = -l:libczmq.a -l:libzmq.a + +ifeq ($(ARCH),aarch64) +CFLAGS += -mcpu=cortex-a57 +CXXFLAGS += -mcpu=cortex-a57 +ZMQ_LIBS += -lgnustl_shared +endif + + +BZIP_FLAGS = -I$(PHONELIBS)/bzip2/ +BZIP_LIBS = -L$(PHONELIBS)/bzip2/ \ + -l:libbz2.a + +# todo: dont use system ffmpeg libs +FFMPEG_LIBS = -lavformat \ + -lavcodec \ + -lswscale \ + -lavutil \ + -lz + +LIBYUV_FLAGS = -I$(PHONELIBS)/libyuv/include +LIBYUV_LIBS = $(PHONELIBS)/libyuv/lib/libyuv.a + +OPENMAX_FLAGS = -I$(PHONELIBS)/openmax/include +OPENMAX_LIBS = -lOmxVenc -lOmxCore + +JSON_FLAGS = -I$(PHONELIBS)/json/src + +YAML_FLAGS = -I$(PHONELIBS)/yaml-cpp/include +YAML_LIBS = $(PHONELIBS)/yaml-cpp/lib/libyaml-cpp.a + +.PHONY: all +all: loggerd + +include ../common/cereal.mk + +OBJS += loggerd.o \ + logger.o \ + ../common/util.o \ + ../common/params.o \ + ../common/cqueue.o \ + ../common/swaglog.o \ + ../common/visionipc.o \ + ../common/ipc.o \ + $(PHONELIBS)/json/src/json.o + +ifeq ($(ARCH),x86_64) +CXXFLAGS += "-DDISABLE_ENCODER" +ZMQ_LIBS = -L$(BASEDIR)/external/zmq/lib/ \ + -l:libczmq.a -l:libzmq.a +EXTRA_LIBS = -lpthread +OPENMAX_LIBS = "" +YAML_LIBS = $(PHONELIBS)/yaml-cpp/x64/lib/libyaml-cpp.a +else +OBJS += encoder.o \ + raw_logger.o +EXTRA_LIBS = -lcutils -llog +endif + +DEPS := $(OBJS:.o=.d) + +loggerd: $(OBJS) + @echo "[ LINK ] $@" + $(CXX) -fPIC -o '$@' $^ \ + $(LIBYUV_LIBS) \ + $(CEREAL_LIBS) \ + $(ZMQ_LIBS) \ + -L/usr/lib \ + $(FFMPEG_LIBS) \ + -L/system/vendor/lib64 \ + $(OPENMAX_LIBS) \ + $(YAML_LIBS) \ + $(EXTRA_LIBS) \ + $(BZIP_LIBS) \ + -lm + +%.o: %.cc + @echo "[ CXX ] $@" + $(CXX) $(CXXFLAGS) -MMD \ + $(CEREAL_CXXFLAGS) \ + $(LIBYUV_FLAGS) \ + $(ZMQ_FLAGS) \ + $(OPENMAX_FLAGS) \ + $(YAML_FLAGS) \ + $(BZIP_FLAGS) \ + -Iinclude \ + -I../ \ + -I../../ \ + -c -o '$@' '$<' + +%.o: %.c + @echo "[ CC ] $@" + $(CC) $(CFLAGS) -MMD \ + $(LIBYUV_FLAGS) \ + $(ZMQ_FLAGS) \ + $(OPENMAX_FLAGS) \ + $(JSON_FLAGS) \ + $(BZIP_FLAGS) \ + -Iinclude \ + -I../ \ + -I../../ \ + -c -o '$@' '$<' + +.PHONY: clean +clean: + rm -f loggerd $(OBJS) $(DEPS) + +-include $(DEPS) diff --git a/selfdrive/loggerd/deleter.py b/selfdrive/loggerd/deleter.py index 86974a00c5..b1e1ffcd04 100644 --- a/selfdrive/loggerd/deleter.py +++ b/selfdrive/loggerd/deleter.py @@ -26,8 +26,9 @@ def deleter_thread(exit_event): break except OSError: cloudlog.exception("issue deleting %s" % delete_path) - - exit_event.wait(30) + exit_event.wait(.1) + else: + exit_event.wait(30) def main(gctx=None): diff --git a/selfdrive/loggerd/encoder.c b/selfdrive/loggerd/encoder.c new file mode 100644 index 0000000000..1b85ad263d --- /dev/null +++ b/selfdrive/loggerd/encoder.c @@ -0,0 +1,714 @@ +#include +#include +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include + +#include + +#include + +#include + +#include "common/mutex.h" +#include "common/swaglog.h" + +#include "encoder.h" + +#define ALOG(...) __android_log_print(ANDROID_LOG_VERBOSE, "omxapp", ##__VA_ARGS__) + +// encoder: lossey codec using hardware hevc + +static void wait_for_state(EncoderState *s, OMX_STATETYPE state) { + pthread_mutex_lock(&s->state_lock); + while (s->state != state) { + pthread_cond_wait(&s->state_cv, &s->state_lock); + } + pthread_mutex_unlock(&s->state_lock); +} + +static OMX_ERRORTYPE event_handler(OMX_HANDLETYPE component, OMX_PTR app_data, OMX_EVENTTYPE event, + OMX_U32 data1, OMX_U32 data2, OMX_PTR event_data) { + EncoderState *s = app_data; + + switch (event) { + case OMX_EventCmdComplete: + assert(data1 == OMX_CommandStateSet); + LOG("set state event 0x%x", data2); + pthread_mutex_lock(&s->state_lock); + s->state = data2; + pthread_cond_broadcast(&s->state_cv); + pthread_mutex_unlock(&s->state_lock); + break; + case OMX_EventError: + LOGE("OMX error 0x%08x", data1); + // assert(false); + break; + default: + LOGE("unhandled event %d", event); + assert(false); + break; + } + + pthread_mutex_unlock(&s->state_lock); + + return OMX_ErrorNone; +} + +static OMX_ERRORTYPE empty_buffer_done(OMX_HANDLETYPE component, OMX_PTR app_data, + OMX_BUFFERHEADERTYPE *buffer) { + EncoderState *s = app_data; + + // printf("empty_buffer_done\n"); + + queue_push(&s->free_in, (void*)buffer); + + return OMX_ErrorNone; +} + + +static OMX_ERRORTYPE fill_buffer_done(OMX_HANDLETYPE component, OMX_PTR app_data, + OMX_BUFFERHEADERTYPE *buffer) { + EncoderState *s = app_data; + + // printf("fill_buffer_done\n"); + + queue_push(&s->done_out, (void*)buffer); + + return OMX_ErrorNone; +} + +static OMX_CALLBACKTYPE omx_callbacks = { + .EventHandler = event_handler, + .EmptyBufferDone = empty_buffer_done, + .FillBufferDone = fill_buffer_done, +}; + +#define PORT_INDEX_IN 0 +#define PORT_INDEX_OUT 1 + +static const char* omx_color_fomat_name(uint32_t format) { + switch (format) { + case OMX_COLOR_FormatUnused: return "OMX_COLOR_FormatUnused"; + case OMX_COLOR_FormatMonochrome: return "OMX_COLOR_FormatMonochrome"; + case OMX_COLOR_Format8bitRGB332: return "OMX_COLOR_Format8bitRGB332"; + case OMX_COLOR_Format12bitRGB444: return "OMX_COLOR_Format12bitRGB444"; + case OMX_COLOR_Format16bitARGB4444: return "OMX_COLOR_Format16bitARGB4444"; + case OMX_COLOR_Format16bitARGB1555: return "OMX_COLOR_Format16bitARGB1555"; + case OMX_COLOR_Format16bitRGB565: return "OMX_COLOR_Format16bitRGB565"; + case OMX_COLOR_Format16bitBGR565: return "OMX_COLOR_Format16bitBGR565"; + case OMX_COLOR_Format18bitRGB666: return "OMX_COLOR_Format18bitRGB666"; + case OMX_COLOR_Format18bitARGB1665: return "OMX_COLOR_Format18bitARGB1665"; + case OMX_COLOR_Format19bitARGB1666: return "OMX_COLOR_Format19bitARGB1666"; + case OMX_COLOR_Format24bitRGB888: return "OMX_COLOR_Format24bitRGB888"; + case OMX_COLOR_Format24bitBGR888: return "OMX_COLOR_Format24bitBGR888"; + case OMX_COLOR_Format24bitARGB1887: return "OMX_COLOR_Format24bitARGB1887"; + case OMX_COLOR_Format25bitARGB1888: return "OMX_COLOR_Format25bitARGB1888"; + case OMX_COLOR_Format32bitBGRA8888: return "OMX_COLOR_Format32bitBGRA8888"; + case OMX_COLOR_Format32bitARGB8888: return "OMX_COLOR_Format32bitARGB8888"; + case OMX_COLOR_FormatYUV411Planar: return "OMX_COLOR_FormatYUV411Planar"; + case OMX_COLOR_FormatYUV411PackedPlanar: return "OMX_COLOR_FormatYUV411PackedPlanar"; + case OMX_COLOR_FormatYUV420Planar: return "OMX_COLOR_FormatYUV420Planar"; + case OMX_COLOR_FormatYUV420PackedPlanar: return "OMX_COLOR_FormatYUV420PackedPlanar"; + case OMX_COLOR_FormatYUV420SemiPlanar: return "OMX_COLOR_FormatYUV420SemiPlanar"; + case OMX_COLOR_FormatYUV422Planar: return "OMX_COLOR_FormatYUV422Planar"; + case OMX_COLOR_FormatYUV422PackedPlanar: return "OMX_COLOR_FormatYUV422PackedPlanar"; + case OMX_COLOR_FormatYUV422SemiPlanar: return "OMX_COLOR_FormatYUV422SemiPlanar"; + case OMX_COLOR_FormatYCbYCr: return "OMX_COLOR_FormatYCbYCr"; + case OMX_COLOR_FormatYCrYCb: return "OMX_COLOR_FormatYCrYCb"; + case OMX_COLOR_FormatCbYCrY: return "OMX_COLOR_FormatCbYCrY"; + case OMX_COLOR_FormatCrYCbY: return "OMX_COLOR_FormatCrYCbY"; + case OMX_COLOR_FormatYUV444Interleaved: return "OMX_COLOR_FormatYUV444Interleaved"; + case OMX_COLOR_FormatRawBayer8bit: return "OMX_COLOR_FormatRawBayer8bit"; + case OMX_COLOR_FormatRawBayer10bit: return "OMX_COLOR_FormatRawBayer10bit"; + case OMX_COLOR_FormatRawBayer8bitcompressed: return "OMX_COLOR_FormatRawBayer8bitcompressed"; + case OMX_COLOR_FormatL2: return "OMX_COLOR_FormatL2"; + case OMX_COLOR_FormatL4: return "OMX_COLOR_FormatL4"; + case OMX_COLOR_FormatL8: return "OMX_COLOR_FormatL8"; + case OMX_COLOR_FormatL16: return "OMX_COLOR_FormatL16"; + case OMX_COLOR_FormatL24: return "OMX_COLOR_FormatL24"; + case OMX_COLOR_FormatL32: return "OMX_COLOR_FormatL32"; + case OMX_COLOR_FormatYUV420PackedSemiPlanar: return "OMX_COLOR_FormatYUV420PackedSemiPlanar"; + case OMX_COLOR_FormatYUV422PackedSemiPlanar: return "OMX_COLOR_FormatYUV422PackedSemiPlanar"; + case OMX_COLOR_Format18BitBGR666: return "OMX_COLOR_Format18BitBGR666"; + case OMX_COLOR_Format24BitARGB6666: return "OMX_COLOR_Format24BitARGB6666"; + case OMX_COLOR_Format24BitABGR6666: return "OMX_COLOR_Format24BitABGR6666"; + + case OMX_COLOR_FormatAndroidOpaque: return "OMX_COLOR_FormatAndroidOpaque"; + case OMX_TI_COLOR_FormatYUV420PackedSemiPlanar: return "OMX_TI_COLOR_FormatYUV420PackedSemiPlanar"; + case OMX_QCOM_COLOR_FormatYVU420SemiPlanar: return "OMX_QCOM_COLOR_FormatYVU420SemiPlanar"; + case OMX_QCOM_COLOR_FormatYUV420PackedSemiPlanar64x32Tile2m8ka: return "OMX_QCOM_COLOR_FormatYUV420PackedSemiPlanar64x32Tile2m8ka"; + case OMX_SEC_COLOR_FormatNV12Tiled: return "OMX_SEC_COLOR_FormatNV12Tiled"; + case OMX_QCOM_COLOR_FormatYUV420PackedSemiPlanar32m: return "OMX_QCOM_COLOR_FormatYUV420PackedSemiPlanar32m"; + + // case QOMX_COLOR_FormatYVU420SemiPlanar: return "QOMX_COLOR_FormatYVU420SemiPlanar"; + case QOMX_COLOR_FormatYVU420PackedSemiPlanar32m4ka: return "QOMX_COLOR_FormatYVU420PackedSemiPlanar32m4ka"; + case QOMX_COLOR_FormatYUV420PackedSemiPlanar16m2ka: return "QOMX_COLOR_FormatYUV420PackedSemiPlanar16m2ka"; + // case QOMX_COLOR_FormatYUV420PackedSemiPlanar64x32Tile2m8ka: return "QOMX_COLOR_FormatYUV420PackedSemiPlanar64x32Tile2m8ka"; + // case QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m: return "QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m"; + case QOMX_COLOR_FORMATYUV420PackedSemiPlanar32mMultiView: return "QOMX_COLOR_FORMATYUV420PackedSemiPlanar32mMultiView"; + case QOMX_COLOR_FORMATYUV420PackedSemiPlanar32mCompressed: return "QOMX_COLOR_FORMATYUV420PackedSemiPlanar32mCompressed"; + case QOMX_COLOR_Format32bitRGBA8888: return "QOMX_COLOR_Format32bitRGBA8888"; + case QOMX_COLOR_Format32bitRGBA8888Compressed: return "QOMX_COLOR_Format32bitRGBA8888Compressed"; + + default: + return "unkn"; + } +} + + +void encoder_init(EncoderState *s, const char* filename, int width, int height, int fps, int bitrate) { + int err; + + memset(s, 0, sizeof(*s)); + s->filename = filename; + s->width = width; + s->height = height; + s->fps = fps; + mutex_init_reentrant(&s->lock); + + s->segment = -1; + + s->state = OMX_StateLoaded; + + s->codec_config = NULL; + + queue_init(&s->free_in); + queue_init(&s->done_out); + + pthread_mutex_init(&s->state_lock, NULL); + pthread_cond_init(&s->state_cv, NULL); + + err = OMX_GetHandle(&s->handle, (OMX_STRING)"OMX.qcom.video.encoder.hevc", + s, &omx_callbacks); + // err = OMX_GetHandle(&s->handle, (OMX_STRING)"OMX.qcom.video.encoder.avc", + // s, &omx_callbacks); + assert(err == OMX_ErrorNone); + // printf("handle: %p\n", s->handle); + + // setup input port + + OMX_PARAM_PORTDEFINITIONTYPE in_port = {0}; + in_port.nSize = sizeof(in_port); + in_port.nPortIndex = (OMX_U32) PORT_INDEX_IN; + err = OMX_GetParameter(s->handle, OMX_IndexParamPortDefinition, + (OMX_PTR) &in_port); + assert(err == OMX_ErrorNone); + + + in_port.format.video.nFrameWidth = s->width; + in_port.format.video.nFrameHeight = s->height; + in_port.format.video.nStride = VENUS_Y_STRIDE(COLOR_FMT_NV12, s->width); + in_port.format.video.nSliceHeight = s->height; + // in_port.nBufferSize = (s->width * s->height * 3) / 2; + in_port.nBufferSize = VENUS_BUFFER_SIZE(COLOR_FMT_NV12, s->width, s->height); + in_port.format.video.xFramerate = (s->fps * 65536); + in_port.format.video.eCompressionFormat = OMX_VIDEO_CodingUnused; + // in_port.format.video.eColorFormat = OMX_COLOR_FormatYUV420SemiPlanar; + in_port.format.video.eColorFormat = QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m; + + err = OMX_SetParameter(s->handle, OMX_IndexParamPortDefinition, + (OMX_PTR) &in_port); + assert(err == OMX_ErrorNone); + + + err = OMX_GetParameter(s->handle, OMX_IndexParamPortDefinition, + (OMX_PTR) &in_port); + assert(err == OMX_ErrorNone); + s->num_in_bufs = in_port.nBufferCountActual; + + // printf("in width: %d, stride: %d\n", + // in_port.format.video.nFrameWidth, in_port.format.video.nStride); + + // setup output port + + OMX_PARAM_PORTDEFINITIONTYPE out_port = {0}; + out_port.nSize = sizeof(out_port); + out_port.nPortIndex = (OMX_U32) PORT_INDEX_OUT; + err = OMX_GetParameter(s->handle, OMX_IndexParamPortDefinition, + (OMX_PTR)&out_port); + assert(err == OMX_ErrorNone); + + out_port.format.video.nFrameWidth = s->width; + out_port.format.video.nFrameHeight = s->height; + out_port.format.video.xFramerate = 0; + out_port.format.video.nBitrate = bitrate; + out_port.format.video.eCompressionFormat = OMX_VIDEO_CodingHEVC; + // out_port.format.video.eCompressionFormat = OMX_VIDEO_CodingAVC; + out_port.format.video.eColorFormat = OMX_COLOR_FormatUnused; + + err = OMX_SetParameter(s->handle, OMX_IndexParamPortDefinition, + (OMX_PTR) &out_port); + assert(err == OMX_ErrorNone); + + + err = OMX_GetParameter(s->handle, OMX_IndexParamPortDefinition, + (OMX_PTR) &out_port); + assert(err == OMX_ErrorNone); + s->num_out_bufs = out_port.nBufferCountActual; + + // printf("out buf num %d\n", out_port.nBufferSize); + + + // setup HEVC + + OMX_VIDEO_PARAM_HEVCTYPE hecv_type = {0}; + hecv_type.nSize = sizeof(hecv_type); + hecv_type.nPortIndex = (OMX_U32) PORT_INDEX_OUT; + err = OMX_GetParameter(s->handle, (OMX_INDEXTYPE)OMX_IndexParamVideoHevc, + (OMX_PTR) &hecv_type); + assert(err == OMX_ErrorNone); + + hecv_type.eProfile = OMX_VIDEO_HEVCProfileMain; + hecv_type.eLevel = OMX_VIDEO_HEVCHighTierLevel5; + + err = OMX_SetParameter(s->handle, (OMX_INDEXTYPE)OMX_IndexParamVideoHevc, + (OMX_PTR) &hecv_type); + assert(err == OMX_ErrorNone); + + + OMX_VIDEO_PARAM_BITRATETYPE bitrate_type = {0}; + bitrate_type.nSize = sizeof(bitrate_type); + bitrate_type.nPortIndex = (OMX_U32) PORT_INDEX_OUT; + err = OMX_GetParameter(s->handle, OMX_IndexParamVideoBitrate, + (OMX_PTR) &bitrate_type); + assert(err == OMX_ErrorNone); + + bitrate_type.eControlRate = OMX_Video_ControlRateVariable; + bitrate_type.nTargetBitrate = bitrate; + + err = OMX_SetParameter(s->handle, OMX_IndexParamVideoBitrate, + (OMX_PTR) &bitrate_type); + assert(err == OMX_ErrorNone); + + +#if 0 + // setup h264 + OMX_VIDEO_PARAM_BITRATETYPE bitrate_type = {0}; + bitrate_type.nSize = sizeof(bitrate_type); + bitrate_type.nPortIndex = (OMX_U32) PORT_INDEX_OUT; + err = OMX_GetParameter(s->handle, OMX_IndexParamVideoBitrate, + (OMX_PTR) &bitrate_type); + assert(err == OMX_ErrorNone); + + bitrate_type.eControlRate = OMX_Video_ControlRateVariable; + bitrate_type.nTargetBitrate = 2000000; + + err = OMX_SetParameter(s->handle, OMX_IndexParamVideoBitrate, + (OMX_PTR) &bitrate_type); + assert(err == OMX_ErrorNone); + + + OMX_VIDEO_PARAM_AVCTYPE avc = { 0 }; + avc.nSize = sizeof(avc); + avc.nPortIndex = (OMX_U32) PORT_INDEX_OUT; + err = OMX_GetParameter(s->handle, OMX_IndexParamVideoAvc, &avc); + assert(err == OMX_ErrorNone); + + avc.nBFrames = 0; + avc.nPFrames = 20;//avctx->gop_size - 1; + + avc.eProfile = OMX_VIDEO_AVCProfileBaseline; + avc.eLevel = OMX_VIDEO_AVCLevel31; + + avc.nAllowedPictureTypes |= OMX_VIDEO_PictureTypeB; + avc.eLoopFilterMode = OMX_VIDEO_AVCLoopFilterEnable; + + err = OMX_SetParameter(s->handle, OMX_IndexParamVideoAvc, &avc); + assert(err == OMX_ErrorNone); +#endif + + + // for (int i = 0; ; i++) { + // OMX_VIDEO_PARAM_PORTFORMATTYPE video_port_format = {0}; + // video_port_format.nSize = sizeof(video_port_format); + // video_port_format.nIndex = i; + // video_port_format.nPortIndex = PORT_INDEX_IN; + // if (OMX_GetParameter(s->handle, OMX_IndexParamVideoPortFormat, &video_port_format) != OMX_ErrorNone) + // break; + // printf("in %d: compression 0x%x format 0x%x %s\n", i, + // video_port_format.eCompressionFormat, video_port_format.eColorFormat, + // omx_color_fomat_name(video_port_format.eColorFormat)); + // } + + // for (int i=0; i<32; i++) { + // OMX_VIDEO_PARAM_PROFILELEVELTYPE params = {0}; + // params.nSize = sizeof(params); + // params.nPortIndex = PORT_INDEX_OUT; + // params.nProfileIndex = i; + // if (OMX_GetParameter(s->handle, OMX_IndexParamVideoProfileLevelQuerySupported, ¶ms) != OMX_ErrorNone) + // break; + // printf("profile %d level 0x%x\n", params.eProfile, params.eLevel); + // } + + err = OMX_SendCommand(s->handle, OMX_CommandStateSet, OMX_StateIdle, NULL); + assert(err == OMX_ErrorNone); + + s->in_buf_headers = calloc(s->num_in_bufs, sizeof(OMX_BUFFERHEADERTYPE*)); + for (int i=0; inum_in_bufs; i++) { + err = OMX_AllocateBuffer(s->handle, &s->in_buf_headers[i], PORT_INDEX_IN, s, + in_port.nBufferSize); + assert(err == OMX_ErrorNone); + } + + s->out_buf_headers = calloc(s->num_out_bufs, sizeof(OMX_BUFFERHEADERTYPE*)); + for (int i=0; inum_out_bufs; i++) { + err = OMX_AllocateBuffer(s->handle, &s->out_buf_headers[i], PORT_INDEX_OUT, s, + out_port.nBufferSize); + assert(err == OMX_ErrorNone); + } + + wait_for_state(s, OMX_StateIdle); + + err = OMX_SendCommand(s->handle, OMX_CommandStateSet, OMX_StateExecuting, NULL); + assert(err == OMX_ErrorNone); + + wait_for_state(s, OMX_StateExecuting); + + // give omx all the output buffers + for (int i = 0; i < s->num_out_bufs; i++) { + // printf("fill %p\n", s->out_buf_headers[i]); + err = OMX_FillThisBuffer(s->handle, s->out_buf_headers[i]); + assert(err == OMX_ErrorNone); + } + + // fill the input free queue + for (int i = 0; i < s->num_in_bufs; i++) { + queue_push(&s->free_in, (void*)s->in_buf_headers[i]); + } +} + +static void handle_out_buf(EncoderState *s, OMX_BUFFERHEADERTYPE *out_buf) { + int err; + + uint8_t *buf_data = out_buf->pBuffer + out_buf->nOffset; + + if (out_buf->nFlags & OMX_BUFFERFLAG_CODECCONFIG) { + if (s->codec_config_len < out_buf->nFilledLen) { + s->codec_config = realloc(s->codec_config, out_buf->nFilledLen); + } + s->codec_config_len = out_buf->nFilledLen; + memcpy(s->codec_config, buf_data, out_buf->nFilledLen); + } + + if (s->stream_sock_raw) { + uint64_t current_time = nanos_since_boot(); + uint64_t diff = current_time - out_buf->nTimeStamp*1000LL; + double msdiff = (double) diff / 1000000.0; + // printf("encoded latency to tsEof: %f\n", msdiff); + zmq_send(s->stream_sock_raw, &out_buf->nTimeStamp, sizeof(out_buf->nTimeStamp), ZMQ_SNDMORE); + zmq_send(s->stream_sock_raw, buf_data, out_buf->nFilledLen, 0); + } + + if (s->of) { + // printf("write %d flags 0x%x\n", out_buf->nFilledLen, out_buf->nFlags); + fwrite(buf_data, out_buf->nFilledLen, 1, s->of); + } + + // give omx back the buffer + err = OMX_FillThisBuffer(s->handle, out_buf); + assert(err == OMX_ErrorNone); +} + +int encoder_encode_frame(EncoderState *s, uint64_t ts, + const uint8_t *y_ptr, const uint8_t *u_ptr, const uint8_t *v_ptr, + int *frame_segment, VIPCBufExtra *extra) { + int err; + + pthread_mutex_lock(&s->lock); + + if (s->opening) { + encoder_open(s, s->next_path); + s->opening = false; + } + + if (!s->open) { + pthread_mutex_unlock(&s->lock); + return -1; + } + + // this sometimes freezes... put it outside the encoder lock so we can still trigger rotates... + // THIS IS A REALLY BAD IDEA, but apparently the race has to happen 30 times to trigger this + pthread_mutex_unlock(&s->lock); + OMX_BUFFERHEADERTYPE* in_buf = queue_pop(&s->free_in); + pthread_mutex_lock(&s->lock); + + if (s->rotating) { + encoder_close(s); + encoder_open(s, s->next_path); + s->segment = s->next_segment; + s->rotating = false; + } + + int ret = s->counter; + + uint8_t *in_buf_ptr = in_buf->pBuffer; + // printf("in_buf ptr %p\n", in_buf_ptr); + + uint8_t *in_y_ptr = in_buf_ptr; + int in_y_stride = VENUS_Y_STRIDE(COLOR_FMT_NV12, s->width); + int in_uv_stride = VENUS_UV_STRIDE(COLOR_FMT_NV12, s->width); + // uint8_t *in_uv_ptr = in_buf_ptr + (s->width * s->height); + uint8_t *in_uv_ptr = in_buf_ptr + (in_y_stride * VENUS_Y_SCANLINES(COLOR_FMT_NV12, s->height)); + + err = I420ToNV12(y_ptr, s->width, + u_ptr, s->width/2, + v_ptr, s->width/2, + in_y_ptr, in_y_stride, + in_uv_ptr, in_uv_stride, + s->width, s->height); + assert(err == 0); + + // in_buf->nFilledLen = (s->width*s->height) + (s->width*s->height/2); + in_buf->nFilledLen = VENUS_BUFFER_SIZE(COLOR_FMT_NV12, s->width, s->height); + in_buf->nFlags = OMX_BUFFERFLAG_ENDOFFRAME; + in_buf->nOffset = 0; + in_buf->nTimeStamp = extra->timestamp_eof/1000LL; + + err = OMX_EmptyThisBuffer(s->handle, in_buf); + assert(err == OMX_ErrorNone); + + // pump output + while (true) { + OMX_BUFFERHEADERTYPE *out_buf = queue_try_pop(&s->done_out); + if (!out_buf) { + break; + } + handle_out_buf(s, out_buf); + } + + s->dirty = true; + + s->counter++; + + if (frame_segment) { + *frame_segment = s->segment; + } + + if (s->closing) { + encoder_close(s); + s->closing = false; + } + + pthread_mutex_unlock(&s->lock); + return ret; +} + +void encoder_open(EncoderState *s, const char* path) { + int err; + + pthread_mutex_lock(&s->lock); + + snprintf(s->vid_path, sizeof(s->vid_path), "%s/%s.hevc", path, s->filename); + s->of = fopen(s->vid_path, "wb"); + assert(s->of); + + if (s->codec_config_len > 0) { + fwrite(s->codec_config, s->codec_config_len, 1, s->of); + } + + // create camera lock file + snprintf(s->lock_path, sizeof(s->lock_path), "%s/%s.lock", path, s->filename); + int lock_fd = open(s->lock_path, O_RDWR | O_CREAT, 0777); + assert(lock_fd >= 0); + close(lock_fd); + + s->open = true; + s->counter = 0; + + pthread_mutex_unlock(&s->lock); +} + +void encoder_close(EncoderState *s) { + int err; + + pthread_mutex_lock(&s->lock); + + if (s->open) { + if (s->dirty) { + // drain output only if there could be frames in the encoder + + OMX_BUFFERHEADERTYPE* in_buf = queue_pop(&s->free_in); + in_buf->nFilledLen = 0; + in_buf->nOffset = 0; + in_buf->nFlags = OMX_BUFFERFLAG_EOS; + in_buf->nTimeStamp = 0; + + err = OMX_EmptyThisBuffer(s->handle, in_buf); + assert(err == OMX_ErrorNone); + + while (true) { + OMX_BUFFERHEADERTYPE *out_buf = queue_pop(&s->done_out); + + handle_out_buf(s, out_buf); + + if (out_buf->nFlags & OMX_BUFFERFLAG_EOS) { + break; + } + } + s->dirty = false; + } + + fclose(s->of); + unlink(s->lock_path); + } + s->open = false; + + pthread_mutex_unlock(&s->lock); +} + +void encoder_rotate(EncoderState *s, const char* new_path, int new_segment) { + pthread_mutex_lock(&s->lock); + snprintf(s->next_path, sizeof(s->next_path), "%s", new_path); + s->next_segment = new_segment; + if (s->open) { + if (s->next_segment == -1) { + s->closing = true; + } else { + s->rotating = true; + } + } else { + s->segment = s->next_segment; + s->opening = true; + } + pthread_mutex_unlock(&s->lock); +} + +void encoder_destroy(EncoderState *s) { + int err; + + assert(!s->open); + + err = OMX_SendCommand(s->handle, OMX_CommandStateSet, OMX_StateIdle, NULL); + assert(err == OMX_ErrorNone); + + wait_for_state(s, OMX_StateIdle); + + err = OMX_SendCommand(s->handle, OMX_CommandStateSet, OMX_StateLoaded, NULL); + assert(err == OMX_ErrorNone); + + for (int i=0; inum_in_bufs; i++) { + err = OMX_FreeBuffer(s->handle, PORT_INDEX_IN, s->in_buf_headers[i]); + assert(err == OMX_ErrorNone); + } + free(s->in_buf_headers); + + for (int i=0; inum_out_bufs; i++) { + err = OMX_FreeBuffer(s->handle, PORT_INDEX_OUT, s->out_buf_headers[i]); + assert(err == OMX_ErrorNone); + } + free(s->out_buf_headers); + + wait_for_state(s, OMX_StateLoaded); + + err = OMX_FreeHandle(s->handle); + assert(err == OMX_ErrorNone); +} + +#if 0 + +// cd one/selfdrive/visiond +// clang +// -fPIC -pie +// -std=gnu11 -O2 -g +// -o encoder +// -I ~/one/selfdrive +// -I ~/one/phonelibs/openmax/include +// -I ~/one/phonelibs/libyuv/include +// -lOmxVenc -lOmxCore -llog +// encoder.c +// buffering.c +// -L ~/one/phonelibs/libyuv/lib -l:libyuv.a + +int main() { + int err; + + EncoderState state; + EncoderState *s = &state; + memset(s, 0, sizeof(*s)); + + int w = 1164; + int h = 874; + + encoder_init(s, w, h, 20); + printf("inited\n"); + + encoder_open(s, "/sdcard/t1"); + + // uint8_t *tmpy = malloc(640*480); + // uint8_t *tmpu = malloc((640/2)*(480/2)); + // uint8_t *tmpv = malloc((640/2)*(480/2)); + + // memset(tmpy, 0, 640*480); + // // memset(tmpu, 0xff, (640/2)*(480/2)); + // memset(tmpv, 0, (640/2)*(480/2)); + +// #if 0 + // FILE *infile = fopen("/sdcard/camera_t2.yuv", "rb"); + uint8_t *inbuf = malloc(w*h*3/2); + memset(inbuf, 0, w*h*3/2); + + for (int i=0; i<20*3+5; i++) { + + // fread(inbuf, w*h*3/2, 1, infile); + + uint8_t *tmpy = inbuf; + uint8_t *tmpu = inbuf + w*h; + uint8_t *tmpv = inbuf + w*h + (w/2)*(h/2); + + for (int y=0; yof); + // s->of = fopen("/sdcard/tmpout2.hevc", "wb"); + // if (s->codec_config) { + // fwrite(s->codec_config, s->codec_config_len, 1, s->of); + // } + // encoder_open(s, "/sdcard/t1"); + + encoder_rotate(s, "/sdcard/t2"); + + for (int i=0; i<20*3+5; i++) { + + // fread(inbuf, w*h*3/2, 1, infile); + + uint8_t *tmpy = inbuf; + uint8_t *tmpu = inbuf + w*h; + uint8_t *tmpv = inbuf + w*h + (w/2)*(h/2); + + for (int y=0; y +#include +#include + +#include + +#include + +#include "common/cqueue.h" +#include "common/visionipc.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct EncoderState { + pthread_mutex_t lock; + int width, height, fps; + const char* path; + char vid_path[1024]; + char lock_path[1024]; + bool open; + bool dirty; + int counter; + int segment; + + bool rotating; + bool closing; + bool opening; + char next_path[1024]; + int next_segment; + + const char* filename; + FILE *of; + + size_t codec_config_len; + uint8_t *codec_config; + + pthread_mutex_t state_lock; + pthread_cond_t state_cv; + OMX_STATETYPE state; + + OMX_HANDLETYPE handle; + + int num_in_bufs; + OMX_BUFFERHEADERTYPE** in_buf_headers; + + int num_out_bufs; + OMX_BUFFERHEADERTYPE** out_buf_headers; + + Queue free_in; + Queue done_out; + + void *stream_sock_raw; +} EncoderState; + +void encoder_init(EncoderState *s, const char* filename, int width, int height, int fps, int bitrate); +int encoder_encode_frame(EncoderState *s, uint64_t ts, + const uint8_t *y_ptr, const uint8_t *u_ptr, const uint8_t *v_ptr, + int *frame_segment, VIPCBufExtra *extra); +void encoder_open(EncoderState *s, const char* path); +void encoder_rotate(EncoderState *s, const char* new_path, int new_segment); +void encoder_close(EncoderState *s); +void encoder_destroy(EncoderState *s); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/selfdrive/loggerd/frame_logger.h b/selfdrive/loggerd/frame_logger.h new file mode 100644 index 0000000000..bfc0681b75 --- /dev/null +++ b/selfdrive/loggerd/frame_logger.h @@ -0,0 +1,81 @@ +#ifndef FRAMELOGGER_H +#define FRAMELOGGER_H + +#include + +#include +#include + +class FrameLogger { +public: + virtual ~FrameLogger() {} + + virtual void Open(const std::string &path) = 0; + virtual void Close() = 0; + + int LogFrame(uint64_t ts, const uint8_t *y_ptr, const uint8_t *u_ptr, const uint8_t *v_ptr, int *frame_segment) { + std::lock_guard guard(lock); + + if (opening) { + Open(next_path); + opening = false; + } + + if (!is_open) return -1; + + if (rotating) { + Close(); + Open(next_path); + segment = next_segment; + rotating = false; + } + + int ret = ProcessFrame(ts, y_ptr, u_ptr, v_ptr); + + if (ret >= 0 && frame_segment) { + *frame_segment = segment; + } + + if (closing) { + Close(); + closing = false; + } + + return ret; + } + + void Rotate(const std::string &new_path, int new_segment) { + std::lock_guard guard(lock); + + next_path = new_path; + next_segment = new_segment; + if (is_open) { + if (next_segment == -1) { + closing = true; + } else { + rotating = true; + } + } else { + segment = next_segment; + opening = true; + } + } + +protected: + + virtual int ProcessFrame(uint64_t ts, const uint8_t *y_ptr, const uint8_t *u_ptr, const uint8_t *v_ptr) = 0; + + std::recursive_mutex lock; + + bool is_open = false; + int segment = -1; + + std::string vid_path, lock_path; + +private: + int next_segment = -1; + bool opening = false, closing = false, rotating = false; + std::string next_path; +}; + +#endif diff --git a/selfdrive/loggerd/include/msm_media_info.h b/selfdrive/loggerd/include/msm_media_info.h new file mode 100644 index 0000000000..39dceb2c49 --- /dev/null +++ b/selfdrive/loggerd/include/msm_media_info.h @@ -0,0 +1,819 @@ +#ifndef __MEDIA_INFO_H__ +#define __MEDIA_INFO_H__ + +#ifndef MSM_MEDIA_ALIGN +#define MSM_MEDIA_ALIGN(__sz, __align) (((__sz) + (__align-1)) & (~(__align-1))) +#endif + +#ifndef MSM_MEDIA_ROUNDUP +#define MSM_MEDIA_ROUNDUP(__sz, __r) (((__sz) + ((__r) - 1)) / (__r)) +#endif + +#ifndef MSM_MEDIA_MAX +#define MSM_MEDIA_MAX(__a, __b) ((__a) > (__b)?(__a):(__b)) +#endif + +enum color_fmts { + /* Venus NV12: + * YUV 4:2:0 image with a plane of 8 bit Y samples followed + * by an interleaved U/V plane containing 8 bit 2x2 subsampled + * colour difference samples. + * + * <-------- Y/UV_Stride --------> + * <------- Width -------> + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . ^ ^ + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . Height | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | Y_Scanlines + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . V | + * . . . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . . . V + * U V U V U V U V U V U V . . . . ^ + * U V U V U V U V U V U V . . . . | + * U V U V U V U V U V U V . . . . | + * U V U V U V U V U V U V . . . . UV_Scanlines + * . . . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . . . V + * . . . . . . . . . . . . . . . . --> Buffer size alignment + * + * Y_Stride : Width aligned to 128 + * UV_Stride : Width aligned to 128 + * Y_Scanlines: Height aligned to 32 + * UV_Scanlines: Height/2 aligned to 16 + * Extradata: Arbitrary (software-imposed) padding + * Total size = align((Y_Stride * Y_Scanlines + * + UV_Stride * UV_Scanlines + * + max(Extradata, Y_Stride * 8), 4096) + */ + COLOR_FMT_NV12, + + /* Venus NV21: + * YUV 4:2:0 image with a plane of 8 bit Y samples followed + * by an interleaved V/U plane containing 8 bit 2x2 subsampled + * colour difference samples. + * + * <-------- Y/UV_Stride --------> + * <------- Width -------> + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . ^ ^ + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . Height | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | Y_Scanlines + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . V | + * . . . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . . . V + * V U V U V U V U V U V U . . . . ^ + * V U V U V U V U V U V U . . . . | + * V U V U V U V U V U V U . . . . | + * V U V U V U V U V U V U . . . . UV_Scanlines + * . . . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . . . V + * . . . . . . . . . . . . . . . . --> Padding & Buffer size alignment + * + * Y_Stride : Width aligned to 128 + * UV_Stride : Width aligned to 128 + * Y_Scanlines: Height aligned to 32 + * UV_Scanlines: Height/2 aligned to 16 + * Extradata: Arbitrary (software-imposed) padding + * Total size = align((Y_Stride * Y_Scanlines + * + UV_Stride * UV_Scanlines + * + max(Extradata, Y_Stride * 8), 4096) + */ + COLOR_FMT_NV21, + /* Venus NV12_MVTB: + * Two YUV 4:2:0 images/views one after the other + * in a top-bottom layout, same as NV12 + * with a plane of 8 bit Y samples followed + * by an interleaved U/V plane containing 8 bit 2x2 subsampled + * colour difference samples. + * + * + * <-------- Y/UV_Stride --------> + * <------- Width -------> + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . ^ ^ ^ + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . Height | | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | Y_Scanlines | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . V | | + * . . . . . . . . . . . . . . . . | View_1 + * . . . . . . . . . . . . . . . . | | + * . . . . . . . . . . . . . . . . | | + * . . . . . . . . . . . . . . . . V | + * U V U V U V U V U V U V . . . . ^ | + * U V U V U V U V U V U V . . . . | | + * U V U V U V U V U V U V . . . . | | + * U V U V U V U V U V U V . . . . UV_Scanlines | + * . . . . . . . . . . . . . . . . | | + * . . . . . . . . . . . . . . . . V V + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . ^ ^ ^ + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . Height | | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | Y_Scanlines | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | + * Y Y Y Y Y Y Y Y Y Y Y Y . . . . V | | + * . . . . . . . . . . . . . . . . | View_2 + * . . . . . . . . . . . . . . . . | | + * . . . . . . . . . . . . . . . . | | + * . . . . . . . . . . . . . . . . V | + * U V U V U V U V U V U V . . . . ^ | + * U V U V U V U V U V U V . . . . | | + * U V U V U V U V U V U V . . . . | | + * U V U V U V U V U V U V . . . . UV_Scanlines | + * . . . . . . . . . . . . . . . . | | + * . . . . . . . . . . . . . . . . V V + * . . . . . . . . . . . . . . . . --> Buffer size alignment + * + * Y_Stride : Width aligned to 128 + * UV_Stride : Width aligned to 128 + * Y_Scanlines: Height aligned to 32 + * UV_Scanlines: Height/2 aligned to 16 + * View_1 begin at: 0 (zero) + * View_2 begin at: Y_Stride * Y_Scanlines + UV_Stride * UV_Scanlines + * Extradata: Arbitrary (software-imposed) padding + * Total size = align((2*(Y_Stride * Y_Scanlines) + * + 2*(UV_Stride * UV_Scanlines) + Extradata), 4096) + */ + COLOR_FMT_NV12_MVTB, + /* Venus NV12 UBWC: + * Compressed Macro-tile format for NV12. + * Contains 4 planes in the following order - + * (A) Y_Meta_Plane + * (B) Y_UBWC_Plane + * (C) UV_Meta_Plane + * (D) UV_UBWC_Plane + * + * Y_Meta_Plane consists of meta information to decode compressed + * tile data in Y_UBWC_Plane. + * Y_UBWC_Plane consists of Y data in compressed macro-tile format. + * UBWC decoder block will use the Y_Meta_Plane data together with + * Y_UBWC_Plane data to produce loss-less uncompressed 8 bit Y samples. + * + * UV_Meta_Plane consists of meta information to decode compressed + * tile data in UV_UBWC_Plane. + * UV_UBWC_Plane consists of UV data in compressed macro-tile format. + * UBWC decoder block will use UV_Meta_Plane data together with + * UV_UBWC_Plane data to produce loss-less uncompressed 8 bit 2x2 + * subsampled color difference samples. + * + * Each tile in Y_UBWC_Plane/UV_UBWC_Plane is independently decodable + * and randomly accessible. There is no dependency between tiles. + * + * <----- Y_Meta_Stride ----> + * <-------- Width ------> + * M M M M M M M M M M M M . . ^ ^ + * M M M M M M M M M M M M . . | | + * M M M M M M M M M M M M . . Height | + * M M M M M M M M M M M M . . | Meta_Y_Scanlines + * M M M M M M M M M M M M . . | | + * M M M M M M M M M M M M . . | | + * M M M M M M M M M M M M . . | | + * M M M M M M M M M M M M . . V | + * . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . -------> Buffer size aligned to 4k + * . . . . . . . . . . . . . . V + * <--Compressed tile Y Stride---> + * <------- Width -------> + * Y* Y* Y* Y* Y* Y* Y* Y* . . . . ^ ^ + * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | + * Y* Y* Y* Y* Y* Y* Y* Y* . . . . Height | + * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | Macro_tile_Y_Scanlines + * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | + * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | + * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | + * Y* Y* Y* Y* Y* Y* Y* Y* . . . . V | + * . . . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . . . -------> Buffer size aligned to 4k + * . . . . . . . . . . . . . . . . V + * <----- UV_Meta_Stride ----> + * M M M M M M M M M M M M . . ^ + * M M M M M M M M M M M M . . | + * M M M M M M M M M M M M . . | + * M M M M M M M M M M M M . . M_UV_Scanlines + * . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . V + * . . . . . . . . . . . . . . -------> Buffer size aligned to 4k + * <--Compressed tile UV Stride---> + * U* V* U* V* U* V* U* V* . . . . ^ + * U* V* U* V* U* V* U* V* . . . . | + * U* V* U* V* U* V* U* V* . . . . | + * U* V* U* V* U* V* U* V* . . . . UV_Scanlines + * . . . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . . . V + * . . . . . . . . . . . . . . . . -------> Buffer size aligned to 4k + * + * Y_Stride = align(Width, 128) + * UV_Stride = align(Width, 128) + * Y_Scanlines = align(Height, 32) + * UV_Scanlines = align(Height/2, 16) + * Y_UBWC_Plane_size = align(Y_Stride * Y_Scanlines, 4096) + * UV_UBWC_Plane_size = align(UV_Stride * UV_Scanlines, 4096) + * Y_Meta_Stride = align(roundup(Width, Y_TileWidth), 64) + * Y_Meta_Scanlines = align(roundup(Height, Y_TileHeight), 16) + * Y_Meta_Plane_size = align(Y_Meta_Stride * Y_Meta_Scanlines, 4096) + * UV_Meta_Stride = align(roundup(Width, UV_TileWidth), 64) + * UV_Meta_Scanlines = align(roundup(Height, UV_TileHeight), 16) + * UV_Meta_Plane_size = align(UV_Meta_Stride * UV_Meta_Scanlines, 4096) + * Extradata = 8k + * + * Total size = align( Y_UBWC_Plane_size + UV_UBWC_Plane_size + + * Y_Meta_Plane_size + UV_Meta_Plane_size + * + max(Extradata, Y_Stride * 48), 4096) + */ + COLOR_FMT_NV12_UBWC, + /* Venus NV12 10-bit UBWC: + * Compressed Macro-tile format for NV12. + * Contains 4 planes in the following order - + * (A) Y_Meta_Plane + * (B) Y_UBWC_Plane + * (C) UV_Meta_Plane + * (D) UV_UBWC_Plane + * + * Y_Meta_Plane consists of meta information to decode compressed + * tile data in Y_UBWC_Plane. + * Y_UBWC_Plane consists of Y data in compressed macro-tile format. + * UBWC decoder block will use the Y_Meta_Plane data together with + * Y_UBWC_Plane data to produce loss-less uncompressed 10 bit Y samples. + * + * UV_Meta_Plane consists of meta information to decode compressed + * tile data in UV_UBWC_Plane. + * UV_UBWC_Plane consists of UV data in compressed macro-tile format. + * UBWC decoder block will use UV_Meta_Plane data together with + * UV_UBWC_Plane data to produce loss-less uncompressed 10 bit 2x2 + * subsampled color difference samples. + * + * Each tile in Y_UBWC_Plane/UV_UBWC_Plane is independently decodable + * and randomly accessible. There is no dependency between tiles. + * + * <----- Y_Meta_Stride -----> + * <-------- Width ------> + * M M M M M M M M M M M M . . ^ ^ + * M M M M M M M M M M M M . . | | + * M M M M M M M M M M M M . . Height | + * M M M M M M M M M M M M . . | Meta_Y_Scanlines + * M M M M M M M M M M M M . . | | + * M M M M M M M M M M M M . . | | + * M M M M M M M M M M M M . . | | + * M M M M M M M M M M M M . . V | + * . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . -------> Buffer size aligned to 4k + * . . . . . . . . . . . . . . V + * <--Compressed tile Y Stride---> + * <------- Width -------> + * Y* Y* Y* Y* Y* Y* Y* Y* . . . . ^ ^ + * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | + * Y* Y* Y* Y* Y* Y* Y* Y* . . . . Height | + * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | Macro_tile_Y_Scanlines + * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | + * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | + * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | + * Y* Y* Y* Y* Y* Y* Y* Y* . . . . V | + * . . . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . . . -------> Buffer size aligned to 4k + * . . . . . . . . . . . . . . . . V + * <----- UV_Meta_Stride ----> + * M M M M M M M M M M M M . . ^ + * M M M M M M M M M M M M . . | + * M M M M M M M M M M M M . . | + * M M M M M M M M M M M M . . M_UV_Scanlines + * . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . V + * . . . . . . . . . . . . . . -------> Buffer size aligned to 4k + * <--Compressed tile UV Stride---> + * U* V* U* V* U* V* U* V* . . . . ^ + * U* V* U* V* U* V* U* V* . . . . | + * U* V* U* V* U* V* U* V* . . . . | + * U* V* U* V* U* V* U* V* . . . . UV_Scanlines + * . . . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . . . V + * . . . . . . . . . . . . . . . . -------> Buffer size aligned to 4k + * + * + * Y_Stride = align(Width * 4/3, 128) + * UV_Stride = align(Width * 4/3, 128) + * Y_Scanlines = align(Height, 32) + * UV_Scanlines = align(Height/2, 16) + * Y_UBWC_Plane_Size = align(Y_Stride * Y_Scanlines, 4096) + * UV_UBWC_Plane_Size = align(UV_Stride * UV_Scanlines, 4096) + * Y_Meta_Stride = align(roundup(Width, Y_TileWidth), 64) + * Y_Meta_Scanlines = align(roundup(Height, Y_TileHeight), 16) + * Y_Meta_Plane_size = align(Y_Meta_Stride * Y_Meta_Scanlines, 4096) + * UV_Meta_Stride = align(roundup(Width, UV_TileWidth), 64) + * UV_Meta_Scanlines = align(roundup(Height, UV_TileHeight), 16) + * UV_Meta_Plane_size = align(UV_Meta_Stride * UV_Meta_Scanlines, 4096) + * Extradata = 8k + * + * Total size = align(Y_UBWC_Plane_size + UV_UBWC_Plane_size + + * Y_Meta_Plane_size + UV_Meta_Plane_size + * + max(Extradata, Y_Stride * 48), 4096) + */ + COLOR_FMT_NV12_BPP10_UBWC, + /* Venus RGBA8888 format: + * Contains 1 plane in the following order - + * (A) RGBA plane + * + * <-------- RGB_Stride --------> + * <------- Width -------> + * R R R R R R R R R R R R . . . . ^ ^ + * R R R R R R R R R R R R . . . . | | + * R R R R R R R R R R R R . . . . Height | + * R R R R R R R R R R R R . . . . | RGB_Scanlines + * R R R R R R R R R R R R . . . . | | + * R R R R R R R R R R R R . . . . | | + * R R R R R R R R R R R R . . . . | | + * R R R R R R R R R R R R . . . . V | + * . . . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . . . V + * + * RGB_Stride = align(Width * 4, 128) + * RGB_Scanlines = align(Height, 32) + * RGB_Plane_size = align(RGB_Stride * RGB_Scanlines, 4096) + * Extradata = 8k + * + * Total size = align(RGB_Plane_size + Extradata, 4096) + */ + COLOR_FMT_RGBA8888, + /* Venus RGBA8888 UBWC format: + * Contains 2 planes in the following order - + * (A) Meta plane + * (B) RGBA plane + * + * <--- RGB_Meta_Stride ----> + * <-------- Width ------> + * M M M M M M M M M M M M . . ^ ^ + * M M M M M M M M M M M M . . | | + * M M M M M M M M M M M M . . Height | + * M M M M M M M M M M M M . . | Meta_RGB_Scanlines + * M M M M M M M M M M M M . . | | + * M M M M M M M M M M M M . . | | + * M M M M M M M M M M M M . . | | + * M M M M M M M M M M M M . . V | + * . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . -------> Buffer size aligned to 4k + * . . . . . . . . . . . . . . V + * <-------- RGB_Stride --------> + * <------- Width -------> + * R R R R R R R R R R R R . . . . ^ ^ + * R R R R R R R R R R R R . . . . | | + * R R R R R R R R R R R R . . . . Height | + * R R R R R R R R R R R R . . . . | RGB_Scanlines + * R R R R R R R R R R R R . . . . | | + * R R R R R R R R R R R R . . . . | | + * R R R R R R R R R R R R . . . . | | + * R R R R R R R R R R R R . . . . V | + * . . . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . . . | + * . . . . . . . . . . . . . . . . -------> Buffer size aligned to 4k + * . . . . . . . . . . . . . . . . V + * + * RGB_Stride = align(Width * 4, 128) + * RGB_Scanlines = align(Height, 32) + * RGB_Plane_size = align(RGB_Stride * RGB_Scanlines, 4096) + * RGB_Meta_Stride = align(roundup(Width, RGB_TileWidth), 64) + * RGB_Meta_Scanline = align(roundup(Height, RGB_TileHeight), 16) + * RGB_Meta_Plane_size = align(RGB_Meta_Stride * + * RGB_Meta_Scanlines, 4096) + * Extradata = 8k + * + * Total size = align(RGB_Meta_Plane_size + RGB_Plane_size + + * Extradata, 4096) + */ + COLOR_FMT_RGBA8888_UBWC, +}; + +static inline unsigned int VENUS_EXTRADATA_SIZE(int width, int height) +{ + (void)height; + (void)width; + + /* + * In the future, calculate the size based on the w/h but just + * hardcode it for now since 16K satisfies all current usecases. + */ + return 16 * 1024; +} + +static inline unsigned int VENUS_Y_STRIDE(int color_fmt, int width) +{ + unsigned int alignment, stride = 0; + if (!width) + goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_NV21: + case COLOR_FMT_NV12: + case COLOR_FMT_NV12_MVTB: + case COLOR_FMT_NV12_UBWC: + alignment = 128; + stride = MSM_MEDIA_ALIGN(width, alignment); + break; + case COLOR_FMT_NV12_BPP10_UBWC: + alignment = 256; + stride = MSM_MEDIA_ALIGN(width, 192); + stride = MSM_MEDIA_ALIGN(stride * 4/3, alignment); + break; + default: + break; + } +invalid_input: + return stride; +} + +static inline unsigned int VENUS_UV_STRIDE(int color_fmt, int width) +{ + unsigned int alignment, stride = 0; + if (!width) + goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_NV21: + case COLOR_FMT_NV12: + case COLOR_FMT_NV12_MVTB: + case COLOR_FMT_NV12_UBWC: + alignment = 128; + stride = MSM_MEDIA_ALIGN(width, alignment); + break; + case COLOR_FMT_NV12_BPP10_UBWC: + alignment = 256; + stride = MSM_MEDIA_ALIGN(width, 192); + stride = MSM_MEDIA_ALIGN(stride * 4/3, alignment); + break; + default: + break; + } +invalid_input: + return stride; +} + +static inline unsigned int VENUS_Y_SCANLINES(int color_fmt, int height) +{ + unsigned int alignment, sclines = 0; + if (!height) + goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_NV21: + case COLOR_FMT_NV12: + case COLOR_FMT_NV12_MVTB: + case COLOR_FMT_NV12_UBWC: + alignment = 32; + break; + case COLOR_FMT_NV12_BPP10_UBWC: + alignment = 16; + break; + default: + return 0; + } + sclines = MSM_MEDIA_ALIGN(height, alignment); +invalid_input: + return sclines; +} + +static inline unsigned int VENUS_UV_SCANLINES(int color_fmt, int height) +{ + unsigned int alignment, sclines = 0; + if (!height) + goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_NV21: + case COLOR_FMT_NV12: + case COLOR_FMT_NV12_MVTB: + case COLOR_FMT_NV12_BPP10_UBWC: + alignment = 16; + break; + case COLOR_FMT_NV12_UBWC: + alignment = 32; + break; + default: + goto invalid_input; + } + + sclines = MSM_MEDIA_ALIGN(height / 2, alignment); + +invalid_input: + return sclines; +} + +static inline unsigned int VENUS_Y_META_STRIDE(int color_fmt, int width) +{ + int y_tile_width = 0, y_meta_stride = 0; + + if (!width) + goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_NV12_UBWC: + y_tile_width = 32; + break; + case COLOR_FMT_NV12_BPP10_UBWC: + y_tile_width = 48; + break; + default: + goto invalid_input; + } + + y_meta_stride = MSM_MEDIA_ROUNDUP(width, y_tile_width); + y_meta_stride = MSM_MEDIA_ALIGN(y_meta_stride, 64); + +invalid_input: + return y_meta_stride; +} + +static inline unsigned int VENUS_Y_META_SCANLINES(int color_fmt, int height) +{ + int y_tile_height = 0, y_meta_scanlines = 0; + + if (!height) + goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_NV12_UBWC: + y_tile_height = 8; + break; + case COLOR_FMT_NV12_BPP10_UBWC: + y_tile_height = 4; + break; + default: + goto invalid_input; + } + + y_meta_scanlines = MSM_MEDIA_ROUNDUP(height, y_tile_height); + y_meta_scanlines = MSM_MEDIA_ALIGN(y_meta_scanlines, 16); + +invalid_input: + return y_meta_scanlines; +} + +static inline unsigned int VENUS_UV_META_STRIDE(int color_fmt, int width) +{ + int uv_tile_width = 0, uv_meta_stride = 0; + + if (!width) + goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_NV12_UBWC: + uv_tile_width = 16; + break; + case COLOR_FMT_NV12_BPP10_UBWC: + uv_tile_width = 24; + break; + default: + goto invalid_input; + } + + uv_meta_stride = MSM_MEDIA_ROUNDUP(width / 2, uv_tile_width); + uv_meta_stride = MSM_MEDIA_ALIGN(uv_meta_stride, 64); + +invalid_input: + return uv_meta_stride; +} + +static inline unsigned int VENUS_UV_META_SCANLINES(int color_fmt, int height) +{ + int uv_tile_height = 0, uv_meta_scanlines = 0; + + if (!height) + goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_NV12_UBWC: + uv_tile_height = 8; + break; + case COLOR_FMT_NV12_BPP10_UBWC: + uv_tile_height = 4; + break; + default: + goto invalid_input; + } + + uv_meta_scanlines = MSM_MEDIA_ROUNDUP(height / 2, uv_tile_height); + uv_meta_scanlines = MSM_MEDIA_ALIGN(uv_meta_scanlines, 16); + +invalid_input: + return uv_meta_scanlines; +} + +static inline unsigned int VENUS_RGB_STRIDE(int color_fmt, int width) +{ + unsigned int alignment = 0, stride = 0; + if (!width) + goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_RGBA8888: + alignment = 128; + break; + case COLOR_FMT_RGBA8888_UBWC: + alignment = 256; + break; + default: + goto invalid_input; + } + + stride = MSM_MEDIA_ALIGN(width * 4, alignment); + +invalid_input: + return stride; +} + +static inline unsigned int VENUS_RGB_SCANLINES(int color_fmt, int height) +{ + unsigned int alignment = 0, scanlines = 0; + + if (!height) + goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_RGBA8888: + alignment = 32; + break; + case COLOR_FMT_RGBA8888_UBWC: + alignment = 16; + break; + default: + goto invalid_input; + } + + scanlines = MSM_MEDIA_ALIGN(height, alignment); + +invalid_input: + return scanlines; +} + +static inline unsigned int VENUS_RGB_META_STRIDE(int color_fmt, int width) +{ + int rgb_tile_width = 0, rgb_meta_stride = 0; + + if (!width) + goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_RGBA8888_UBWC: + rgb_tile_width = 16; + break; + default: + goto invalid_input; + } + + rgb_meta_stride = MSM_MEDIA_ROUNDUP(width, rgb_tile_width); + rgb_meta_stride = MSM_MEDIA_ALIGN(rgb_meta_stride, 64); + +invalid_input: + return rgb_meta_stride; +} + +static inline unsigned int VENUS_RGB_META_SCANLINES(int color_fmt, int height) +{ + int rgb_tile_height = 0, rgb_meta_scanlines = 0; + + if (!height) + goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_RGBA8888_UBWC: + rgb_tile_height = 4; + break; + default: + goto invalid_input; + } + + rgb_meta_scanlines = MSM_MEDIA_ROUNDUP(height, rgb_tile_height); + rgb_meta_scanlines = MSM_MEDIA_ALIGN(rgb_meta_scanlines, 16); + +invalid_input: + return rgb_meta_scanlines; +} + +static inline unsigned int VENUS_BUFFER_SIZE( + int color_fmt, int width, int height) +{ + const unsigned int extra_size = VENUS_EXTRADATA_SIZE(width, height); + unsigned int uv_alignment = 0, size = 0; + unsigned int y_plane, uv_plane, y_stride, + uv_stride, y_sclines, uv_sclines; + unsigned int y_ubwc_plane = 0, uv_ubwc_plane = 0; + unsigned int y_meta_stride = 0, y_meta_scanlines = 0; + unsigned int uv_meta_stride = 0, uv_meta_scanlines = 0; + unsigned int y_meta_plane = 0, uv_meta_plane = 0; + unsigned int rgb_stride = 0, rgb_scanlines = 0; + unsigned int rgb_plane = 0, rgb_ubwc_plane = 0, rgb_meta_plane = 0; + unsigned int rgb_meta_stride = 0, rgb_meta_scanlines = 0; + + if (!width || !height) + goto invalid_input; + + y_stride = VENUS_Y_STRIDE(color_fmt, width); + uv_stride = VENUS_UV_STRIDE(color_fmt, width); + y_sclines = VENUS_Y_SCANLINES(color_fmt, height); + uv_sclines = VENUS_UV_SCANLINES(color_fmt, height); + rgb_stride = VENUS_RGB_STRIDE(color_fmt, width); + rgb_scanlines = VENUS_RGB_SCANLINES(color_fmt, height); + + switch (color_fmt) { + case COLOR_FMT_NV21: + case COLOR_FMT_NV12: + uv_alignment = 4096; + y_plane = y_stride * y_sclines; + uv_plane = uv_stride * uv_sclines + uv_alignment; + size = y_plane + uv_plane + + MSM_MEDIA_MAX(extra_size, 8 * y_stride); + size = MSM_MEDIA_ALIGN(size, 4096); + break; + case COLOR_FMT_NV12_MVTB: + uv_alignment = 4096; + y_plane = y_stride * y_sclines; + uv_plane = uv_stride * uv_sclines + uv_alignment; + size = y_plane + uv_plane; + size = 2 * size + extra_size; + size = MSM_MEDIA_ALIGN(size, 4096); + break; + case COLOR_FMT_NV12_UBWC: + case COLOR_FMT_NV12_BPP10_UBWC: + y_ubwc_plane = MSM_MEDIA_ALIGN(y_stride * y_sclines, 4096); + uv_ubwc_plane = MSM_MEDIA_ALIGN(uv_stride * uv_sclines, 4096); + y_meta_stride = VENUS_Y_META_STRIDE(color_fmt, width); + y_meta_scanlines = VENUS_Y_META_SCANLINES(color_fmt, height); + y_meta_plane = MSM_MEDIA_ALIGN( + y_meta_stride * y_meta_scanlines, 4096); + uv_meta_stride = VENUS_UV_META_STRIDE(color_fmt, width); + uv_meta_scanlines = VENUS_UV_META_SCANLINES(color_fmt, height); + uv_meta_plane = MSM_MEDIA_ALIGN(uv_meta_stride * + uv_meta_scanlines, 4096); + + size = y_ubwc_plane + uv_ubwc_plane + y_meta_plane + + uv_meta_plane + + MSM_MEDIA_MAX(extra_size + 8192, 48 * y_stride); + size = MSM_MEDIA_ALIGN(size, 4096); + break; + case COLOR_FMT_RGBA8888: + rgb_plane = MSM_MEDIA_ALIGN(rgb_stride * rgb_scanlines, 4096); + size = rgb_plane; + size = MSM_MEDIA_ALIGN(size, 4096); + break; + case COLOR_FMT_RGBA8888_UBWC: + rgb_ubwc_plane = MSM_MEDIA_ALIGN(rgb_stride * rgb_scanlines, + 4096); + rgb_meta_stride = VENUS_RGB_META_STRIDE(color_fmt, width); + rgb_meta_scanlines = VENUS_RGB_META_SCANLINES(color_fmt, + height); + rgb_meta_plane = MSM_MEDIA_ALIGN(rgb_meta_stride * + rgb_meta_scanlines, 4096); + size = rgb_ubwc_plane + rgb_meta_plane; + size = MSM_MEDIA_ALIGN(size, 4096); + break; + default: + break; + } +invalid_input: + return size; +} + +static inline unsigned int VENUS_VIEW2_OFFSET( + int color_fmt, int width, int height) +{ + unsigned int offset = 0; + unsigned int y_plane, uv_plane, y_stride, + uv_stride, y_sclines, uv_sclines; + if (!width || !height) + goto invalid_input; + + y_stride = VENUS_Y_STRIDE(color_fmt, width); + uv_stride = VENUS_UV_STRIDE(color_fmt, width); + y_sclines = VENUS_Y_SCANLINES(color_fmt, height); + uv_sclines = VENUS_UV_SCANLINES(color_fmt, height); + switch (color_fmt) { + case COLOR_FMT_NV12_MVTB: + y_plane = y_stride * y_sclines; + uv_plane = uv_stride * uv_sclines; + offset = y_plane + uv_plane; + break; + default: + break; + } +invalid_input: + return offset; +} + +#endif diff --git a/selfdrive/loggerd/logger.c b/selfdrive/loggerd/logger.c new file mode 100644 index 0000000000..7dfb610bad --- /dev/null +++ b/selfdrive/loggerd/logger.c @@ -0,0 +1,217 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include "common/swaglog.h" + +#include "logger.h" + +static int mkpath(char* file_path) { + assert(file_path && *file_path); + char* p; + for (p=strchr(file_path+1, '/'); p; p=strchr(p+1, '/')) { + *p = '\0'; + if (mkdir(file_path, 0777)==-1) { + if (errno != EEXIST) { + *p = '/'; + return -1; + } + } + *p = '/'; + } + return 0; +} + +void logger_init(LoggerState *s, const char* log_name, const uint8_t* init_data, size_t init_data_len, bool has_qlog) { + memset(s, 0, sizeof(*s)); + if (init_data) { + s->init_data = (uint8_t*)malloc(init_data_len); + assert(s->init_data); + memcpy(s->init_data, init_data, init_data_len); + s->init_data_len = init_data_len; + } + + umask(0); + + pthread_mutex_init(&s->lock, NULL); + + s->part = -1; + s->has_qlog = has_qlog; + + time_t rawtime = time(NULL); + struct tm timeinfo; + localtime_r(&rawtime, &timeinfo); + + strftime(s->route_name, sizeof(s->route_name), + "%Y-%m-%d--%H-%M-%S", &timeinfo); + snprintf(s->log_name, sizeof(s->log_name), "%s", log_name); +} + +static LoggerHandle* logger_open(LoggerState *s, const char* root_path) { + int err; + + LoggerHandle *h = NULL; + for (int i=0; ihandles[i].refcnt == 0) { + h = &s->handles[i]; + break; + } + } + assert(h); + + snprintf(h->segment_path, sizeof(h->segment_path), + "%s/%s--%d", root_path, s->route_name, s->part); + + snprintf(h->log_path, sizeof(h->log_path), "%s/%s.bz2", h->segment_path, s->log_name); + snprintf(h->qlog_path, sizeof(h->qlog_path), "%s/qlog.bz2", h->segment_path); + snprintf(h->lock_path, sizeof(h->lock_path), "%s.lock", h->log_path); + + err = mkpath(h->log_path); + if (err) return NULL; + + FILE* lock_file = fopen(h->lock_path, "wb"); + if (lock_file == NULL) return NULL; + fclose(lock_file); + + h->log_file = fopen(h->log_path, "wb"); + if (h->log_file == NULL) goto fail; + + if (s->has_qlog) { + h->qlog_file = fopen(h->qlog_path, "wb"); + if (h->qlog_file == NULL) goto fail; + } + + int bzerror; + h->bz_file = BZ2_bzWriteOpen(&bzerror, h->log_file, 9, 0, 30); + if (bzerror != BZ_OK) goto fail; + + if (s->has_qlog) { + h->bz_qlog = BZ2_bzWriteOpen(&bzerror, h->qlog_file, 9, 0, 30); + if (bzerror != BZ_OK) goto fail; + } + + if (s->init_data) { + BZ2_bzWrite(&bzerror, h->bz_file, s->init_data, s->init_data_len); + if (bzerror != BZ_OK) goto fail; + + if (s->has_qlog) { + // init data goes in the qlog too + BZ2_bzWrite(&bzerror, h->bz_qlog, s->init_data, s->init_data_len); + if (bzerror != BZ_OK) goto fail; + } + } + + pthread_mutex_init(&h->lock, NULL); + h->refcnt++; + return h; +fail: + LOGE("logger failed to open files"); + if (h->qlog_file) fclose(h->qlog_file); + if (h->log_file) fclose(h->log_file); + return NULL; +} + +int logger_next(LoggerState *s, const char* root_path, + char* out_segment_path, size_t out_segment_path_len, + int* out_part) { + pthread_mutex_lock(&s->lock); + s->part++; + + LoggerHandle* next_h = logger_open(s, root_path); + if (!next_h) { + pthread_mutex_unlock(&s->lock); + return -1; + } + + if (s->cur_handle) { + lh_close(s->cur_handle); + } + s->cur_handle = next_h; + + if (out_segment_path) { + snprintf(out_segment_path, out_segment_path_len, "%s", next_h->segment_path); + } + if (out_part) { + *out_part = s->part; + } + + pthread_mutex_unlock(&s->lock); + return 0; +} + +LoggerHandle* logger_get_handle(LoggerState *s) { + pthread_mutex_lock(&s->lock); + LoggerHandle* h = s->cur_handle; + if (h) { + pthread_mutex_lock(&h->lock); + h->refcnt++; + pthread_mutex_unlock(&h->lock); + } + pthread_mutex_unlock(&s->lock); + return h; +} + +void logger_log(LoggerState *s, uint8_t* data, size_t data_size, bool in_qlog) { + pthread_mutex_lock(&s->lock); + if (s->cur_handle) { + lh_log(s->cur_handle, data, data_size, in_qlog); + } + pthread_mutex_unlock(&s->lock); +} + +void logger_close(LoggerState *s) { + pthread_mutex_lock(&s->lock); + free(s->init_data); + if (s->cur_handle) { + lh_close(s->cur_handle); + } + pthread_mutex_unlock(&s->lock); +} + +void lh_log(LoggerHandle* h, uint8_t* data, size_t data_size, bool in_qlog) { + pthread_mutex_lock(&h->lock); + assert(h->refcnt > 0); + int bzerror; + BZ2_bzWrite(&bzerror, h->bz_file, data, data_size); + + if (in_qlog && h->bz_qlog != NULL) { + BZ2_bzWrite(&bzerror, h->bz_qlog, data, data_size); + } + pthread_mutex_unlock(&h->lock); +} + +void lh_close(LoggerHandle* h) { + pthread_mutex_lock(&h->lock); + assert(h->refcnt > 0); + h->refcnt--; + if (h->refcnt == 0) { + if (h->bz_file){ + int bzerror; + BZ2_bzWriteClose(&bzerror, h->bz_file, 0, NULL, NULL); + h->bz_file = NULL; + } + if (h->bz_qlog){ + int bzerror; + BZ2_bzWriteClose(&bzerror, h->bz_qlog, 0, NULL, NULL); + h->bz_qlog = NULL; + } + if (h->qlog_file) fclose(h->qlog_file); + fclose(h->log_file); + unlink(h->lock_path); + pthread_mutex_unlock(&h->lock); + pthread_mutex_destroy(&h->lock); + return; + } + pthread_mutex_unlock(&h->lock); +} diff --git a/selfdrive/loggerd/logger.h b/selfdrive/loggerd/logger.h new file mode 100644 index 0000000000..ab8798481c --- /dev/null +++ b/selfdrive/loggerd/logger.h @@ -0,0 +1,59 @@ +#ifndef LOGGER_H +#define LOGGER_H + +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define LOGGER_MAX_HANDLES 16 + +typedef struct LoggerHandle { + pthread_mutex_t lock; + int refcnt; + char segment_path[4096]; + char log_path[4096]; + char lock_path[4096]; + FILE* log_file; + BZFILE* bz_file; + + FILE* qlog_file; + char qlog_path[4096]; + BZFILE* bz_qlog; +} LoggerHandle; + +typedef struct LoggerState { + pthread_mutex_t lock; + + uint8_t* init_data; + size_t init_data_len; + + int part; + char route_name[64]; + char log_name[64]; + bool has_qlog; + + LoggerHandle handles[LOGGER_MAX_HANDLES]; + LoggerHandle* cur_handle; +} LoggerState; + +void logger_init(LoggerState *s, const char* log_name, const uint8_t* init_data, size_t init_data_len, bool has_qlog); +int logger_next(LoggerState *s, const char* root_path, + char* out_segment_path, size_t out_segment_path_len, + int* out_part); +LoggerHandle* logger_get_handle(LoggerState *s); +void logger_close(LoggerState *s); +void logger_log(LoggerState *s, uint8_t* data, size_t data_size, bool in_qlog); + +void lh_log(LoggerHandle* h, uint8_t* data, size_t data_size, bool in_qlog); +void lh_close(LoggerHandle* h); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/selfdrive/loggerd/loggerd b/selfdrive/loggerd/loggerd deleted file mode 100755 index 2fcf09831f..0000000000 Binary files a/selfdrive/loggerd/loggerd and /dev/null differ diff --git a/selfdrive/loggerd/loggerd.cc b/selfdrive/loggerd/loggerd.cc new file mode 100644 index 0000000000..db59780f0b --- /dev/null +++ b/selfdrive/loggerd/loggerd.cc @@ -0,0 +1,770 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include "common/version.h" +#include "common/timing.h" +#include "common/params.h" +#include "common/swaglog.h" +#include "common/visionipc.h" +#include "common/utilpp.h" +#include "common/util.h" + +#include "logger.h" + + +#ifndef DISABLE_ENCODER +#include "encoder.h" +#include "raw_logger.h" +#endif + +#include "cereal/gen/cpp/log.capnp.h" + +#define CAMERA_FPS 20 +#define SEGMENT_LENGTH 60 +#define LOG_ROOT "/data/media/0/realdata" +#define ENABLE_LIDAR 0 + +#define RAW_CLIP_LENGTH 100 // 5 seconds at 20fps +#define RAW_CLIP_FREQUENCY (randrange(61, 8*60)) // once every ~4 minutes + +namespace { + +double randrange(double a, double b) { + static std::mt19937 gen(millis_since_boot()); + + std::uniform_real_distribution<> dist(a, b); + return dist(gen); +} + + +volatile int do_exit = 0; +static void set_do_exit(int sig) { + do_exit = 1; +} +struct LoggerdState { + void *ctx; + LoggerState logger; + + std::mutex lock; + std::condition_variable cv; + char segment_path[4096]; + uint32_t last_frame_id; + uint32_t rotate_last_frame_id; + int rotate_segment; +}; +LoggerdState s; + +#ifndef DISABLE_ENCODER +void encoder_thread(bool is_streaming, bool raw_clips, bool front) { + int err; + + if (front) { + char *value; + const int result = read_db_value(NULL, "RecordFront", &value, NULL); + if (result != 0) return; + if (value[0] != '1') { free(value); return; } + free(value); + LOGW("recording front camera"); + + set_thread_name("FrontCameraEncoder"); + } else { + set_thread_name("RearCameraEncoder"); + } + + VisionStream stream; + + bool encoder_inited = false; + EncoderState encoder; + + int encoder_segment = -1; + int cnt = 0; + + void *idx_sock = zmq_socket(s.ctx, ZMQ_PUB); + assert(idx_sock); + zmq_bind(idx_sock, front ? "tcp://*:8061" : "tcp://*:8015"); + + LoggerHandle *lh = NULL; + + while (!do_exit) { + VisionStreamBufs buf_info; + if (front) { + err = visionstream_init(&stream, VISION_STREAM_YUV_FRONT, false, &buf_info); + } else { + err = visionstream_init(&stream, VISION_STREAM_YUV, false, &buf_info); + } + if (err != 0) { + LOGD("visionstream connect fail"); + usleep(100000); + continue; + } + + if (!encoder_inited) { + LOGD("encoder init %dx%d", buf_info.width, buf_info.height); + encoder_init(&encoder, front ? "dcamera" : "fcamera", buf_info.width, buf_info.height, CAMERA_FPS, front ? 1000000 : 5000000); + encoder_inited = true; + if (is_streaming) { + encoder.stream_sock_raw = zmq_socket(s.ctx, ZMQ_PUB); + assert(encoder.stream_sock_raw); + zmq_bind(encoder.stream_sock_raw, "tcp://*:9002"); + } + } + + // dont log a raw clip in the first minute + double rawlogger_start_time = seconds_since_boot()+RAW_CLIP_FREQUENCY; + int rawlogger_clip_cnt = 0; + RawLogger *rawlogger = NULL; + + if (raw_clips) { + rawlogger = new RawLogger("prcamera", buf_info.width, buf_info.height, CAMERA_FPS); + } + + while (!do_exit) { + VIPCBufExtra extra; + VIPCBuf* buf = visionstream_get(&stream, &extra); + if (buf == NULL) { + LOG("visionstream get failed"); + break; + } + + uint64_t current_time = nanos_since_boot(); + uint64_t diff = current_time - extra.timestamp_eof; + double msdiff = (double) diff / 1000000.0; + // printf("logger latency to tsEof: %f\n", msdiff); + + uint8_t *y = (uint8_t*)buf->addr; + uint8_t *u = y + (buf_info.width*buf_info.height); + uint8_t *v = u + (buf_info.width/2)*(buf_info.height/2); + + { + bool should_rotate = false; + std::unique_lock lk(s.lock); + if (!front) { + // wait if log camera is older on back camera + while ( extra.frame_id > s.last_frame_id //if the log camera is older, wait for it to catch up. + && (extra.frame_id-s.last_frame_id) < 8 // but if its too old then there probably was a discontinuity (visiond restarted) + && !do_exit) { + s.cv.wait(lk); + } + should_rotate = extra.frame_id > s.rotate_last_frame_id && encoder_segment < s.rotate_segment; + } else { + // front camera is best effort + should_rotate = encoder_segment < s.rotate_segment; + } + if (do_exit) break; + + // rotate the encoder if the logger is on a newer segment + if (should_rotate) { + LOG("rotate encoder to %s", s.segment_path); + + encoder_rotate(&encoder, s.segment_path, s.rotate_segment); + + if (raw_clips) { + rawlogger->Rotate(s.segment_path, s.rotate_segment); + } + + encoder_segment = s.rotate_segment; + if (lh) { + lh_close(lh); + } + lh = logger_get_handle(&s.logger); + } + } + + { + // encode hevc + int out_segment = -1; + int out_id = encoder_encode_frame(&encoder, cnt*50000ULL, + y, u, v, &out_segment, &extra); + + // publish encode index + capnp::MallocMessageBuilder msg; + cereal::Event::Builder event = msg.initRoot(); + event.setLogMonoTime(nanos_since_boot()); + auto eidx = event.initEncodeIdx(); + eidx.setFrameId(extra.frame_id); + eidx.setType(front ? cereal::EncodeIndex::Type::FRONT : cereal::EncodeIndex::Type::FULL_H_E_V_C); + eidx.setEncodeId(cnt); + eidx.setSegmentNum(out_segment); + eidx.setSegmentId(out_id); + + auto words = capnp::messageToFlatArray(msg); + auto bytes = words.asBytes(); + if (zmq_send(idx_sock, bytes.begin(), bytes.size(), 0) < 0) { + printf("err sending encodeIdx pkt: %s\n", strerror(errno)); + } + if (lh) { + lh_log(lh, bytes.begin(), bytes.size(), false); + } + } + + if (raw_clips) { + double ts = seconds_since_boot(); + if (ts > rawlogger_start_time) { + // encode raw if in clip + int out_segment = -1; + int out_id = rawlogger->LogFrame(cnt, y, u, v, &out_segment); + + if (rawlogger_clip_cnt == 0) { + LOG("starting raw clip in seg %d", out_segment); + } + + // publish encode index + capnp::MallocMessageBuilder msg; + cereal::Event::Builder event = msg.initRoot(); + event.setLogMonoTime(nanos_since_boot()); + auto eidx = event.initEncodeIdx(); + eidx.setFrameId(extra.frame_id); + eidx.setType(cereal::EncodeIndex::Type::FULL_LOSSLESS_CLIP); + eidx.setEncodeId(cnt); + eidx.setSegmentNum(out_segment); + eidx.setSegmentId(out_id); + + auto words = capnp::messageToFlatArray(msg); + auto bytes = words.asBytes(); + if (lh) { + lh_log(lh, bytes.begin(), bytes.size(), false); + } + + // close rawlogger if clip ended + rawlogger_clip_cnt++; + if (rawlogger_clip_cnt >= RAW_CLIP_LENGTH) { + rawlogger->Close(); + + rawlogger_clip_cnt = 0; + rawlogger_start_time = ts+RAW_CLIP_FREQUENCY; + + LOG("ending raw clip in seg %d, next in %.1f sec", out_segment, rawlogger_start_time-ts); + } + } + } + + cnt++; + } + + if (lh) { + lh_close(lh); + lh = NULL; + } + + if (raw_clips) { + rawlogger->Close(); + delete rawlogger; + } + + visionstream_destroy(&stream); + } + + if (encoder_inited) { + LOG("encoder destroy"); + encoder_close(&encoder); + encoder_destroy(&encoder); + } +} +#endif + +#if ENABLE_LIDAR + +#include +#include +#include +#include + +#define VELODYNE_DATA_PORT 2368 +#define VELODYNE_TELEMETRY_PORT 8308 + +#define MAX_LIDAR_PACKET 2048 + +int lidar_thread() { + // increase kernel max buffer size + system("sysctl -w net.core.rmem_max=26214400"); + set_thread_name("lidar"); + + int sock; + if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { + perror("cannot create socket"); + return -1; + } + + int a = 26214400; + if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &a, sizeof(int)) == -1) { + perror("cannot set socket opts"); + return -1; + } + + struct sockaddr_in addr; + memset(&addr, 0, sizeof(struct sockaddr_in)); + addr.sin_family = AF_INET; + addr.sin_port = htons(VELODYNE_DATA_PORT); + inet_aton("192.168.5.11", &(addr.sin_addr)); + + if (bind(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) { + perror("cannot bind LIDAR socket"); + return -1; + } + + capnp::byte buf[MAX_LIDAR_PACKET]; + + while (!do_exit) { + // receive message + struct sockaddr from; + socklen_t fromlen = sizeof(from); + int cnt = recvfrom(sock, (void *)buf, MAX_LIDAR_PACKET, 0, &from, &fromlen); + if (cnt <= 0) { + printf("bug in lidar recieve!\n"); + continue; + } + + // create message for log + capnp::MallocMessageBuilder msg; + auto event = msg.initRoot(); + event.setLogMonoTime(nanos_since_boot()); + auto lidar_pts = event.initLidarPts(); + + // copy in the buffer + // TODO: can we remove this copy? does it matter? + kj::ArrayPtr bufferPtr = kj::arrayPtr(buf, cnt); + lidar_pts.setPkt(bufferPtr); + + // log it + auto words = capnp::messageToFlatArray(msg); + auto bytes = words.asBytes(); + logger_log(&s.logger, bytes.begin(), bytes.size()); + } + return 0; +} +#endif + +} + +void append_property(const char* key, const char* value, void *cookie) { + std::vector > *properties = + (std::vector > *)cookie; + + properties->push_back(std::make_pair(std::string(key), std::string(value))); +} + +kj::Array gen_init_data() { + capnp::MallocMessageBuilder msg; + auto event = msg.initRoot(); + event.setLogMonoTime(nanos_since_boot()); + auto init = event.initInitData(); + + init.setDeviceType(cereal::InitData::DeviceType::NEO); + init.setVersion(capnp::Text::Reader(COMMA_VERSION)); + + std::ifstream cmdline_stream("/proc/cmdline"); + std::vector kernel_args; + std::string buf; + while (cmdline_stream >> buf) { + kernel_args.push_back(buf); + } + + auto lkernel_args = init.initKernelArgs(kernel_args.size()); + for (int i=0; i > properties; + property_list(append_property, (void*)&properties); + + auto lentries = init.initAndroidProperties().initEntries(properties.size()); + for (int i=0; i params; + read_db_all(NULL, ¶ms); + auto lparams = init.initParams().initEntries(params.size()); + int i = 0; + for (auto& kv : params) { + auto lentry = lparams[i]; + lentry.setKey(kv.first); + lentry.setValue(kv.second); + i++; + } + } + + + auto words = capnp::messageToFlatArray(msg); + + if (git_commit) { + free((void*)git_commit); + } + + if (git_branch) { + free((void*)git_branch); + } + + if (git_remote) { + free((void*)git_remote); + } + + if (passive) { + free((void*)passive); + } + + return words; +} + +static int clear_locks_fn(const char* fpath, const struct stat *sb, int tyupeflag) { + const char* dot = strrchr(fpath, '.'); + if (dot && strcmp(dot, ".lock") == 0) { + unlink(fpath); + } + return 0; +} + +static void clear_locks() { + ftw(LOG_ROOT, clear_locks_fn, 16); +} + +static void bootlog() { + int err; + + { + auto words = gen_init_data(); + auto bytes = words.asBytes(); + logger_init(&s.logger, "bootlog", bytes.begin(), bytes.size(), false); + } + + err = logger_next(&s.logger, LOG_ROOT, s.segment_path, sizeof(s.segment_path), &s.rotate_segment); + assert(err == 0); + LOGW("bootlog to %s", s.segment_path); + + { + capnp::MallocMessageBuilder msg; + auto event = msg.initRoot(); + event.setLogMonoTime(nanos_since_boot()); + + auto boot = event.initBoot(); + + boot.setWallTimeNanos(nanos_since_epoch()); + + std::string lastKmsg = util::read_file("/sys/fs/pstore/console-ramoops"); + boot.setLastKmsg(capnp::Data::Reader((const kj::byte*)lastKmsg.data(), lastKmsg.size())); + + std::string lastPmsg = util::read_file("/sys/fs/pstore/pmsg-ramoops-0"); + boot.setLastPmsg(capnp::Data::Reader((const kj::byte*)lastPmsg.data(), lastPmsg.size())); + + auto words = capnp::messageToFlatArray(msg); + auto bytes = words.asBytes(); + logger_log(&s.logger, bytes.begin(), bytes.size(), false); + } + + logger_close(&s.logger); +} + +int main(int argc, char** argv) { + int err; + + if (argc > 1 && strcmp(argv[1], "--bootlog") == 0) { + bootlog(); + return 0; + } + + setpriority(PRIO_PROCESS, 0, -12); + + clear_locks(); + + signal(SIGINT, (sighandler_t)set_do_exit); + signal(SIGTERM, (sighandler_t)set_do_exit); + + s.ctx = zmq_ctx_new(); + assert(s.ctx); + + std::set ts_replace_sock; + + std::string exe_dir = util::dir_name(util::readlink("/proc/self/exe")); + std::string service_list_path = exe_dir + "/../service_list.yaml"; + + // subscribe to all services + + void *frame_sock = NULL; + + // zmq_poll is slow because it has to be careful because the signaling + // fd is edge-triggered. we can be faster by knowing that we're not messing with it + // other than draining and polling + std::vector polls; + std::vector socks; + + std::map qlog_counter; + std::map qlog_freqs; + + YAML::Node service_list = YAML::LoadFile(service_list_path); + for (const auto& it : service_list) { + auto name = it.first.as(); + int port = it.second[0].as(); + bool should_log = it.second[1].as(); + int qlog_freq = it.second[3] ? it.second[3].as() : 0; + + if (should_log) { + void* sock = zmq_socket(s.ctx, ZMQ_SUB); + zmq_setsockopt(sock, ZMQ_SUBSCRIBE, "", 0); + + // make zmq will do exponential backoff from 100ms to 500ms for socket reconnects + int reconnect_ivl = 500; + zmq_setsockopt(sock, ZMQ_RECONNECT_IVL_MAX, &reconnect_ivl, sizeof(reconnect_ivl)); + + std::stringstream ss; + ss << "tcp://"; + if (it.second[4]) { + ss << it.second[4].as(); + ts_replace_sock.insert(sock); + } else{ + ss << "127.0.0.1"; + } + ss << ":" << port; + + zmq_connect(sock, ss.str().c_str()); + + struct pollfd pfd = {0}; + size_t fd_size = sizeof(pfd.fd); + err = zmq_getsockopt(sock, ZMQ_FD, &pfd.fd, &fd_size); + assert(err == 0); + pfd.events = POLLIN; + polls.push_back(pfd); + socks.push_back(sock); + + if (name == "frame") { + LOGD("found frame sock at port %d", port); + frame_sock = sock; + } + + qlog_counter[sock] = (qlog_freq == 0) ? -1 : 0; + qlog_freqs[sock] = qlog_freq; + } + } + + + { + auto words = gen_init_data(); + auto bytes = words.asBytes(); + logger_init(&s.logger, "rlog", bytes.begin(), bytes.size(), true); + } + + bool is_streaming = false; + bool is_logging = true; + + if (argc > 1 && strcmp(argv[1], "--stream") == 0) { + is_streaming = true; + } else if (argc > 1 && strcmp(argv[1], "--only-stream") == 0) { + is_streaming = true; + is_logging = false; + } + + if (is_logging) { + err = logger_next(&s.logger, LOG_ROOT, s.segment_path, sizeof(s.segment_path), &s.rotate_segment); + assert(err == 0); + LOGW("logging to %s", s.segment_path); + } + + double start_ts = seconds_since_boot(); + double last_rotate_ts = start_ts; + +#ifndef DISABLE_ENCODER + // rear camera + std::thread encoder_thread_handle(encoder_thread, is_streaming, false, false); + + // front camera + std::thread front_encoder_thread_handle(encoder_thread, false, false, true); +#endif + +#if ENABLE_LIDAR + std::thread lidar_thread_handle(lidar_thread); +#endif + + uint64_t msg_count = 0; + uint64_t bytes_count = 0; + + while (!do_exit) { + // err = zmq_poll(polls.data(), polls.size(), 100 * 1000); + err = poll(polls.data(), polls.size(), 100*1000); + if (err < 0) break; + + for (int i=0; i((len / sizeof(capnp::word)) + 1); + memcpy(amsg.begin(), data, len); + + // track camera frames to sync to encoder + capnp::FlatArrayMessageReader cmsg(amsg); + cereal::Event::Reader event = cmsg.getRoot(); + if (event.isFrame()) { + std::unique_lock lk(s.lock); + s.last_frame_id = event.getFrame().getFrameId(); + lk.unlock(); + s.cv.notify_all(); + } + } + + if (ts_replace_sock.find(socks[i]) != ts_replace_sock.end()) { + // get new time + uint64_t current_time = nanos_since_boot(); + + // read out the current message + /*auto amsg = kj::heapArray((len / sizeof(capnp::word)) + 1); + memcpy(amsg.begin(), data, len); + capnp::FlatArrayMessageReader cmsg(amsg); + cereal::Event::Reader revent = cmsg.getRoot(); + + // create a copy, ugh + capnp::MallocMessageBuilder msg; + msg.setRoot(revent); + + // replace the timestamp with the current timestamp on the phone + cereal::Event::Builder event = msg.getRoot(); + + // test it's correct + auto twords = capnp::messageToFlatArray(msg); + auto tbytes = twords.asBytes(); + assert(memcmp(data, tbytes.begin(), len) == 0); + + // modify it + event.setLogMonoTime(current_time); + + // put it back + auto words = capnp::messageToFlatArray(msg); + auto bytes = words.asBytes(); + memcpy(data, bytes.begin(), len);*/ + + // binary patching HACK! + assert(memcmp(data+0xC, "\x02\x00\x01\x00", 4) == 0); + memcpy(data+0x10, ¤t_time, sizeof(current_time)); + } + + logger_log(&s.logger, data, len, qlog_counter[socks[i]] == 0); + zmq_msg_close(&msg); + + if (qlog_counter[socks[i]] != -1) { + //printf("%p: %d/%d\n", socks[i], qlog_counter[socks[i]], qlog_freqs[socks[i]]); + qlog_counter[socks[i]]++; + qlog_counter[socks[i]] %= qlog_freqs[socks[i]]; + } + + bytes_count += len; + msg_count++; + } + } + + double ts = seconds_since_boot(); + if (ts - last_rotate_ts > SEGMENT_LENGTH) { + // rotate the log + + last_rotate_ts += SEGMENT_LENGTH; + + std::lock_guard guard(s.lock); + s.rotate_last_frame_id = s.last_frame_id; + + if (is_logging) { + err = logger_next(&s.logger, LOG_ROOT, s.segment_path, sizeof(s.segment_path), &s.rotate_segment); + assert(err == 0); + LOGW("rotated to %s", s.segment_path); + } + } + + if ((msg_count%1000) == 0) { + LOGD("%lu messages, %.2f msg/sec, %.2f KB/sec", msg_count, msg_count*1.0/(ts-start_ts), bytes_count*0.001/(ts-start_ts)); + } + } + + LOGW("joining threads"); + s.cv.notify_all(); + +#ifndef DISABLE_ENCODER + front_encoder_thread_handle.join(); + encoder_thread_handle.join(); + LOGW("encoder joined"); +#endif + +#if ENABLE_LIDAR + lidar_thread_handle.join(); + LOGW("lidar joined"); +#endif + + logger_close(&s.logger); + + return 0; +} diff --git a/selfdrive/loggerd/raw_logger.cc b/selfdrive/loggerd/raw_logger.cc new file mode 100644 index 0000000000..37b3f28428 --- /dev/null +++ b/selfdrive/loggerd/raw_logger.cc @@ -0,0 +1,163 @@ +#include +#include +#include + +#include +#include + +#define __STDC_CONSTANT_MACROS + +extern "C" { +#include +#include +#include +} + +#include "common/swaglog.h" +#include "common/utilpp.h" + +#include "raw_logger.h" + +RawLogger::RawLogger(const std::string &afilename, int awidth, int aheight, int afps) + : filename(afilename), + width(awidth), + height(aheight), + fps(afps) { + + int err = 0; + + av_register_all(); + codec = avcodec_find_encoder(AV_CODEC_ID_FFVHUFF); + // codec = avcodec_find_encoder(AV_CODEC_ID_FFV1); + assert(codec); + + codec_ctx = avcodec_alloc_context3(codec); + assert(codec_ctx); + codec_ctx->width = width; + codec_ctx->height = height; + codec_ctx->pix_fmt = AV_PIX_FMT_YUV420P; + + // codec_ctx->thread_count = 2; + + // ffv1enc doesn't respect AV_PICTURE_TYPE_I. make every frame a key frame for now. + // codec_ctx->gop_size = 0; + + codec_ctx->time_base = (AVRational){ 1, fps }; + + err = avcodec_open2(codec_ctx, codec, NULL); + assert(err >= 0); + + frame = av_frame_alloc(); + assert(frame); + frame->format = codec_ctx->pix_fmt; + frame->width = width; + frame->height = height; + frame->linesize[0] = width; + frame->linesize[1] = width/2; + frame->linesize[2] = width/2; +} + +RawLogger::~RawLogger() { + av_frame_free(&frame); + avcodec_close(codec_ctx); + av_free(codec_ctx); +} + +void RawLogger::Open(const std::string &path) { + int err = 0; + + std::lock_guard guard(lock); + + vid_path = util::string_format("%s/%s.mkv", path.c_str(), filename.c_str()); + + // create camera lock file + lock_path = util::string_format("%s/%s.lock", path.c_str(), filename.c_str()); + + LOG("open %s\n", lock_path.c_str()); + + int lock_fd = open(lock_path.c_str(), O_RDWR | O_CREAT, 0777); + assert(lock_fd >= 0); + close(lock_fd); + + format_ctx = NULL; + avformat_alloc_output_context2(&format_ctx, NULL, NULL, vid_path.c_str()); + assert(format_ctx); + + stream = avformat_new_stream(format_ctx, codec); + // AVStream *stream = avformat_new_stream(format_ctx, NULL); + assert(stream); + stream->id = 0; + stream->time_base = (AVRational){ 1, fps }; + // codec_ctx->time_base = stream->time_base; + + err = avcodec_parameters_from_context(stream->codecpar, codec_ctx); + assert(err >= 0); + + err = avio_open(&format_ctx->pb, vid_path.c_str(), AVIO_FLAG_WRITE); + assert(err >= 0); + + err = avformat_write_header(format_ctx, NULL); + assert(err >= 0); + + is_open = true; + counter = 0; +} + +void RawLogger::Close() { + int err = 0; + + std::lock_guard guard(lock); + + if (!is_open) return; + + err = av_write_trailer(format_ctx); + assert(err == 0); + + avcodec_close(stream->codec); + + err = avio_closep(&format_ctx->pb); + assert(err == 0); + + avformat_free_context(format_ctx); + format_ctx = NULL; + + unlink(lock_path.c_str()); + is_open = false; +} + +int RawLogger::ProcessFrame(uint64_t ts, const uint8_t *y_ptr, const uint8_t *u_ptr, const uint8_t *v_ptr) { + int err = 0; + + AVPacket pkt; + av_init_packet(&pkt); + pkt.data = NULL; + pkt.size = 0; + + frame->data[0] = (uint8_t*)y_ptr; + frame->data[1] = (uint8_t*)u_ptr; + frame->data[2] = (uint8_t*)v_ptr; + frame->pts = ts; + + int ret = counter; + + int got_output = 0; + err = avcodec_encode_video2(codec_ctx, &pkt, frame, &got_output); + if (err) { + LOGE("encoding error\n"); + ret = -1; + } else if (got_output) { + + av_packet_rescale_ts(&pkt, codec_ctx->time_base, stream->time_base); + pkt.stream_index = 0; + + err = av_interleaved_write_frame(format_ctx, &pkt); + if (err < 0) { + LOGE("encoder writer error\n"); + ret = -1; + } else { + counter++; + } + } + + return ret; +} diff --git a/selfdrive/loggerd/raw_logger.h b/selfdrive/loggerd/raw_logger.h new file mode 100644 index 0000000000..249be40db8 --- /dev/null +++ b/selfdrive/loggerd/raw_logger.h @@ -0,0 +1,43 @@ +#ifndef FFV1LOGGER_H +#define FFV1LOGGER_H + +#include +#include + +#include +#include +#include +#include + +extern "C" { +#include +#include +#include +} + +#include "frame_logger.h" + +class RawLogger : public FrameLogger { +public: + RawLogger(const std::string &filename, int awidth, int aheight, int afps); + ~RawLogger(); + + int ProcessFrame(uint64_t ts, const uint8_t *y_ptr, const uint8_t *u_ptr, const uint8_t *v_ptr); + void Open(const std::string &path); + void Close(); + +private: + std::string filename; + int width, height, fps; + int counter = 0; + + AVCodec *codec = NULL; + AVCodecContext *codec_ctx = NULL; + + AVStream *stream = NULL; + AVFormatContext *format_ctx = NULL; + + AVFrame *frame = NULL; +}; + +#endif diff --git a/selfdrive/loggerd/tests/test_deleter.py b/selfdrive/loggerd/tests/test_deleter.py index d804b6f6ff..6e62db600f 100644 --- a/selfdrive/loggerd/tests/test_deleter.py +++ b/selfdrive/loggerd/tests/test_deleter.py @@ -44,7 +44,7 @@ class TestDeleter(UploaderTestCase): with Timeout(5, "Timeout waiting for file to be deleted"): while os.path.exists(f_path): - time.sleep(0.5) + time.sleep(0.01) self.join_thread() self.assertFalse(os.path.exists(f_path), "File not deleted") @@ -60,7 +60,7 @@ class TestDeleter(UploaderTestCase): with Timeout(5, "Timeout waiting for file to be deleted"): while os.path.exists(f_path_1) and os.path.exists(f_path_2): - time.sleep(0.5) + time.sleep(0.01) self.join_thread() @@ -79,7 +79,7 @@ class TestDeleter(UploaderTestCase): try: with Timeout(2, "Timeout waiting for file to be deleted"): while os.path.exists(f_path): - time.sleep(0.5) + time.sleep(0.01) except TimeoutException: pass finally: @@ -95,7 +95,7 @@ class TestDeleter(UploaderTestCase): try: with Timeout(2, "Timeout waiting for file to be deleted"): while os.path.exists(f_path): - time.sleep(0.5) + time.sleep(0.01) except TimeoutException: pass finally: diff --git a/selfdrive/loggerd/uploader.py b/selfdrive/loggerd/uploader.py index d65a2d5613..7cad71bf7d 100644 --- a/selfdrive/loggerd/uploader.py +++ b/selfdrive/loggerd/uploader.py @@ -139,30 +139,29 @@ class Uploader(object): total_size += os.stat(fn).st_size return dict(name_counts), total_size - def next_file_to_compress(self): + def next_file_to_upload(self, with_raw): + # try to upload qlog files first for name, key, fn in self.gen_upload_files(): - if name.endswith("log"): + if name == "qlog.bz2": return (key, fn, 0) - return None - def next_file_to_upload(self, with_video): - # try to upload log files first - for name, key, fn in self.gen_upload_files(): - if name == "rlog.bz2": - return (key, fn, 0) + if with_raw: + # then upload log files + for name, key, fn in self.gen_upload_files(): + if name == "rlog.bz2": + return (key, fn, 1) - if with_video: - # then upload compressed rear and front camera files + # then upload rear and front camera files for name, key, fn in self.gen_upload_files(): if name == "fcamera.hevc": - return (key, fn, 1) - elif name == "dcamera.hevc": return (key, fn, 2) + elif name == "dcamera.hevc": + return (key, fn, 3) # then upload other files for name, key, fn in self.gen_upload_files(): if not name.endswith('.lock') and not name.endswith(".tmp"): - return (key, fn, 3) + return (key, fn, 4) return None @@ -199,21 +198,6 @@ class Uploader(object): return self.last_resp - def compress(self, key, fn): - # write out the bz2 compress - if fn.endswith("log"): - ext = ".bz2" - cloudlog.info("compressing %r to %r", fn, fn+ext) - if os.system("nice -n 19 bzip2 -c %s > %s.tmp && mv %s.tmp %s%s && rm %s" % (fn, fn, fn, fn, ext, fn)) != 0: - cloudlog.exception("upload: bzip2 compression failed") - return False - - # assuming file is named properly - key += ext - fn += ext - - return (key, fn) - def upload(self, key, fn): try: sz = os.path.getsize(fn) @@ -234,7 +218,13 @@ class Uploader(object): stat = self.normal_upload(key, fn) if stat is not None and stat.status_code in (200, 201): cloudlog.event("upload_success", key=key, fn=fn, sz=sz) - os.unlink(fn) # delete the file + + # delete the file + try: + os.unlink(fn) + except OSError: + cloudlog.exception("delete_failed", stat=stat, exc=self.last_exc, key=key, fn=fn, sz=sz) + success = True else: cloudlog.event("upload_failed", stat=stat, exc=self.last_exc, key=key, fn=fn, sz=sz) @@ -260,6 +250,7 @@ def uploader_fn(exit_event): backoff = 0.1 while True: + allow_raw_upload = (params.get("IsUploadRawEnabled") != "0") allow_cellular = (params.get("IsUploadVideoOverCellularEnabled") != "0") on_hotspot = is_on_hotspot() on_wifi = is_on_wifi() @@ -268,17 +259,7 @@ def uploader_fn(exit_event): if exit_event.is_set(): return - d = uploader.next_file_to_compress() - if d is not None: - key, fn, _ = d - uploader.compress(key, fn) - continue - - if not should_upload: - time.sleep(5) - continue - - d = uploader.next_file_to_upload(with_video=True) + d = uploader.next_file_to_upload(with_raw=allow_raw_upload and should_upload) if d is None: time.sleep(5) continue diff --git a/selfdrive/logmessaged.py b/selfdrive/logmessaged.py index fb4a2bedf0..c2c583dfc5 100755 --- a/selfdrive/logmessaged.py +++ b/selfdrive/logmessaged.py @@ -4,19 +4,19 @@ from logentries import LogentriesHandler from selfdrive.services import service_list import selfdrive.messaging as messaging -def main(gctx): +def main(gctx=None): # setup logentries. we forward log messages to it le_token = "e8549616-0798-4d7e-a2ca-2513ae81fa17" le_handler = LogentriesHandler(le_token, use_tls=False, verbose=False) le_level = 20 #logging.INFO - ctx = zmq.Context() + ctx = zmq.Context().instance() sock = ctx.socket(zmq.PULL) sock.bind("ipc:///tmp/logmessage") # and we publish them - pub_sock = messaging.pub_sock(ctx, service_list['logMessage'].port) + pub_sock = messaging.pub_sock(service_list['logMessage'].port) while True: dat = ''.join(sock.recv_multipart()) @@ -37,4 +37,4 @@ def main(gctx): pub_sock.send(msg.to_bytes()) if __name__ == "__main__": - main(None) + main() diff --git a/selfdrive/manager.py b/selfdrive/manager.py index 30e413c30b..c3be2c094d 100755 --- a/selfdrive/manager.py +++ b/selfdrive/manager.py @@ -41,8 +41,14 @@ def unblock_stdout(): os._exit(os.wait()[1]) if __name__ == "__main__": - neos_update_required = os.path.isfile("/init.qcom.rc") \ - and (not os.path.isfile("/VERSION") or int(open("/VERSION").read()) < 9) + is_neos = os.path.isfile("/init.qcom.rc") + neos_update_required = False + + if is_neos: + version = int(open("/VERSION").read()) if os.path.isfile("/VERSION") else 0 + revision = int(open("/REVISION").read()) if version >= 10 else 0 # Revision only present in NEOS 10 and up + neos_update_required = version < 10 or (version == 10 and revision != 3) + if neos_update_required: # update continue.sh before updating NEOS if os.path.isfile(os.path.join(BASEDIR, "scripts", "continue.sh")): @@ -52,7 +58,9 @@ if __name__ == "__main__": # run the updater print("Starting NEOS updater") subprocess.check_call(["git", "clean", "-xdf"], cwd=BASEDIR) - os.system(os.path.join(BASEDIR, "installer", "updater", "updater")) + updater_dir = os.path.join(BASEDIR, "installer", "updater") + manifest_path = os.path.realpath(os.path.join(updater_dir, "update.json")) + os.system(os.path.join(updater_dir, "updater") + " file://" + manifest_path) raise Exception("NEOS outdated") elif os.path.isdir("/data/neoupdate"): from shutil import rmtree @@ -68,7 +76,6 @@ import subprocess import traceback from multiprocessing import Process -import zmq from setproctitle import setproctitle #pylint: disable=no-name-in-module from common.params import Params @@ -102,10 +109,10 @@ managed_processes = { "pandad": "selfdrive.pandad", "ui": ("selfdrive/ui", ["./start.py"]), "calibrationd": "selfdrive.locationd.calibrationd", - "locationd": "selfdrive.locationd.locationd_local", + "params_learner": ("selfdrive/locationd", ["./params_learner"]), "visiond": ("selfdrive/visiond", ["./visiond"]), - "sensord": ("selfdrive/sensord", ["./sensord"]), - "gpsd": ("selfdrive/sensord", ["./gpsd"]), + "sensord": ("selfdrive/sensord", ["./start_sensord.py"]), + "gpsd": ("selfdrive/sensord", ["./start_gpsd.py"]), "updated": "selfdrive.updated", "athena": "selfdrive.athena.athenad", } @@ -139,7 +146,7 @@ car_started_processes = [ 'sensord', 'radard', 'calibrationd', - 'locationd', + 'params_learner', 'visiond', 'proclogd', 'ubloxd', @@ -157,7 +164,7 @@ def register_managed_process(name, desc, car_started=False): persistent_processes.append(name) # ****************** process management functions ****************** -def launcher(proc, gctx): +def launcher(proc): try: # import the process mod = importlib.import_module(proc) @@ -165,8 +172,12 @@ def launcher(proc, gctx): # rename the process setproctitle(proc) + # terminate the zmq context since we forked + import zmq + zmq.Context.instance().term() + # exec the process - mod.main(gctx) + mod.main() except KeyboardInterrupt: cloudlog.warning("child %s got SIGINT" % proc) except Exception: @@ -190,7 +201,7 @@ def start_managed_process(name): proc = managed_processes[name] if isinstance(proc, str): cloudlog.info("starting python %s" % proc) - running[name] = Process(name=name, target=launcher, args=(proc, gctx)) + running[name] = Process(name=name, target=launcher, args=(proc,)) else: pdir, pargs = proc cwd = os.path.join(BASEDIR, pdir) @@ -262,8 +273,6 @@ def cleanup_all_processes(signal, frame): # ****************** run loop ****************** def manager_init(should_register=True): - global gctx - if should_register: reg_res = register() if reg_res: @@ -291,9 +300,6 @@ def manager_init(should_register=True): except OSError: pass - # set gctx - gctx = {} - def system(cmd): try: cloudlog.info("running %s" % cmd) @@ -307,8 +313,7 @@ def system(cmd): def manager_thread(): # now loop - context = zmq.Context() - thermal_sock = messaging.sub_sock(context, service_list['thermal'].port) + thermal_sock = messaging.sub_sock(service_list['thermal'].port) cloudlog.info("manager start") cloudlog.info({"environ": os.environ}) @@ -479,6 +484,8 @@ def main(): params.put("IsFcwEnabled", "1") if params.get("HasAcceptedTerms") is None: params.put("HasAcceptedTerms", "0") + if params.get("IsUploadRawEnabled") is None: + params.put("IsUploadRawEnabled", "1") if params.get("IsUploadVideoOverCellularEnabled") is None: params.put("IsUploadVideoOverCellularEnabled", "1") if params.get("IsDriverMonitoringEnabled") is None: diff --git a/selfdrive/messaging.py b/selfdrive/messaging.py index 4811f93454..4e78f66c81 100644 --- a/selfdrive/messaging.py +++ b/selfdrive/messaging.py @@ -1,19 +1,23 @@ import zmq from cereal import log -from common import realtime +from common.realtime import sec_since_boot +from selfdrive.services import service_list def new_message(): dat = log.Event.new_message() - dat.logMonoTime = int(realtime.sec_since_boot() * 1e9) + dat.logMonoTime = int(sec_since_boot() * 1e9) + dat.valid = True return dat -def pub_sock(context, port, addr="*"): +def pub_sock(port, addr="*"): + context = zmq.Context.instance() sock = context.socket(zmq.PUB) sock.bind("tcp://%s:%d" % (addr, port)) return sock -def sub_sock(context, port, poller=None, addr="127.0.0.1", conflate=False): +def sub_sock(port, poller=None, addr="127.0.0.1", conflate=False): + context = zmq.Context.instance() sock = context.socket(zmq.SUB) if conflate: sock.setsockopt(zmq.CONFLATE, 1) @@ -61,3 +65,68 @@ def recv_one_or_none(sock): return log.Event.from_bytes(sock.recv(zmq.NOBLOCK)) except zmq.error.Again: return None + + +class SubMaster(): + def __init__(self, services, addr="127.0.0.1"): + self.poller = zmq.Poller() + self.frame = -1 + self.updated = {s : False for s in services} + self.rcv_time = {s : 0. for s in services} + self.rcv_frame = {s : 0 for s in services} + self.alive = {s : False for s in services} + self.sock = {} + self.freq = {} + self.data = {} + self.logMonoTime = {} + self.valid = {} + for s in services: + # TODO: get address automatically from service_list + self.sock[s] = sub_sock(service_list[s].port, poller=self.poller, addr=addr, conflate=True) + self.freq[s] = service_list[s].frequency + data = new_message() + data.init(s) + self.data[s] = getattr(data, s) + self.logMonoTime[s] = data.logMonoTime + self.valid[s] = data.valid + + def __getitem__(self, s): + return self.data[s] + + def update(self, timeout=-1): + # TODO: add optional input that specify the service to wait for + self.frame += 1 + self.updated = dict.fromkeys(self.updated, False) + cur_time = sec_since_boot() + for sock, _ in self.poller.poll(timeout): + msg = recv_one(sock) + s = msg.which() + self.updated[s] = True + self.rcv_time[s] = cur_time + self.rcv_frame[s] = self.frame + self.data[s] = getattr(msg, s) + self.logMonoTime[s] = msg.logMonoTime + self.valid[s] = msg.valid + + for s in self.data: + # arbitrary small number to avoid float comparison. If freq is 0, we can skip the check + if self.freq[s] > 1e-5: + # alive if delay is within 10x the expected frequency + self.alive[s] = (cur_time - self.rcv_time[s]) < (10. / self.freq[s]) + else: + self.alive[s] = True + + def all_alive(self, service_list=None): + if service_list is None: # check all + service_list = self.alive.keys() + return all(self.alive[s] for s in service_list) + + def all_valid(self, service_list=None): + if service_list is None: # check all + service_list = self.valid.keys() + return all(self.valid[s] for s in service_list) + + def all_alive_and_valid(self, service_list=None): + if service_list is None: # check all + service_list = self.alive.keys() + return self.all_alive(service_list=service_list) and self.all_valid(service_list=service_list) diff --git a/selfdrive/pandad.py b/selfdrive/pandad.py old mode 100644 new mode 100755 index 981546ccf9..09f2e717f9 --- a/selfdrive/pandad.py +++ b/selfdrive/pandad.py @@ -1,14 +1,76 @@ -#!/usr/bin/env python +#!/usr/bin/env python2 # simple boardd wrapper that updates the panda first import os -from panda import ensure_st_up_to_date +import time + +from selfdrive.swaglog import cloudlog +from panda import Panda, PandaDFU, BASEDIR + + +def update_panda(): + with open(os.path.join(BASEDIR, "VERSION")) as f: + repo_version = f.read() + repo_version += "-EON" if os.path.isfile('/EON') else "-DEV" + + panda = None + panda_dfu = None + + cloudlog.info("Connecting to panda") + + while True: + # break on normal mode Panda + panda_list = Panda.list() + if len(panda_list) > 0: + cloudlog.info("Panda found, connecting") + panda = Panda(panda_list[0]) + break + + # flash on DFU mode Panda + panda_dfu = PandaDFU.list() + if len(panda_dfu) > 0: + cloudlog.info("Panda in DFU mode found, flashing recovery") + panda_dfu = PandaDFU(panda_dfu[0]) + panda_dfu.recover() + + print "waiting for board..." + time.sleep(1) + + current_version = "bootstub" if panda.bootstub else str(panda.get_version()) + cloudlog.info("Panda connected, version: %s, expected %s" % (current_version, repo_version)) + + if panda.bootstub or not current_version.startswith(repo_version): + cloudlog.info("Panda firmware out of date, update required") + + signed_fn = os.path.join(BASEDIR, "board", "obj", "panda.bin.signed") + if os.path.exists(signed_fn): + cloudlog.info("Flashing signed firmware") + panda.flash(fn=signed_fn) + else: + cloudlog.info("Building and flashing unsigned firmware") + panda.flash() + + cloudlog.info("Done flashing") + + if panda.bootstub: + cloudlog.info("Flashed firmware not booting, flashing development bootloader") + panda.recover() + cloudlog.info("Done flashing bootloader") + + if panda.bootstub: + cloudlog.info("Panda still not booting, exiting") + raise AssertionError + + version = str(panda.get_version()) + if not version.startswith(repo_version): + cloudlog.info("Version mismatch after flashing, exiting") + raise AssertionError + def main(gctx=None): - ensure_st_up_to_date() + update_panda() os.chdir("boardd") os.execvp("./boardd", ["./boardd"]) if __name__ == "__main__": main() - diff --git a/selfdrive/proclogd/Makefile b/selfdrive/proclogd/Makefile index a7cd3682b2..9939a715f3 100644 --- a/selfdrive/proclogd/Makefile +++ b/selfdrive/proclogd/Makefile @@ -1,3 +1,5 @@ +ARCH := $(shell uname -m) + CC = clang CXX = clang++ @@ -13,10 +15,15 @@ WARN_FLAGS = -Werror=implicit-function-declaration \ CFLAGS = -std=gnu11 -g -fPIC -O2 $(WARN_FLAGS) CXXFLAGS = -std=c++11 -g -fPIC -O2 $(WARN_FLAGS) -ZMQ_FLAGS = -I$(PHONELIBS)/zmq/aarch64/include -ZMQ_LIBS = -L$(PHONELIBS)/zmq/aarch64/lib \ - -l:libczmq.a -l:libzmq.a \ - -lgnustl_shared +ZMQ_LIBS = -l:libczmq.a -l:libzmq.a + +ifeq ($(ARCH),aarch64) +CFLAGS += -mcpu=cortex-a57 +CXXFLAGS += -mcpu=cortex-a57 +ZMQ_LIBS += -lgnustl_shared +endif + +#ZMQ_FLAGS = -I$(PHONELIBS)/zmq/aarch64/include .PHONY: all all: proclogd diff --git a/selfdrive/registration.py b/selfdrive/registration.py index 9e4c89b4cd..9f68998499 100644 --- a/selfdrive/registration.py +++ b/selfdrive/registration.py @@ -2,7 +2,6 @@ import os import json import subprocess import struct -import jwt from datetime import datetime, timedelta from selfdrive.swaglog import cloudlog @@ -66,7 +65,8 @@ def register(): if not os.path.isfile("/persist/comma/id_rsa.pub"): cloudlog.warning("generating your personal RSA key") mkdirs_exists_ok("/persist/comma") - assert os.system("echo -e 'y\n' | ssh-keygen -t rsa -b 2048 -f /persist/comma/id_rsa.tmp -N ''") == 0 + assert os.system("openssl genrsa -out /persist/comma/id_rsa.tmp 2048") == 0 + assert os.system("openssl rsa -in /persist/comma/id_rsa.tmp -pubout -out /persist/comma/id_rsa.tmp.pub") == 0 os.rename("/persist/comma/id_rsa.tmp", "/persist/comma/id_rsa") os.rename("/persist/comma/id_rsa.tmp.pub", "/persist/comma/id_rsa.pub") @@ -76,6 +76,9 @@ def register(): # create registration token # in the future, this key will make JWTs directly private_key = open("/persist/comma/id_rsa").read() + + # late import + import jwt register_token = jwt.encode({'register':True, 'exp': datetime.utcnow() + timedelta(hours=1)}, private_key, algorithm='RS256') try: diff --git a/selfdrive/sensord/build_from_src.mk b/selfdrive/sensord/build_from_src.mk new file mode 100644 index 0000000000..8c71f5f96d --- /dev/null +++ b/selfdrive/sensord/build_from_src.mk @@ -0,0 +1,88 @@ +CC = clang +CXX = clang++ + +PHONELIBS = ../../phonelibs +BASEDIR = ../.. + +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) \ + -I$(PHONELIBS)/android_frameworks_native/include \ + -I$(PHONELIBS)/android_system_core/include \ + -I$(PHONELIBS)/android_hardware_libhardware/include +CXXFLAGS = -std=c++11 -g -fPIC -O2 $(WARN_FLAGS) \ + -I$(PHONELIBS)/android_frameworks_native/include \ + -I$(PHONELIBS)/android_system_core/include \ + -I$(PHONELIBS)/android_hardware_libhardware/include + +ZMQ_LIBS = -l:libczmq.a -l:libzmq.a -llog -luuid -lgnustl_shared + +ifeq ($(ARCH),aarch64) +CFLAGS += -mcpu=cortex-a57 +CXXFLAGS += -mcpu=cortex-a57 +endif + + +JSON_FLAGS = -I$(PHONELIBS)/json/src + +DIAG_LIBS = -L/system/vendor/lib64 -ldiag -ltime_genoff + +.PHONY: all +all: sensord gpsd + +include ../common/cereal.mk + +SENSORD_OBJS = sensors.o \ + ../common/swaglog.o \ + $(PHONELIBS)/json/src/json.o + +GPSD_OBJS = gpsd.o \ + rawgps.o \ + ../common/swaglog.o \ + $(PHONELIBS)/json/src/json.o + +DEPS := $(SENSORD_OBJS:.o=.d) $(GPSD_OBJS:.o=.d) + +sensord: $(SENSORD_OBJS) + @echo "[ LINK ] $@" + $(CXX) -fPIC -o '$@' $^ \ + $(CEREAL_LIBS) \ + $(ZMQ_LIBS) \ + -lhardware + +gpsd: $(GPSD_OBJS) + @echo "[ LINK ] $@" + $(CXX) -fPIC -o '$@' $^ \ + $(CEREAL_LIBS) \ + $(ZMQ_LIBS) \ + $(DIAG_LIBS) \ + -lhardware + +%.o: %.cc + @echo "[ CXX ] $@" + $(CXX) $(CXXFLAGS) \ + $(CEREAL_CXXFLAGS) \ + $(ZMQ_FLAGS) \ + $(JSON_FLAGS) \ + -I../ \ + -I../../ \ + -c -o '$@' '$<' + + +%.o: %.c + @echo "[ CC ] $@" + $(CC) $(CFLAGS) \ + $(JSON_FLAGS) \ + -I../ \ + -I../../ \ + -c -o '$@' '$<' + +.PHONY: clean +clean: + rm -f sensord gpsd $(OBJS) $(DEPS) + +-include $(DEPS) diff --git a/selfdrive/sensord/gpsd b/selfdrive/sensord/gpsd deleted file mode 100755 index 78c105a7d8..0000000000 Binary files a/selfdrive/sensord/gpsd and /dev/null differ diff --git a/selfdrive/sensord/gpsd.cc b/selfdrive/sensord/gpsd.cc new file mode 100644 index 0000000000..6bf7a6a9e1 --- /dev/null +++ b/selfdrive/sensord/gpsd.cc @@ -0,0 +1,268 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include +#include + +#include + +#include + +#include "common/timing.h" +#include "common/swaglog.h" + +#include "cereal/gen/cpp/log.capnp.h" + +#include "rawgps.h" + +volatile int do_exit = 0; + +namespace { + +pthread_t clock_thread_handle; + +// zmq output +void *gps_context; +void *gps_publisher; +void *gps_location_publisher; + +const GpsInterface* gGpsInterface = NULL; +const AGpsInterface* gAGpsInterface = NULL; + +void set_do_exit(int sig) { + do_exit = 1; +} + +void nmea_callback(GpsUtcTime timestamp, const char* nmea, int length) { + + uint64_t log_time = nanos_since_boot(); + uint64_t log_time_wall = nanos_since_epoch(); + + capnp::MallocMessageBuilder msg; + cereal::Event::Builder event = msg.initRoot(); + event.setLogMonoTime(log_time); + + auto nmeaData = event.initGpsNMEA(); + nmeaData.setTimestamp(timestamp); + nmeaData.setLocalWallTime(log_time_wall); + nmeaData.setNmea(nmea); + + auto words = capnp::messageToFlatArray(msg); + auto bytes = words.asBytes(); + // printf("gps send %d\n", bytes.size()); + zmq_send(gps_publisher, bytes.begin(), bytes.size(), 0); +} + +void location_callback(GpsLocation* location) { + //printf("got location callback\n"); + uint64_t log_time = nanos_since_boot(); + + capnp::MallocMessageBuilder msg; + cereal::Event::Builder event = msg.initRoot(); + event.setLogMonoTime(log_time); + + auto locationData = event.initGpsLocation(); + locationData.setFlags(location->flags); + locationData.setLatitude(location->latitude); + locationData.setLongitude(location->longitude); + locationData.setAltitude(location->altitude); + locationData.setSpeed(location->speed); + locationData.setBearing(location->bearing); + locationData.setAccuracy(location->accuracy); + locationData.setTimestamp(location->timestamp); + locationData.setSource(cereal::GpsLocationData::SensorSource::ANDROID); + + auto words = capnp::messageToFlatArray(msg); + auto bytes = words.asBytes(); + zmq_send(gps_location_publisher, bytes.begin(), bytes.size(), 0); +} + +pthread_t create_thread_callback(const char* name, void (*start)(void *), void* arg) { + LOG("creating thread: %s", name); + pthread_t thread; + pthread_attr_t attr; + int err; + + err = pthread_attr_init(&attr); + err = pthread_create(&thread, &attr, (void*(*)(void*))start, arg); + + return thread; +} + +GpsCallbacks gps_callbacks = { + sizeof(GpsCallbacks), + location_callback, + NULL, + NULL, + nmea_callback, + NULL, + NULL, + NULL, + create_thread_callback, +}; + +void agps_status_cb(AGpsStatus *status) { + switch (status->status) { + case GPS_REQUEST_AGPS_DATA_CONN: + fprintf(stdout, "*** data_conn_open\n"); + gAGpsInterface->data_conn_open("internet"); + break; + case GPS_RELEASE_AGPS_DATA_CONN: + fprintf(stdout, "*** data_conn_closed\n"); + gAGpsInterface->data_conn_closed(); + break; + } +} + +AGpsCallbacks agps_callbacks = { + agps_status_cb, + create_thread_callback, +}; + + + +void gps_init() { + LOG("*** init GPS"); + hw_module_t* module = NULL; + hw_get_module(GPS_HARDWARE_MODULE_ID, (hw_module_t const**)&module); + assert(module); + + static hw_device_t* device = NULL; + module->methods->open(module, GPS_HARDWARE_MODULE_ID, &device); + assert(device); + + // ** get gps interface ** + gps_device_t* gps_device = (gps_device_t *)device; + gGpsInterface = gps_device->get_gps_interface(gps_device); + assert(gGpsInterface); + + gAGpsInterface = (const AGpsInterface*)gGpsInterface->get_extension(AGPS_INTERFACE); + assert(gAGpsInterface); + + + gGpsInterface->init(&gps_callbacks); + gAGpsInterface->init(&agps_callbacks); + gAGpsInterface->set_server(AGPS_TYPE_SUPL, "supl.google.com", 7276); + + // gGpsInterface->delete_aiding_data(GPS_DELETE_ALL); + gGpsInterface->start(); + gGpsInterface->set_position_mode(GPS_POSITION_MODE_MS_BASED, + GPS_POSITION_RECURRENCE_PERIODIC, + 100, 0, 0); + + gps_context = zmq_ctx_new(); + gps_publisher = zmq_socket(gps_context, ZMQ_PUB); + zmq_bind(gps_publisher, "tcp://*:8004"); + + gps_location_publisher = zmq_socket(gps_context, ZMQ_PUB); + zmq_bind(gps_location_publisher, "tcp://*:8026"); +} + +void gps_destroy() { + gGpsInterface->stop(); + gGpsInterface->cleanup(); +} + + +int64_t arm_cntpct() { + int64_t v; + asm volatile("mrs %0, cntpct_el0" : "=r"(v)); + return v; +} + +// TODO: move this out of here +void* clock_thread(void* args) { + int err = 0; + + void* clock_publisher = zmq_socket(gps_context, ZMQ_PUB); + zmq_bind(clock_publisher, "tcp://*:8034"); + + int timerfd = timerfd_create(CLOCK_BOOTTIME, 0); + assert(timerfd >= 0); + + struct itimerspec spec = {0}; + spec.it_interval.tv_sec = 1; + spec.it_interval.tv_nsec = 0; + spec.it_value.tv_sec = 1; + spec.it_value.tv_nsec = 0; + + err = timerfd_settime(timerfd, 0, &spec, 0); + assert(err == 0); + + uint64_t expirations = 0; + while ((err = read(timerfd, &expirations, sizeof(expirations)))) { + if (err < 0) break; + + if (do_exit) break; + + uint64_t boottime = nanos_since_boot(); + uint64_t monotonic = nanos_monotonic(); + uint64_t monotonic_raw = nanos_monotonic_raw(); + uint64_t wall_time = nanos_since_epoch(); + + uint64_t modem_uptime_v = arm_cntpct() / 19200ULL; // 19.2 mhz clock + + capnp::MallocMessageBuilder msg; + cereal::Event::Builder event = msg.initRoot(); + event.setLogMonoTime(boottime); + auto clocks = event.initClocks(); + + clocks.setBootTimeNanos(boottime); + clocks.setMonotonicNanos(monotonic); + clocks.setMonotonicRawNanos(monotonic_raw); + clocks.setWallTimeNanos(wall_time); + clocks.setModemUptimeMillis(modem_uptime_v); + + auto words = capnp::messageToFlatArray(msg); + auto bytes = words.asBytes(); + zmq_send(clock_publisher, bytes.begin(), bytes.size(), 0); + } + + close(timerfd); + zmq_close(clock_publisher); + + return NULL; +} + + +} + +int main() { + int err = 0; + setpriority(PRIO_PROCESS, 0, -13); + + signal(SIGINT, (sighandler_t)set_do_exit); + signal(SIGTERM, (sighandler_t)set_do_exit); + + gps_init(); + + rawgps_init(); + + err = pthread_create(&clock_thread_handle, NULL, + clock_thread, NULL); + assert(err == 0); + + while(!do_exit) pause(); + + err = pthread_join(clock_thread_handle, NULL); + assert(err == 0); + + rawgps_destroy(); + + gps_destroy(); + + return 0; +} diff --git a/selfdrive/sensord/libdiag.h b/selfdrive/sensord/libdiag.h new file mode 100644 index 0000000000..ab3ee91b14 --- /dev/null +++ b/selfdrive/sensord/libdiag.h @@ -0,0 +1,40 @@ +#ifndef LIBDIAG_H +#define LIBDIAG_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define DIAG_MAX_RX_PKT_SIZ 4096 + +bool Diag_LSM_Init(uint8_t* pIEnv); +bool Diag_LSM_DeInit(void); + +// DCI + +#define DIAG_CON_APSS 0x001 +#define DIAG_CON_MPSS 0x002 +#define DIAG_CON_LPASS 0x004 +#define DIAG_CON_WCNSS 0x008 + +enum { + DIAG_DCI_NO_ERROR = 1001, +} diag_dci_error_type; + +int diag_register_dci_client(int*, uint16_t*, int, void*); +int diag_log_stream_config(int client_id, int set_mask, uint16_t log_codes_array[], int num_codes); +int diag_register_dci_stream(void (*func_ptr_logs)(unsigned char *ptr, int len), void (*func_ptr_events)(unsigned char *ptr, int len)); +int diag_release_dci_client(int*); + +int diag_send_dci_async_req(int client_id, unsigned char buf[], int bytes, unsigned char *rsp_ptr, int rsp_len, + void (*func_ptr)(unsigned char *ptr, int len, void *data_ptr), void *data_ptr); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/selfdrive/sensord/rawgps.cc b/selfdrive/sensord/rawgps.cc new file mode 100644 index 0000000000..91e5562c7d --- /dev/null +++ b/selfdrive/sensord/rawgps.cc @@ -0,0 +1,1189 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "cereal/gen/cpp/log.capnp.h" + +#include "common/timing.h" +#include "common/util.h" +#include "common/swaglog.h" + +#include "libdiag.h" + +extern volatile int do_exit; + +#define NV_GNSS_OEM_FEATURE_MASK 7165 +# define NV_GNSS_OEM_FEATURE_MASK_OEMDRE 1 +#define NV_CGPS_DPO_CONTROL 5596 + +#define DIAG_NV_READ_F 38 +#define DIAG_NV_WRITE_F 39 + +#define DIAG_SUBSYS_CMD 75 +#define DIAG_SUBSYS_CMD_VER_2 128 + +#define DIAG_SUBSYS_GPS 13 +#define DIAG_SUBSYS_FS 19 + +#define CGPS_DIAG_PDAPI_CMD 100 +#define CGPS_OEM_CONTROL 202 + +#define GPSDIAG_OEMFEATURE_DRE 1 +#define GPSDIAG_OEM_DRE_ON 1 + +#define FEATURE_OEMDRE_NOT_SUPPORTED 1 +#define FEATURE_OEMDRE_ON 2 +#define FEATURE_OEMDRE_ALREADY_ON 4 + +#define TM_DIAG_NAV_CONFIG_CMD 0x6E + +#define EFS2_DIAG_SYNC_NO_WAIT 48 + +struct __attribute__((packed)) NvPacket { + uint8_t cmd_code; + uint16_t nv_id; + uint8_t data[128]; + uint16_t status; +}; + +enum NvStatus { + NV_DONE, + NV_BUSY, + NV_FULL, + NV_FAIL, + NV_NOTACTIVE, + NV_BADPARAM, + NV_READONLY, + NV_BADRG, + NV_NOMEM, + NV_NOTALLOC, +}; + +struct __attribute__((packed)) Efs2DiagSyncReq { + uint8_t cmd_code; + uint8_t subsys_id; + uint16_t subsys_cmd_code; + uint16_t sequence_num; + char path[8]; +}; + + +struct __attribute__((packed)) Efs2DiagSyncResp { + uint8_t cmd_code; + uint8_t subsys_id; + uint16_t subsys_cmd_code; + uint16_t sequence_num; + uint32_t sync_token; + int32_t diag_errno; +}; + + + +struct __attribute__((packed)) GpsOemControlReq { + uint8_t cmd_code; + uint8_t subsys_id; + uint16_t subsys_cmd_code; + uint8_t gps_cmd_code; + uint8_t version; + + uint32_t oem_feature; + uint32_t oem_command; + uint32_t reserved[2]; +}; + + +struct __attribute__((packed)) GpsOemControlResp { + uint8_t cmd_code; + uint8_t subsys_id; + uint16_t subsys_cmd_code; + uint8_t gps_cmd_code; + uint8_t version; + + uint32_t oem_feature; + uint32_t oem_command; + uint32_t resp_result; + uint32_t reserved[2]; +}; + +struct __attribute__((packed)) GpsNavConfigReq { + uint8_t cmd_code; + uint8_t subsys_id; + uint16_t subsys_cmd_code; + uint32_t subsys_status; + uint16_t subsys_delayed_resp_id; + uint16_t subsys_rsp_cnt; + + uint8_t desired_config; +}; + +struct __attribute__((packed)) GpsNavConfigResp { + uint8_t cmd_code; + uint8_t subsys_id; + uint16_t subsys_cmd_code; + uint32_t subsys_status; + uint16_t subsys_delayed_resp_id; + uint16_t subsys_rsp_cnt; + + uint8_t supported_config; + uint8_t actual_config; +}; + + +#define LOG_GNSS_POSITION_REPORT 0x1476 +#define LOG_GNSS_GPS_MEASUREMENT_REPORT 0x1477 +#define LOG_GNSS_CLOCK_REPORT 0x1478 +#define LOG_GNSS_GLONASS_MEASUREMENT_REPORT 0x1480 +#define LOG_GNSS_BDS_MEASUREMENT_REPORT 0x1756 +#define LOG_GNSS_GAL_MEASUREMENT_REPORT 0x1886 + +#define LOG_GNSS_OEMDRE_MEASUREMENMT_REPORT 0x14DE +#define LOG_GNSS_OEMDRE_SVPOLY_REPORT 0x14E1 + +#define LOG_GNSS_ME_DPO_STATUS 0x1838 +#define LOG_GNSS_CD_DB_REPORT 0x147B +#define LOG_GNSS_PRX_RF_HW_STATUS_REPORT 0x147E +#define LOG_CGPS_SLOW_CLOCK_CLIB_REPORT 0x1488 +#define LOG_GNSS_CONFIGURATION_STATE 0x1516 + +struct __attribute__((packed)) log_header_type { + uint16_t len; + uint16_t code; + uint64_t ts; +}; + + + +enum SVObservationStates { + SV_IDLE, + SV_SEARCH, + SV_SEACH_VERIFY, + SV_BIT_EDGE, + SV_TRACK_VERIFY, + SV_TRACK, + SV_RESTART, + SV_DPO, + SV_GLO_10ms_BE, + SV_GLO_10ms_AT, +}; + +struct __attribute__((packed)) GNSSGpsMeasurementReportv0_SV{ + uint8_t sv_id; + uint8_t observation_state; // SVObservationStates + uint8_t observations; + uint8_t good_observations; + uint16_t parity_error_count; + uint8_t filter_stages; + uint16_t carrier_noise; + int16_t latency; + uint8_t predetect_interval; + uint16_t postdetections; + uint32_t unfiltered_measurement_integral; + float unfiltered_measurement_fraction; + float unfiltered_time_uncertainty; + float unfiltered_speed; + float unfiltered_speed_uncertainty; + uint32_t measurement_status; + uint8_t misc_status; + uint32_t multipath_estimate; + float azimuth; + float elevation; + int32_t carrier_phase_cycles_integral; + uint16_t carrier_phase_cycles_fraction; + float fine_speed; + float fine_speed_uncertainty; + uint8_t cycle_slip_count; + uint32_t pad; +}; + +_Static_assert(sizeof(GNSSGpsMeasurementReportv0_SV) == 70, "error"); + +struct __attribute__((packed)) GNSSGpsMeasurementReportv0{ + log_header_type header; + uint8_t version; + uint32_t f_count; + uint16_t week; + uint32_t milliseconds; + float time_bias; + float clock_time_uncertainty; + float clock_frequency_bias; + float clock_frequency_uncertainty; + uint8_t sv_count; + GNSSGpsMeasurementReportv0_SV sv[]; +}; + + + +struct __attribute__((packed)) GNSSGlonassMeasurementReportv0_SV { + uint8_t sv_id; + int8_t frequency_index; + uint8_t observation_state; // SVObservationStates + uint8_t observations; + uint8_t good_observations; + uint8_t hemming_error_count; + uint8_t filter_stages; + uint16_t carrier_noise; + int16_t latency; + uint8_t predetect_interval; + uint16_t postdetections; + uint32_t unfiltered_measurement_integral; + float unfiltered_measurement_fraction; + float unfiltered_time_uncertainty; + float unfiltered_speed; + float unfiltered_speed_uncertainty; + uint32_t measurement_status; + uint8_t misc_status; + uint32_t multipath_estimate; + float azimuth; + float elevation; + int32_t carrier_phase_cycles_integral; + uint16_t carrier_phase_cycles_fraction; + float fine_speed; + float fine_speed_uncertainty; + uint8_t cycle_slip_count; + uint32_t pad; +}; + +_Static_assert(sizeof(GNSSGlonassMeasurementReportv0_SV) == 70, "error"); + +struct __attribute__((packed)) GNSSGlonassMeasurementReportv0 { + log_header_type header; + uint8_t version; + uint32_t f_count; + uint8_t glonass_cycle_number; + uint16_t glonass_number_of_days; + uint32_t milliseconds; + float time_bias; + float clock_time_uncertainty; + float clock_frequency_bias; + float clock_frequency_uncertainty; + uint8_t sv_count; + GNSSGlonassMeasurementReportv0_SV sv[]; +}; + + +struct __attribute__((packed)) GNSSClockReportv2 { + log_header_type header; + uint8_t version; + uint16_t valid_flags; + + uint32_t f_count; + + uint16_t gps_week; + uint32_t gps_milliseconds; + float gps_time_bias; + float gps_clock_time_uncertainty; + uint8_t gps_clock_source; + + uint8_t glonass_year; + uint16_t glonass_day; + uint32_t glonass_milliseconds; + float glonass_time_bias; + float glonass_clock_time_uncertainty; + uint8_t glonass_clock_source; + + uint16_t bds_week; + uint32_t bds_milliseconds; + float bds_time_bias; + float bds_clock_time_uncertainty; + uint8_t bds_clock_source; + + uint16_t gal_week; + uint32_t gal_milliseconds; + float gal_time_bias; + float gal_clock_time_uncertainty; + uint8_t gal_clock_source; + + float clock_frequency_bias; + float clock_frequency_uncertainty; + uint8_t frequency_source; + uint8_t gps_leap_seconds; + uint8_t gps_leap_seconds_uncertainty; + uint8_t gps_leap_seconds_source; + + float gps_to_glonass_time_bias_milliseconds; + float gps_to_glonass_time_bias_milliseconds_uncertainty; + float gps_to_bds_time_bias_milliseconds; + float gps_to_bds_time_bias_milliseconds_uncertainty; + float bds_to_glo_time_bias_milliseconds; + float bds_to_glo_time_bias_milliseconds_uncertainty; + float gps_to_gal_time_bias_milliseconds; + float gps_to_gal_time_bias_milliseconds_uncertainty; + float gal_to_glo_time_bias_milliseconds; + float gal_to_glo_time_bias_milliseconds_uncertainty; + float gal_to_bds_time_bias_milliseconds; + float gal_to_bds_time_bias_milliseconds_uncertainty; + + uint32_t system_rtc_time; + uint32_t f_count_offset; + uint32_t lpm_rtc_count; + uint32_t clock_resets; + + uint32_t reserved[3]; + +}; + + +enum GNSSMeasurementSource { + SOURCE_GPS, + SOURCE_GLONASS, + SOURCE_BEIDOU, +}; + +struct __attribute__((packed)) GNSSOemdreMeasurement { + uint8_t sv_id; + uint8_t unkn; + int8_t glonass_frequency_index; + uint32_t observation_state; + uint8_t observations; + uint8_t good_observations; + uint8_t filter_stages; + uint8_t predetect_interval; + uint8_t cycle_slip_count; + uint16_t postdetections; + + uint32_t measurement_status; + uint32_t measurement_status2; + + uint16_t carrier_noise; + uint16_t rf_loss; + int16_t latency; + + float filtered_measurement_fraction; + uint32_t filtered_measurement_integral; + float filtered_time_uncertainty; + float filtered_speed; + float filtered_speed_uncertainty; + + float unfiltered_measurement_fraction; + uint32_t unfiltered_measurement_integral; + float unfiltered_time_uncertainty; + float unfiltered_speed; + float unfiltered_speed_uncertainty; + + uint8_t multipath_estimate_valid; + uint32_t multipath_estimate; + uint8_t direction_valid; + float azimuth; + float elevation; + float doppler_acceleration; + float fine_speed; + float fine_speed_uncertainty; + + uint64_t carrier_phase; + uint32_t f_count; + + uint16_t parity_error_count; + uint8_t good_parity; + +}; + +_Static_assert(sizeof(GNSSOemdreMeasurement) == 109, "error"); + +struct __attribute__((packed)) GNSSOemdreMeasurementReportv2 { + log_header_type header; + uint8_t version; + uint8_t reason; + uint8_t sv_count; + uint8_t seq_num; + uint8_t seq_max; + uint16_t rf_loss; + + uint8_t system_rtc_valid; + uint32_t f_count; + uint32_t clock_resets; + uint64_t system_rtc_time; + + uint8_t gps_leap_seconds; + uint8_t gps_leap_seconds_uncertainty; + float gps_to_glonass_time_bias_milliseconds; + float gps_to_glonass_time_bias_milliseconds_uncertainty; + + uint16_t gps_week; + uint32_t gps_milliseconds; + uint32_t gps_time_bias; + uint32_t gps_clock_time_uncertainty; + uint8_t gps_clock_source; + + uint8_t glonass_clock_source; + uint8_t glonass_year; + uint16_t glonass_day; + uint32_t glonass_milliseconds; + float glonass_time_bias; + float glonass_clock_time_uncertainty; + + float clock_frequency_bias; + float clock_frequency_uncertainty; + uint8_t frequency_source; + + uint32_t cdma_clock_info[5]; + + uint8_t source; + + GNSSOemdreMeasurement measurements[16]; + +}; + +_Static_assert(sizeof(GNSSOemdreMeasurementReportv2) == 1851, "error"); + + +struct __attribute__((packed)) GNSSOemdreSVPolyReportv2 { + log_header_type header; + uint8_t version; + uint16_t sv_id; + int8_t frequency_index; + uint8_t flags; + uint16_t iode; + double t0; + double xyz0[3]; + double xyzN[9]; + float other[4]; + float position_uncertainty; + float iono_delay; + float iono_dot; + float sbas_iono_delay; + float sbas_iono_dot; + float tropo_delay; + float elevation; + float elevation_dot; + float elevation_uncertainty; + double velocity_coeff[12]; +}; + +_Static_assert(sizeof(GNSSOemdreSVPolyReportv2) == 271, "error"); + + +static void* rawgps_context; +static void *rawgps_publisher; +static int client_id = 0; + +static void hexdump(uint8_t* d, size_t len) { + for (int i=0; i= sizeof(log_header_type)+1); + log_header_type* log_header = (log_header_type*)ptr; + uint8_t* log_data = ptr + sizeof(log_header_type); + +#ifdef RAWGPS_TEST + printf("%04x\n", log_header->code); +#endif + + capnp::MallocMessageBuilder msg; + cereal::Event::Builder event = msg.initRoot(); + event.setLogMonoTime(nanos_since_boot()); + auto qcomGnss = event.initQcomGnss(); + qcomGnss.setLogTs(log_header->ts); + + switch (log_header->code) { + + case LOG_GNSS_CLOCK_REPORT: { + uint8_t version = log_data[0]; + assert(version == 2); + + assert(len >= sizeof(GNSSClockReportv2)); + const GNSSClockReportv2* report = (const GNSSClockReportv2*)ptr; + + auto lreport = qcomGnss.initClockReport(); + lreport.setHasFCount(report->valid_flags & (1 << 0)); + lreport.setFCount(report->f_count); + + lreport.setHasGpsWeek(report->valid_flags & (1 << 2)); + lreport.setGpsWeek(report->gps_week); + lreport.setHasGpsMilliseconds(report->valid_flags & (1 << 1)); + lreport.setGpsMilliseconds(report->gps_milliseconds); + lreport.setGpsTimeBias(report->gps_time_bias); + lreport.setGpsClockTimeUncertainty(report->gps_clock_time_uncertainty); + lreport.setGpsClockSource(report->gps_clock_source); + + lreport.setHasGlonassYear(report->valid_flags & (1 << 6)); + lreport.setGlonassYear(report->glonass_year); + lreport.setHasGlonassDay(report->valid_flags & (1 << 5)); + lreport.setGlonassDay(report->glonass_day); + lreport.setHasGlonassMilliseconds(report->valid_flags & (1 << 4)); + lreport.setGlonassMilliseconds(report->glonass_milliseconds); + lreport.setGlonassTimeBias(report->glonass_time_bias); + lreport.setGlonassClockTimeUncertainty(report->glonass_clock_time_uncertainty); + lreport.setGlonassClockSource(report->glonass_clock_source); + + lreport.setBdsWeek(report->bds_week); + lreport.setBdsMilliseconds(report->bds_milliseconds); + lreport.setBdsTimeBias(report->bds_time_bias); + lreport.setBdsClockTimeUncertainty(report->bds_clock_time_uncertainty); + lreport.setBdsClockSource(report->bds_clock_source); + + lreport.setGalWeek(report->gal_week); + lreport.setGalMilliseconds(report->gal_milliseconds); + lreport.setGalTimeBias(report->gal_time_bias); + lreport.setGalClockTimeUncertainty(report->gal_clock_time_uncertainty); + lreport.setGalClockSource(report->gal_clock_source); + + lreport.setClockFrequencyBias(report->clock_frequency_bias); + lreport.setClockFrequencyUncertainty(report->clock_frequency_uncertainty); + lreport.setFrequencySource(report->frequency_source); + lreport.setGpsLeapSeconds(report->gps_leap_seconds); + lreport.setGpsLeapSecondsUncertainty(report->gps_leap_seconds_uncertainty); + lreport.setGpsLeapSecondsSource(report->gps_leap_seconds_source); + + lreport.setGpsToGlonassTimeBiasMilliseconds(report->gps_to_glonass_time_bias_milliseconds); + lreport.setGpsToGlonassTimeBiasMillisecondsUncertainty(report->gps_to_glonass_time_bias_milliseconds_uncertainty); + lreport.setGpsToBdsTimeBiasMilliseconds(report->gps_to_bds_time_bias_milliseconds); + lreport.setGpsToBdsTimeBiasMillisecondsUncertainty(report->gps_to_bds_time_bias_milliseconds_uncertainty); + lreport.setBdsToGloTimeBiasMilliseconds(report->bds_to_glo_time_bias_milliseconds); + lreport.setBdsToGloTimeBiasMillisecondsUncertainty(report->bds_to_glo_time_bias_milliseconds_uncertainty); + lreport.setGpsToGalTimeBiasMilliseconds(report->gps_to_gal_time_bias_milliseconds); + lreport.setGpsToGalTimeBiasMillisecondsUncertainty(report->gps_to_gal_time_bias_milliseconds_uncertainty); + lreport.setGalToGloTimeBiasMilliseconds(report->gal_to_glo_time_bias_milliseconds); + lreport.setGalToGloTimeBiasMillisecondsUncertainty(report->gal_to_glo_time_bias_milliseconds_uncertainty); + lreport.setGalToBdsTimeBiasMilliseconds(report->gal_to_bds_time_bias_milliseconds); + lreport.setGalToBdsTimeBiasMillisecondsUncertainty(report->gal_to_bds_time_bias_milliseconds_uncertainty); + + lreport.setHasRtcTime(report->valid_flags & (1 << 3)); + lreport.setSystemRtcTime(report->system_rtc_time); + lreport.setFCountOffset(report->f_count_offset); + lreport.setLpmRtcCount(report->lpm_rtc_count); + lreport.setClockResets(report->clock_resets); + + break; + } + case LOG_GNSS_GPS_MEASUREMENT_REPORT: { + uint8_t version = log_data[0]; + assert(version == 0); + + assert(len >= sizeof(GNSSGpsMeasurementReportv0)); + const GNSSGpsMeasurementReportv0* report = (const GNSSGpsMeasurementReportv0*)ptr; + assert(len >= sizeof(sizeof(GNSSGpsMeasurementReportv0))+sizeof(GNSSGpsMeasurementReportv0_SV) * report->sv_count); + + auto lreport = qcomGnss.initMeasurementReport(); + lreport.setSource(cereal::QcomGnss::MeasurementSource::GPS); + lreport.setFCount(report->f_count); + lreport.setGpsWeek(report->week); + lreport.setMilliseconds(report->milliseconds); + lreport.setTimeBias(report->time_bias); + lreport.setClockTimeUncertainty(report->clock_time_uncertainty); + lreport.setClockFrequencyBias(report->clock_frequency_bias); + lreport.setClockFrequencyUncertainty(report->clock_frequency_uncertainty); + + auto lsvs = lreport.initSv(report->sv_count); + for (int i=0; isv_count; i++) { + auto lsv = lsvs[i]; + const GNSSGpsMeasurementReportv0_SV *sv = &report->sv[i]; + + lsv.setSvId(sv->sv_id); + lsv.setObservationState(cereal::QcomGnss::SVObservationState(sv->observation_state)); + lsv.setObservations(sv->observations); + lsv.setGoodObservations(sv->good_observations); + lsv.setGpsParityErrorCount(sv->parity_error_count); + lsv.setFilterStages(sv->filter_stages); + lsv.setCarrierNoise(sv->carrier_noise); + lsv.setLatency(sv->latency); + lsv.setPredetectInterval(sv->predetect_interval); + lsv.setPostdetections(sv->postdetections); + lsv.setUnfilteredMeasurementIntegral(sv->unfiltered_measurement_integral); + lsv.setUnfilteredMeasurementFraction(sv->unfiltered_measurement_fraction); + lsv.setUnfilteredTimeUncertainty(sv->unfiltered_time_uncertainty); + lsv.setUnfilteredSpeed(sv->unfiltered_speed); + lsv.setUnfilteredSpeedUncertainty(sv->unfiltered_speed_uncertainty); + + lsv.setMultipathEstimate(sv->multipath_estimate); + lsv.setAzimuth(sv->azimuth); + lsv.setElevation(sv->elevation); + lsv.setCarrierPhaseCyclesIntegral(sv->carrier_phase_cycles_integral); + lsv.setCarrierPhaseCyclesFraction(sv->carrier_phase_cycles_fraction); + lsv.setFineSpeed(sv->fine_speed); + lsv.setFineSpeedUncertainty(sv->fine_speed_uncertainty); + lsv.setCycleSlipCount(sv->cycle_slip_count); + + auto status = lsv.initMeasurementStatus(); + parse_measurement_status_common(sv->measurement_status, status); + + status.setGpsRoundRobinRxDiversity(sv->measurement_status & (1 << 18)); + status.setGpsRxDiversity(sv->measurement_status & (1 << 19)); + status.setGpsLowBandwidthRxDiversityCombined(sv->measurement_status & (1 << 20)); + status.setGpsHighBandwidthNu4(sv->measurement_status & (1 << 21)); + status.setGpsHighBandwidthNu8(sv->measurement_status & (1 << 22)); + status.setGpsHighBandwidthUniform(sv->measurement_status & (1 << 23)); + + status.setMultipathEstimateIsValid(sv->misc_status & (1 << 0)); + status.setDirectionIsValid(sv->misc_status & (1 << 1)); + +#ifdef RAWGPS_TEST + // if (sv->measurement_status & (1 << 27)) printf("%d\n", sv->unfiltered_measurement_integral); + printf("GPS %03d %d %d 0x%08X o: %02x go: %02x fs: %02x cn: %02x pd: %02x cs: %02x po: %02x ms: %08x ms2: %08x me: %08x az: %08x el: %08x fc: %08x\n", + sv->sv_id, + !!(sv->measurement_status & (1 << 27)), + sv->unfiltered_measurement_integral, sv->unfiltered_measurement_integral, + sv->observations, + sv->good_observations, + sv->filter_stages, + sv->carrier_noise, + sv->predetect_interval, + sv->cycle_slip_count, + sv->postdetections, + sv->measurement_status, + sv->misc_status, + sv->multipath_estimate, + *(uint32_t*)&sv->azimuth, + *(uint32_t*)&sv->elevation, + report->f_count + ); +#endif + + } + + break; + } + case LOG_GNSS_GLONASS_MEASUREMENT_REPORT: { + uint8_t version = log_data[0]; + assert(version == 0); + + assert(len >= sizeof(GNSSGlonassMeasurementReportv0)); + const GNSSGlonassMeasurementReportv0* report = (const GNSSGlonassMeasurementReportv0*)ptr; + + auto lreport = qcomGnss.initMeasurementReport(); + lreport.setSource(cereal::QcomGnss::MeasurementSource::GLONASS); + lreport.setFCount(report->f_count); + lreport.setGlonassCycleNumber(report->glonass_cycle_number); + lreport.setGlonassNumberOfDays(report->glonass_number_of_days); + lreport.setMilliseconds(report->milliseconds); + lreport.setTimeBias(report->time_bias); + lreport.setClockTimeUncertainty(report->clock_time_uncertainty); + lreport.setClockFrequencyBias(report->clock_frequency_bias); + lreport.setClockFrequencyUncertainty(report->clock_frequency_uncertainty); + + auto lsvs = lreport.initSv(report->sv_count); + for (int i=0; isv_count; i++) { + auto lsv = lsvs[i]; + const GNSSGlonassMeasurementReportv0_SV *sv = &report->sv[i]; + + lsv.setSvId(sv->sv_id); + lsv.setObservationState(cereal::QcomGnss::SVObservationState(sv->observation_state)); + lsv.setObservations(sv->observations); + lsv.setGoodObservations(sv->good_observations); + lsv.setGlonassFrequencyIndex(sv->frequency_index); + lsv.setGlonassHemmingErrorCount(sv->hemming_error_count); + lsv.setFilterStages(sv->filter_stages); + lsv.setCarrierNoise(sv->carrier_noise); + lsv.setLatency(sv->latency); + lsv.setPredetectInterval(sv->predetect_interval); + lsv.setPostdetections(sv->postdetections); + lsv.setUnfilteredMeasurementIntegral(sv->unfiltered_measurement_integral); + lsv.setUnfilteredMeasurementFraction(sv->unfiltered_measurement_fraction); + lsv.setUnfilteredTimeUncertainty(sv->unfiltered_time_uncertainty); + lsv.setUnfilteredSpeed(sv->unfiltered_speed); + lsv.setUnfilteredSpeedUncertainty(sv->unfiltered_speed_uncertainty); + + lsv.setMultipathEstimate(sv->multipath_estimate); + lsv.setAzimuth(sv->azimuth); + lsv.setElevation(sv->elevation); + lsv.setCarrierPhaseCyclesIntegral(sv->carrier_phase_cycles_integral); + lsv.setCarrierPhaseCyclesFraction(sv->carrier_phase_cycles_fraction); + lsv.setFineSpeed(sv->fine_speed); + lsv.setFineSpeedUncertainty(sv->fine_speed_uncertainty); + lsv.setCycleSlipCount(sv->cycle_slip_count); + + auto status = lsv.initMeasurementStatus(); + parse_measurement_status_common(sv->measurement_status, status); + + status.setGlonassMeanderBitEdgeValid(sv->measurement_status & (1 << 16)); + status.setGlonassTimeMarkValid(sv->measurement_status & (1 << 17)); + + status.setMultipathEstimateIsValid(sv->misc_status & (1 << 0)); + status.setDirectionIsValid(sv->misc_status & (1 << 1)); + + +#ifdef RAWGPS_TEST + // if (sv->measurement_status & (1 << 27)) printf("%d\n", sv->unfiltered_measurement_integral); + printf("GLO %03d %02x %d %d 0x%08X o: %02x go: %02x fs: %02x cn: %02x pd: %02x cs: %02x po: %02x ms: %08x ms2: %08x me: %08x az: %08x el: %08x fc: %08x\n", + sv->sv_id, sv->frequency_index & 0xff, + !!(sv->measurement_status & (1 << 27)), + sv->unfiltered_measurement_integral, sv->unfiltered_measurement_integral, + sv->observations, + sv->good_observations, + sv->filter_stages, + sv->carrier_noise, + sv->predetect_interval, + sv->cycle_slip_count, + sv->postdetections, + sv->measurement_status, + sv->misc_status, + sv->multipath_estimate, + *(uint32_t*)&sv->azimuth, + *(uint32_t*)&sv->elevation, + report->f_count + ); +#endif + + } + break; + } + case LOG_GNSS_OEMDRE_MEASUREMENMT_REPORT: { + // hexdump(ptr, len); + + uint8_t version = log_data[0]; + assert(version == 2); + + assert(len >= sizeof(GNSSOemdreMeasurementReportv2)); + const GNSSOemdreMeasurementReportv2* report = (const GNSSOemdreMeasurementReportv2*)ptr; + + + auto lreport = qcomGnss.initDrMeasurementReport(); + + lreport.setReason(report->reason); + lreport.setSeqNum(report->seq_num); + lreport.setSeqMax(report->seq_max); + lreport.setRfLoss(report->rf_loss); + lreport.setSystemRtcValid(report->system_rtc_valid); + lreport.setFCount(report->f_count); + lreport.setClockResets(report->clock_resets); + lreport.setSystemRtcTime(report->system_rtc_time); + + lreport.setGpsLeapSeconds(report->gps_leap_seconds); + lreport.setGpsLeapSecondsUncertainty(report->gps_leap_seconds_uncertainty); + lreport.setGpsToGlonassTimeBiasMilliseconds(report->gps_to_glonass_time_bias_milliseconds); + lreport.setGpsToGlonassTimeBiasMillisecondsUncertainty(report->gps_to_glonass_time_bias_milliseconds_uncertainty); + + lreport.setGpsWeek(report->gps_week); + lreport.setGpsMilliseconds(report->gps_milliseconds); + lreport.setGpsTimeBiasMs(report->gps_time_bias); + lreport.setGpsClockTimeUncertaintyMs(report->gps_clock_time_uncertainty); + lreport.setGpsClockSource(report->gps_clock_source); + + lreport.setGlonassClockSource(report->glonass_clock_source); + lreport.setGlonassYear(report->glonass_year); + lreport.setGlonassDay(report->glonass_day); + lreport.setGlonassMilliseconds(report->glonass_milliseconds); + lreport.setGlonassTimeBias(report->glonass_time_bias); + lreport.setGlonassClockTimeUncertainty(report->glonass_clock_time_uncertainty); + + lreport.setClockFrequencyBias(report->clock_frequency_bias); + lreport.setClockFrequencyUncertainty(report->clock_frequency_uncertainty); + lreport.setFrequencySource(report->frequency_source); + + lreport.setSource(cereal::QcomGnss::MeasurementSource(report->source)); + + auto lsvs = lreport.initSv(report->sv_count); + + // for (int i=0; isv_count; i++) { + // GNSSOemdreMeasurement *sv = &report->gps[i]; + // if (!(sv->measurement_status & (1 << 27))) continue; + // printf("oemdre %03d %d %f\n", sv->sv_id, sv->unfiltered_measurement_integral, sv->unfiltered_measurement_fraction); + // } + for (int i=0; isv_count; i++) { + auto lsv = lsvs[i]; + const GNSSOemdreMeasurement *sv = &report->measurements[i]; + + lsv.setSvId(sv->sv_id); + lsv.setGlonassFrequencyIndex(sv->glonass_frequency_index); + lsv.setObservationState(cereal::QcomGnss::SVObservationState(sv->observation_state)); + lsv.setObservations(sv->observations); + lsv.setGoodObservations(sv->good_observations); + lsv.setFilterStages(sv->filter_stages); + lsv.setPredetectInterval(sv->predetect_interval); + lsv.setCycleSlipCount(sv->cycle_slip_count); + lsv.setPostdetections(sv->postdetections); + + auto status = lsv.initMeasurementStatus(); + parse_measurement_status_common(sv->measurement_status, status); + + status.setMultipathEstimateIsValid(sv->multipath_estimate_valid); + status.setDirectionIsValid(sv->direction_valid); + + lsv.setCarrierNoise(sv->carrier_noise); + lsv.setRfLoss(sv->rf_loss); + lsv.setLatency(sv->latency); + + lsv.setFilteredMeasurementFraction(sv->filtered_measurement_fraction); + lsv.setFilteredMeasurementIntegral(sv->filtered_measurement_integral); + lsv.setFilteredTimeUncertainty(sv->filtered_time_uncertainty); + lsv.setFilteredSpeed(sv->filtered_speed); + lsv.setFilteredSpeedUncertainty(sv->filtered_speed_uncertainty); + + lsv.setUnfilteredMeasurementFraction(sv->unfiltered_measurement_fraction); + lsv.setUnfilteredMeasurementIntegral(sv->unfiltered_measurement_integral); + lsv.setUnfilteredTimeUncertainty(sv->unfiltered_time_uncertainty); + lsv.setUnfilteredSpeed(sv->unfiltered_speed); + lsv.setUnfilteredSpeedUncertainty(sv->unfiltered_speed_uncertainty); + + lsv.setMultipathEstimate(sv->multipath_estimate); + lsv.setAzimuth(sv->azimuth); + lsv.setElevation(sv->elevation); + lsv.setDopplerAcceleration(sv->doppler_acceleration); + lsv.setFineSpeed(sv->fine_speed); + lsv.setFineSpeedUncertainty(sv->fine_speed_uncertainty); + + lsv.setCarrierPhase(sv->carrier_phase); + lsv.setFCount(sv->f_count); + + lsv.setParityErrorCount(sv->parity_error_count); + lsv.setGoodParity(sv->good_parity); + + } + break; + } + case LOG_GNSS_OEMDRE_SVPOLY_REPORT: { + uint8_t version = log_data[0]; + assert(version == 2); + + assert(len >= sizeof(GNSSOemdreSVPolyReportv2)); + const GNSSOemdreSVPolyReportv2* report = (const GNSSOemdreSVPolyReportv2*)ptr; + + auto lreport = qcomGnss.initDrSvPoly(); + + lreport.setSvId(report->sv_id); + lreport.setFrequencyIndex(report->frequency_index); + + lreport.setHasPosition(report->flags & 1); + lreport.setHasIono(report->flags & 2); + lreport.setHasTropo(report->flags & 4); + lreport.setHasElevation(report->flags & 8); + lreport.setPolyFromXtra(report->flags & 16); + lreport.setHasSbasIono(report->flags & 32); + + lreport.setIode(report->iode); + lreport.setT0(report->t0); + + kj::ArrayPtr xyz0(report->xyz0, 3); + lreport.setXyz0(xyz0); + + kj::ArrayPtr xyzN(report->xyzN, 9); + lreport.setXyzN(xyzN); + + kj::ArrayPtr other(report->other, 4); + lreport.setOther(other); + + lreport.setPositionUncertainty(report->position_uncertainty); + lreport.setIonoDelay(report->iono_delay); + lreport.setIonoDot(report->iono_dot); + lreport.setSbasIonoDelay(report->sbas_iono_delay); + lreport.setSbasIonoDot(report->sbas_iono_dot); + lreport.setTropoDelay(report->tropo_delay); + lreport.setElevation(report->elevation); + lreport.setElevationDot(report->elevation_dot); + lreport.setElevationUncertainty(report->elevation_uncertainty); + + kj::ArrayPtr velocity_coeff(report->velocity_coeff, 12); + lreport.setVelocityCoeff(velocity_coeff); + + break; + } + default: + // printf("%04x\n", log_header->code); + // hexdump(ptr, len); + + qcomGnss.setRawLog(kj::arrayPtr(ptr, len)); + + break; + } + + auto words = capnp::messageToFlatArray(msg); + auto bytes = words.asBytes(); + zmq_send(rawgps_publisher, bytes.begin(), bytes.size(), 0); +} + +static void handle_event(unsigned char *ptr, int len) { + // printf("EVENT\n"); +} + +static uint16_t log_codes[] = { + LOG_GNSS_CLOCK_REPORT, + LOG_GNSS_GPS_MEASUREMENT_REPORT, + LOG_GNSS_GLONASS_MEASUREMENT_REPORT, + LOG_GNSS_OEMDRE_MEASUREMENMT_REPORT, + LOG_GNSS_OEMDRE_SVPOLY_REPORT, + + // unparsed: + LOG_GNSS_POSITION_REPORT, + + LOG_GNSS_BDS_MEASUREMENT_REPORT, // these are missing by might as well try to catch them anyway + LOG_GNSS_GAL_MEASUREMENT_REPORT, + + LOG_GNSS_ME_DPO_STATUS, + LOG_GNSS_CD_DB_REPORT, + LOG_GNSS_PRX_RF_HW_STATUS_REPORT, + LOG_CGPS_SLOW_CLOCK_CLIB_REPORT, + LOG_GNSS_CONFIGURATION_STATE, +}; + + +struct SendDiagSyncState { + sem_t sem; + int len; +}; + +static void diag_send_sync_cb(unsigned char *ptr, int len, void *data_ptr) { + SendDiagSyncState *s = (SendDiagSyncState*)data_ptr; + s->len = len; + sem_post(&s->sem); +} + +static int diag_send_sync(int client_id, unsigned char* req_pkt, size_t pkt_len, + unsigned char* res_pkt, size_t res_pkt_size) { + + SendDiagSyncState s = {0}; + sem_init(&s.sem, 0, 0); + + int err = diag_send_dci_async_req(client_id, req_pkt, pkt_len, res_pkt, res_pkt_size, + diag_send_sync_cb, &s); + assert(err == DIAG_DCI_NO_ERROR); + + sem_wait(&s.sem); + return s.len; +} + +static int oemdre_on(int client_id) { + // enable OEM DR + unsigned char res_pkt[DIAG_MAX_RX_PKT_SIZ]; + + GpsOemControlReq req_pkt = { + .cmd_code = DIAG_SUBSYS_CMD, + .subsys_id = DIAG_SUBSYS_GPS, + .subsys_cmd_code = CGPS_DIAG_PDAPI_CMD, + .gps_cmd_code = CGPS_OEM_CONTROL, + .version = 1, + + .oem_feature = GPSDIAG_OEMFEATURE_DRE, + .oem_command = GPSDIAG_OEM_DRE_ON, + }; + + int res_len = diag_send_sync(client_id, (unsigned char*)&req_pkt, sizeof(req_pkt), + res_pkt, sizeof(res_pkt)); + GpsOemControlResp *resp = (GpsOemControlResp*)res_pkt; + + if (res_len != sizeof(GpsOemControlResp) + || resp->cmd_code != DIAG_SUBSYS_CMD + || resp->subsys_id != DIAG_SUBSYS_GPS + || resp->subsys_cmd_code != CGPS_DIAG_PDAPI_CMD + || resp->gps_cmd_code != CGPS_OEM_CONTROL + || resp->oem_feature != GPSDIAG_OEMFEATURE_DRE + || resp->oem_command != GPSDIAG_OEM_DRE_ON) { + LOGW("oemdre_on: bad response!"); + return -1; + } + + return resp->resp_result; +} + +static void efs_sync(int client_id) { + unsigned char res_pkt[DIAG_MAX_RX_PKT_SIZ]; + + Efs2DiagSyncReq req_pkt = { + .cmd_code = DIAG_SUBSYS_CMD, + .subsys_id = DIAG_SUBSYS_FS, + .subsys_cmd_code = EFS2_DIAG_SYNC_NO_WAIT, + .sequence_num = (uint16_t)(rand() % 100), + }; + req_pkt.path[0] = '/'; + req_pkt.path[1] = 0; + + int res_len = diag_send_sync(client_id, (unsigned char*)&req_pkt, sizeof(req_pkt), + res_pkt, sizeof(res_pkt)); + Efs2DiagSyncResp *resp = (Efs2DiagSyncResp*)res_pkt; + + if (res_len != sizeof(Efs2DiagSyncResp) + || resp->cmd_code != DIAG_SUBSYS_CMD + || resp->subsys_id != DIAG_SUBSYS_FS + || resp->subsys_cmd_code != EFS2_DIAG_SYNC_NO_WAIT) { + LOGW("efs_sync: bad response!"); + return; + } + if (resp->diag_errno != 0) { + LOGW("efs_sync: error %d", resp->diag_errno); + } +} + +static uint32_t nv_read_u32(int client_id, uint16_t nv_id) { + NvPacket req = { + .cmd_code = DIAG_NV_READ_F, + .nv_id = nv_id, + }; + NvPacket resp = {0}; + + int res_len = diag_send_sync(client_id, (unsigned char*)&req, sizeof(req), + (unsigned char*)&resp, sizeof(resp)); + + // hexdump((uint8_t*)&resp, res_len); + + if (resp.cmd_code != DIAG_NV_READ_F + || resp.nv_id != nv_id) { + LOGW("nv_read_u32: diag command failed"); + return 0; + } + + if (resp.status != NV_DONE) { + LOGW("nv_read_u32: read failed: %d", resp.status); + return 0; + } + return *(uint32_t*)resp.data; +} + +static bool nv_write_u32(int client_id, uint16_t nv_id, uint32_t val) { + NvPacket req = { + .cmd_code = DIAG_NV_WRITE_F, + .nv_id = nv_id, + }; + *(uint32_t*)req.data = val; + + NvPacket resp = {0}; + int res_len = diag_send_sync(client_id, (unsigned char*)&req, sizeof(req), + (unsigned char*)&resp, sizeof(resp)); + + // hexdump((uint8_t*)&resp, res_len); + + if (resp.cmd_code != DIAG_NV_WRITE_F + || resp.nv_id != nv_id) { + LOGW("nv_write_u32: diag command failed"); + return false; + } + + if (resp.status != NV_DONE) { + LOGW("nv_write_u32: write failed: %d", resp.status); + return false; + } + + return true; +} + +static void nav_config(int client_id, uint8_t config) { + unsigned char res_pkt[DIAG_MAX_RX_PKT_SIZ]; + + GpsNavConfigReq req_pkt = { + .cmd_code = DIAG_SUBSYS_CMD_VER_2, + .subsys_id = DIAG_SUBSYS_GPS, + .subsys_cmd_code = TM_DIAG_NAV_CONFIG_CMD, + .desired_config = config, + }; + + int res_len = diag_send_sync(client_id, (unsigned char*)&req_pkt, sizeof(req_pkt), + res_pkt, sizeof(res_pkt)); + GpsNavConfigResp *resp = (GpsNavConfigResp*)res_pkt; + + if (res_len != sizeof(GpsNavConfigResp) + || resp->cmd_code != DIAG_SUBSYS_CMD_VER_2 + || resp->subsys_id != DIAG_SUBSYS_GPS + || resp->subsys_cmd_code != TM_DIAG_NAV_CONFIG_CMD) { + LOGW("nav_config: bad response!"); + return; + } + LOG("nav config: %04x %04x", resp->supported_config, resp->actual_config); +} + +void rawgps_init() { + int err; + + + rawgps_context = zmq_ctx_new(); + rawgps_publisher = zmq_socket(rawgps_context, ZMQ_PUB); + zmq_bind(rawgps_publisher, "tcp://*:8029"); + + + bool init_success = Diag_LSM_Init(NULL); + assert(init_success); + + uint16_t list = DIAG_CON_APSS | DIAG_CON_MPSS; + int signal_type = SIGCONT; + err = diag_register_dci_client(&client_id, &list, 0, &signal_type); + assert(err == DIAG_DCI_NO_ERROR); + + { + uint32_t oem_features = nv_read_u32(client_id, NV_GNSS_OEM_FEATURE_MASK); + LOG("oem features: %08x", oem_features); + + if (!(oem_features & NV_GNSS_OEM_FEATURE_MASK_OEMDRE)) { + LOG("OEMDRE feature disabled, enabling..."); + nv_write_u32(client_id, NV_GNSS_OEM_FEATURE_MASK, NV_GNSS_OEM_FEATURE_MASK_OEMDRE); + efs_sync(client_id); + } + + int oemdre_status = oemdre_on(client_id); + LOG("oemdre status: %d", oemdre_status); + } + + { + // make sure GNSS duty cycling is off + uint32_t dpo = nv_read_u32(client_id, NV_CGPS_DPO_CONTROL); + LOG("dpo: %d", dpo); + if (dpo != 0) { + nv_write_u32(client_id, NV_CGPS_DPO_CONTROL, 0); + efs_sync(client_id); + } + } + + // enable beidou + // nav_config(client_id, 0x13); // 0b10011 + + err = diag_register_dci_stream(handle_log, handle_event); + assert(err == DIAG_DCI_NO_ERROR); + + err = diag_log_stream_config(client_id, true, log_codes, ARRAYSIZE(log_codes)); + assert(err == DIAG_DCI_NO_ERROR); +} + +void rawgps_destroy() { + + int err; + + err = diag_log_stream_config(client_id, false, log_codes, ARRAYSIZE(log_codes)); + assert(err == DIAG_DCI_NO_ERROR); + + err = diag_release_dci_client(&client_id); + assert(err == DIAG_DCI_NO_ERROR); + + Diag_LSM_DeInit(); + + zmq_close(rawgps_publisher); + zmq_term(rawgps_context); + +} + + +#ifdef RAWGPS_TEST +int main() { + int err = 0; + rawgps_init(); + + while(1) { + usleep(100000); + } + + rawgps_destroy(); + return 0; +} +#endif \ No newline at end of file diff --git a/selfdrive/sensord/rawgps.h b/selfdrive/sensord/rawgps.h new file mode 100644 index 0000000000..13d23cd28c --- /dev/null +++ b/selfdrive/sensord/rawgps.h @@ -0,0 +1,7 @@ +#ifndef RAWGPS_H +#define RAWGPS_H + +void rawgps_init(); +void rawgps_destroy(); + +#endif diff --git a/selfdrive/sensord/sensord b/selfdrive/sensord/sensord deleted file mode 100755 index df98efc6af..0000000000 Binary files a/selfdrive/sensord/sensord and /dev/null differ diff --git a/selfdrive/sensord/sensors.cc b/selfdrive/sensord/sensors.cc new file mode 100644 index 0000000000..5717458f72 --- /dev/null +++ b/selfdrive/sensord/sensors.cc @@ -0,0 +1,232 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include +#include + +#include + +#include + +#include "common/timing.h" +#include "common/swaglog.h" + +#include "cereal/gen/cpp/log.capnp.h" + +#define SENSOR_ACCELEROMETER 1 +#define SENSOR_MAGNETOMETER 2 +#define SENSOR_GYRO 4 + +// ACCELEROMETER_UNCALIBRATED is only in Android O +// https://developer.android.com/reference/android/hardware/Sensor.html#STRING_TYPE_ACCELEROMETER_UNCALIBRATED +#define SENSOR_MAGNETOMETER_UNCALIBRATED 3 +#define SENSOR_GYRO_UNCALIBRATED 5 + +#define SENSOR_PROXIMITY 6 +#define SENSOR_LIGHT 7 + +volatile int do_exit = 0; + +namespace { + +void set_do_exit(int sig) { + do_exit = 1; +} + +void sigpipe_handler(int sig) { + LOGE("SIGPIPE received"); +} + + +void sensor_loop() { + LOG("*** sensor loop"); + struct sensors_poll_device_t* device; + struct sensors_module_t* module; + + hw_get_module(SENSORS_HARDWARE_MODULE_ID, (hw_module_t const**)&module); + sensors_open(&module->common, &device); + + // required + struct sensor_t const* list; + int count = module->get_sensors_list(module, &list); + LOG("%d sensors found", count); + + if (getenv("SENSOR_TEST")) { + exit(count); + } + + for (int i = 0; i < count; i++) { + LOGD("sensor %4d: %4d %60s %d-%ld us", i, list[i].handle, list[i].name, list[i].minDelay, list[i].maxDelay); + } + + device->activate(device, SENSOR_MAGNETOMETER_UNCALIBRATED, 0); + device->activate(device, SENSOR_GYRO_UNCALIBRATED, 0); + device->activate(device, SENSOR_ACCELEROMETER, 0); + device->activate(device, SENSOR_MAGNETOMETER, 0); + device->activate(device, SENSOR_GYRO, 0); + device->activate(device, SENSOR_PROXIMITY, 0); + device->activate(device, SENSOR_LIGHT, 0); + + device->activate(device, SENSOR_MAGNETOMETER_UNCALIBRATED, 1); + device->activate(device, SENSOR_GYRO_UNCALIBRATED, 1); + device->activate(device, SENSOR_ACCELEROMETER, 1); + device->activate(device, SENSOR_MAGNETOMETER, 1); + device->activate(device, SENSOR_GYRO, 1); + device->activate(device, SENSOR_PROXIMITY, 1); + device->activate(device, SENSOR_LIGHT, 1); + + device->setDelay(device, SENSOR_GYRO_UNCALIBRATED, ms2ns(10)); + device->setDelay(device, SENSOR_MAGNETOMETER_UNCALIBRATED, ms2ns(100)); + device->setDelay(device, SENSOR_ACCELEROMETER, ms2ns(10)); + device->setDelay(device, SENSOR_GYRO, ms2ns(10)); + device->setDelay(device, SENSOR_MAGNETOMETER, ms2ns(100)); + device->setDelay(device, SENSOR_PROXIMITY, ms2ns(100)); + device->setDelay(device, SENSOR_LIGHT, ms2ns(100)); + + static const size_t numEvents = 16; + sensors_event_t buffer[numEvents]; + + auto sensor_events_sock = zsock_new_pub("@tcp://*:8003"); + assert(sensor_events_sock); + auto sensor_events_sock_raw = zsock_resolve(sensor_events_sock); + + while (!do_exit) { + int n = device->poll(device, buffer, numEvents); + if (n == 0) continue; + if (n < 0) { + LOG("sensor_loop poll failed: %d", n); + continue; + } + + int log_events = 0; + for (int i=0; i < n; i++) { + switch (buffer[i].type) { + case SENSOR_TYPE_ACCELEROMETER: + case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED: + case SENSOR_TYPE_MAGNETIC_FIELD: + case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED: + case SENSOR_TYPE_GYROSCOPE: + case SENSOR_TYPE_PROXIMITY: + case SENSOR_TYPE_LIGHT: + log_events++; + break; + default: + continue; + } + } + + uint64_t log_time = nanos_since_boot(); + + capnp::MallocMessageBuilder msg; + cereal::Event::Builder event = msg.initRoot(); + event.setLogMonoTime(log_time); + + auto sensor_events = event.initSensorEvents(log_events); + + int log_i = 0; + for (int i = 0; i < n; i++) { + + const sensors_event_t& data = buffer[i]; + + switch (data.type) { + case SENSOR_TYPE_ACCELEROMETER: + case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED: + case SENSOR_TYPE_MAGNETIC_FIELD: + case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED: + case SENSOR_TYPE_GYROSCOPE: + case SENSOR_TYPE_PROXIMITY: + case SENSOR_TYPE_LIGHT: + break; + default: + continue; + } + + auto log_event = sensor_events[log_i]; + + log_event.setSource(cereal::SensorEventData::SensorSource::ANDROID); + log_event.setVersion(data.version); + log_event.setSensor(data.sensor); + log_event.setType(data.type); + log_event.setTimestamp(data.timestamp); + + switch (data.type) { + case SENSOR_TYPE_ACCELEROMETER: { + auto svec = log_event.initAcceleration(); + kj::ArrayPtr vs(&data.acceleration.v[0], 3); + svec.setV(vs); + svec.setStatus(data.acceleration.status); + break; + } + case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED: { + auto svec = log_event.initMagneticUncalibrated(); + // assuming the uncalib and bias floats are contiguous in memory + kj::ArrayPtr vs(&data.uncalibrated_magnetic.uncalib[0], 6); + svec.setV(vs); + break; + } + case SENSOR_TYPE_MAGNETIC_FIELD: { + auto svec = log_event.initMagnetic(); + kj::ArrayPtr vs(&data.magnetic.v[0], 3); + svec.setV(vs); + svec.setStatus(data.magnetic.status); + break; + } + case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED: { + auto svec = log_event.initGyroUncalibrated(); + // assuming the uncalib and bias floats are contiguous in memory + kj::ArrayPtr vs(&data.uncalibrated_gyro.uncalib[0], 6); + svec.setV(vs); + break; + } + case SENSOR_TYPE_GYROSCOPE: { + auto svec = log_event.initGyro(); + kj::ArrayPtr vs(&data.gyro.v[0], 3); + svec.setV(vs); + svec.setStatus(data.gyro.status); + break; + } + case SENSOR_TYPE_PROXIMITY: { + log_event.setProximity(data.distance); + break; + } + case SENSOR_TYPE_LIGHT: + log_event.setLight(data.light); + break; + } + + log_i++; + } + + auto words = capnp::messageToFlatArray(msg); + auto bytes = words.asBytes(); + zmq_send(sensor_events_sock_raw, bytes.begin(), bytes.size(), ZMQ_DONTWAIT); + + } + LOG("bye"); +} + +} + +int main(int argc, char *argv[]) { + setpriority(PRIO_PROCESS, 0, -13); + signal(SIGINT, (sighandler_t)set_do_exit); + signal(SIGTERM, (sighandler_t)set_do_exit); + signal(SIGPIPE, (sighandler_t)sigpipe_handler); + + sensor_loop(); + + return 0; +} diff --git a/selfdrive/sensord/start_gpsd.py b/selfdrive/sensord/start_gpsd.py new file mode 100755 index 0000000000..ada2687158 --- /dev/null +++ b/selfdrive/sensord/start_gpsd.py @@ -0,0 +1,6 @@ +#!/usr/bin/env python2 +import os + +assert os.system("make") == 0 +os.environ['LD_LIBRARY_PATH'] = "/system/lib64:" + os.environ['LD_LIBRARY_PATH'] +os.execv("./gpsd", ["gpsd"]) diff --git a/selfdrive/sensord/start_sensord.py b/selfdrive/sensord/start_sensord.py new file mode 100755 index 0000000000..d6d6564113 --- /dev/null +++ b/selfdrive/sensord/start_sensord.py @@ -0,0 +1,6 @@ +#!/usr/bin/env python2 +import os + +assert os.system("make") == 0 +os.environ['LD_LIBRARY_PATH'] = "/system/lib64:" + os.environ['LD_LIBRARY_PATH'] +os.execv("./sensord", ["sensord"]) diff --git a/selfdrive/service_list.yaml b/selfdrive/service_list.yaml index d18eaf6137..9d141c88d1 100644 --- a/selfdrive/service_list.yaml +++ b/selfdrive/service_list.yaml @@ -2,119 +2,135 @@ # LogRotate: 8001 is a PUSH PULL socket between loggerd and visiond -# all ZMQ pub sub: +# all ZMQ pub sub: port, should_log, frequency, (qlog_decimation) # frame syncing packet -frame: [8002, true] +frame: [8002, true, 20., 1] # accel, gyro, and compass -sensorEvents: [8003, true] +sensorEvents: [8003, true, 100., 100] # GPS data, also global timestamp -gpsNMEA: [8004, true] +gpsNMEA: [8004, true, 9.] # 9 msgs each sec # CPU+MEM+GPU+BAT temps -thermal: [8005, true] +thermal: [8005, true, 1., 1] # List(CanData), list of can messages -can: [8006, true] -controlsState: [8007, true] - -# random events we want to log - -#liveEvent: [8008, true] -model: [8009, true] -features: [8010, true] -health: [8011, true] -radarState: [8012, true] -#liveUI: [8014, true] -encodeIdx: [8015, true] -liveTracks: [8016, true] -sendcan: [8017, true] -logMessage: [8018, true] -liveCalibration: [8019, true] -androidLog: [8020, true] -carState: [8021, true] +can: [8006, true, 100.] +controlsState: [8007, true, 100., 100] +#liveEvent: [8008, true, 0.] +model: [8009, true, 20.] +features: [8010, true, 0.] +health: [8011, true, 1., 1] +radarState: [8012, true, 20.] +#liveUI: [8014, true, 0.] +encodeIdx: [8015, true, 20.] +liveTracks: [8016, true, 20.] +sendcan: [8017, true, 100.] +logMessage: [8018, true, 0.] +liveCalibration: [8019, true, 5.] +androidLog: [8020, true, 0.] +carState: [8021, true, 100., 10] # 8022 is reserved for sshd -carControl: [8023, true] -plan: [8024, true] -liveLocation: [8025, true] -gpsLocation: [8026, true] -ethernetData: [8027, true] -navUpdate: [8028, true] -qcomGnss: [8029, true] -lidarPts: [8030, true] -procLog: [8031, true] -gpsLocationExternal: [8032, true] -ubloxGnss: [8033, true] -clocks: [8034, true] -liveMpc: [8035, true] -liveLongitudinalMpc: [8036, true] -plusFrame: [8037, false] -navStatus: [8038, true] -gpsLocationTrimble: [8039, true] -trimbleGnss: [8041, true] -ubloxRaw: [8042, true] -gpsPlannerPoints: [8043, true] -gpsPlannerPlan: [8044, true] -applanixRaw: [8046, true] -orbLocation: [8047, true] -trafficEvents: [8048, true] -liveLocationTiming: [8049, true] -orbslamCorrection: [8050, true] -liveLocationCorrected: [8051, true] -orbObservation: [8052, true] -applanixLocation: [8053, true] -liveLocationKalman: [8054, true] -uiNavigationEvent: [8055, true] -orbOdometry: [8057, true] -orbFeatures: [8058, false] -orbKeyFrame: [8059, true] -uiLayoutState: [8060, true] -frontEncodeIdx: [8061, true] -orbFeaturesSummary: [8062, true] -driverMonitoring: [8063, true] -liveParameters: [8064, true] -liveMapData: [8065, true] -cameraOdometry: [8066, true] -pathPlan: [8067, true] -kalmanOdometry: [8068, true] - -testModel: [8040, false] -testLiveLocation: [8045, false] -testJoystick: [8056, false] +carControl: [8023, true, 100., 10] +plan: [8024, true, 20.] +liveLocation: [8025, true, 0.] +gpsLocation: [8026, true, 1., 1] +ethernetData: [8027, true, 0.] +navUpdate: [8028, true, 0.] +qcomGnss: [8029, true, 0.] +lidarPts: [8030, true, 0.] +procLog: [8031, true, 0.5] +gpsLocationExternal: [8032, true, 10., 1] +ubloxGnss: [8033, true, 10.] +clocks: [8034, true, 1.] +liveMpc: [8035, false, 20.] +liveLongitudinalMpc: [8036, false, 20.] +plusFrame: [8037, false, 0.] +navStatus: [8038, true, 0.] +gpsLocationTrimble: [8039, true, 0.] +trimbleGnss: [8041, true, 0.] +ubloxRaw: [8042, true, 20.] +gpsPlannerPoints: [8043, true, 0.] +gpsPlannerPlan: [8044, true, 0.] +applanixRaw: [8046, true, 0.] +orbLocation: [8047, true, 0.] +trafficEvents: [8048, true, 0.] +liveLocationTiming: [8049, true, 0.] +orbslamCorrection: [8050, true, 0.] +liveLocationCorrected: [8051, true, 0.] +orbObservation: [8052, true, 0.] +applanixLocation: [8053, true, 0.] +liveLocationKalman: [8054, true, 0.] +uiNavigationEvent: [8055, true, 0.] +orbOdometry: [8057, true, 0.] +orbFeatures: [8058, false, 0.] +orbKeyFrame: [8059, true, 0.] +uiLayoutState: [8060, true, 0.] +frontEncodeIdx: [8061, true, 5.] +orbFeaturesSummary: [8062, true, 0.] +driverMonitoring: [8063, true, 5., 1] +liveParameters: [8064, true, 10.] +liveMapData: [8065, true, 0.] +cameraOdometry: [8066, true, 5.] +pathPlan: [8067, true, 20.] +kalmanOdometry: [8068, true, 0.] +thumbnail: [8069, true, 0.2, 1] +carEvents: [8070, true, 1., 1] +carParams: [8071, true, 0.02, 1] + +testModel: [8040, false, 0.] +testLiveLocation: [8045, false, 0.] +testJoystick: [8056, false, 0.] # 8080 is reserved for slave testing daemon # 8762 is reserved for logserver # manager -- base process to manage starting and stopping of all others -# subscribes: health -# publishes: thermal +# subscribes: thermal # **** processes that communicate with the outside world **** +# thermald -- decides when to start and stop onroad +# subscribes: health, location +# publishes: thermal + # boardd -- communicates with the car # subscribes: sendcan -# publishes: can, health, ubloxRaw +# publishes: can, health, ubloxRaw + +# sensord -- publishes IMU and Magnetometer +# publishes: sensorEvents -# sensord -- publishes the IMU and GPS -# publishes: sensorEvents, gpsNMEA +# gpsd -- publishes EON's gps +# publishes: gpsNMEA # visiond -- talks to the cameras, runs the model, saves the videos -# subscribes: liveCalibration, sensorEvents, controlsState -# publishes: frame, encodeIdx, model, liveCalibration +# publishes: frame, model, driverMonitoring, cameraOdometry, thumbnail # **** stateful data transformers **** # plannerd -- decides where to drive the car -# subscribes: carState, model, radarState -# publishes: plan +# subscribes: carState, model, radarState, controlsState, liveParameters +# publishes: plan, pathPlan, liveMpc, liveLongitudinalMpc -# controlsd -- actually drives the car -# subscribes: can, thermal, plan -# publishes: carState, carControl, sendcan, controlsState +# controlsd -- drives the car by sending CAN messages to panda +# subscribes: can, thermal, health, plan, pathPlan, driverMonitoring, liveCalibration +# publishes: carState, carControl, sendcan, controlsState, carEvents, carParams # radard -- processes the radar and vision data -# blocks: CarParams -# subscribes: can, controlsState, model +# subscribes: can, controlsState, model, liveParameters # publishes: radarState, liveTracks +# params_learner -- learns vehicle params by observing the vehicle dynamics +# subscribes: controlsState, sensorEvents, cameraOdometry +# publishes: liveParameters + +# calibrationd -- reads posenet and applies a temporal filter on the frame region to look at +# subscribes: cameraOdometry +# publishes: liveCalibration + +# ubloxd -- read raw ublox data and converts them in readable format +# subscribes: ubloxRaw +# publishes: ubloxGnss + # **** LOGGING SERVICE **** # loggerd @@ -123,11 +139,14 @@ testJoystick: [8056, false] # **** NON VITAL SERVICES **** # ui -# subscribes: controlsState, radarState, liveCalibration, model, (raw frames) +# subscribes: thermal, model, controlsState, uiLayout, liveCalibration, radarState, liveMpc, plusFrame, liveMapData # uploader # communicates through file system with loggerd +# deleter +# communicates through file system with loggerd and uploader + # logmessaged -- central logging service, can log to cloud # publishes: logMessage @@ -138,3 +157,7 @@ testJoystick: [8056, false] # publishes: procLog # tombstoned -- reports native crashes + +# athenad -- on request, open a sub socket and return the value + +# updated -- waits for network access and tries to update every hour diff --git a/selfdrive/services.py b/selfdrive/services.py index bd804afe79..18d43ff76a 100644 --- a/selfdrive/services.py +++ b/selfdrive/services.py @@ -2,13 +2,14 @@ import os import yaml class Service(object): - def __init__(self, port, should_log): + def __init__(self, port, should_log, frequency): self.port = port self.should_log = should_log + self.frequency = frequency service_list_path = os.path.join(os.path.dirname(__file__), "service_list.yaml") service_list = {} with open(service_list_path, "r") as f: - for k, v in yaml.load(f).items(): - service_list[k] = Service(v[0], v[1]) + for k, v in yaml.safe_load(f).items(): + service_list[k] = Service(v[0], v[1], v[2]) diff --git a/selfdrive/test/plant/plant.py b/selfdrive/test/plant/plant.py index abe021cd83..e39bafd792 100755 --- a/selfdrive/test/plant/plant.py +++ b/selfdrive/test/plant/plant.py @@ -2,7 +2,6 @@ import os import struct from collections import namedtuple -import zmq import numpy as np from opendbc import DBC_PATH @@ -93,13 +92,16 @@ class Plant(object): self.rate = rate if not Plant.messaging_initialized: - context = zmq.Context() - Plant.logcan = messaging.pub_sock(context, service_list['can'].port) - Plant.sendcan = messaging.sub_sock(context, service_list['sendcan'].port) - Plant.model = messaging.pub_sock(context, service_list['model'].port) - Plant.cal = messaging.pub_sock(context, service_list['liveCalibration'].port) - Plant.controls_state = messaging.sub_sock(context, service_list['controlsState'].port) - Plant.plan = messaging.sub_sock(context, service_list['plan'].port) + Plant.logcan = messaging.pub_sock(service_list['can'].port) + Plant.sendcan = messaging.sub_sock(service_list['sendcan'].port) + Plant.model = messaging.pub_sock(service_list['model'].port) + Plant.live_params = messaging.pub_sock(service_list['liveParameters'].port) + Plant.health = messaging.pub_sock(service_list['health'].port) + Plant.thermal = messaging.pub_sock(service_list['thermal'].port) + Plant.driverMonitoring = messaging.pub_sock(service_list['driverMonitoring'].port) + Plant.cal = messaging.pub_sock(service_list['liveCalibration'].port) + Plant.controls_state = messaging.sub_sock(service_list['controlsState'].port) + Plant.plan = messaging.sub_sock(service_list['plan'].port) Plant.messaging_initialized = True self.angle_steer = 0. @@ -135,6 +137,7 @@ class Plant(object): def close(self): Plant.logcan.close() Plant.model.close() + Plant.live_params.close() def speed_sensor(self, speed): if speed<0.3: @@ -322,6 +325,31 @@ class Plant(object): Plant.logcan.send(can_list_to_can_capnp(can_msgs)) + # Fake sockets that controlsd subscribes to + live_parameters = messaging.new_message() + live_parameters.init('liveParameters') + live_parameters.liveParameters.valid = True + live_parameters.liveParameters.sensorValid = True + live_parameters.liveParameters.steerRatio = CP.steerRatio + live_parameters.liveParameters.stiffnessFactor = 1.0 + Plant.live_params.send(live_parameters.to_bytes()) + + driver_monitoring = messaging.new_message() + driver_monitoring.init('driverMonitoring') + driver_monitoring.driverMonitoring.descriptor = [0.] * 7 + Plant.driverMonitoring.send(driver_monitoring.to_bytes()) + + health = messaging.new_message() + health.init('health') + health.health.controlsAllowed = True + Plant.health.send(health.to_bytes()) + + thermal = messaging.new_message() + thermal.init('thermal') + thermal.thermal.freeSpace = 1. + thermal.thermal.batteryPercent = 100 + Plant.thermal.send(thermal.to_bytes()) + # ******** publish a fake model going straight and fake calibration ******** # note that this is worst case for MPC, since model will delay long mpc by one time step if publish_model and self.rk.frame % 5 == 0: diff --git a/selfdrive/test/test_fingerprints.py b/selfdrive/test/test_fingerprints.py index b247b4ca1d..721ea163fc 100755 --- a/selfdrive/test/test_fingerprints.py +++ b/selfdrive/test/test_fingerprints.py @@ -21,9 +21,9 @@ def _get_fingerprints(): def check_fingerprint_consistency(f1, f2): # return false if it finds a fingerprint fully included in another - # max message worth checking is 1900, as above that they usually come too infrequently and not + # max message worth checking is 1800, as above that they usually come too infrequently and not # usable for fingerprinting - max_msg = 1900 + max_msg = 1800 is_f1_in_f2 = True for k in f1: diff --git a/selfdrive/thermald.py b/selfdrive/thermald.py index e3c02dc062..ef75cfffd9 100755 --- a/selfdrive/thermald.py +++ b/selfdrive/thermald.py @@ -1,6 +1,5 @@ #!/usr/bin/env python2.7 import os -import zmq from smbus2 import SMBus from cereal import log from selfdrive.version import training_version @@ -128,10 +127,9 @@ def thermald_thread(): BATT_PERC_OFF = 10 if LEON else 3 # now loop - context = zmq.Context() - thermal_sock = messaging.pub_sock(context, service_list['thermal'].port) - health_sock = messaging.sub_sock(context, service_list['health'].port) - location_sock = messaging.sub_sock(context, service_list['gpsLocation'].port) + thermal_sock = messaging.pub_sock(service_list['thermal'].port) + health_sock = messaging.sub_sock(service_list['health'].port) + location_sock = messaging.sub_sock(service_list['gpsLocation'].port) fan_speed = 0 count = 0 diff --git a/selfdrive/tombstoned.py b/selfdrive/tombstoned.py index 3d7061c6a6..3af76818d4 100644 --- a/selfdrive/tombstoned.py +++ b/selfdrive/tombstoned.py @@ -101,7 +101,7 @@ def report_tombstone(fn, client): cloudlog.error({'tombstone': message}) -def main(gctx): +def main(gctx=None): initial_tombstones = set(get_tombstones()) client = Client('https://d3b175702f62402c91ade04d1c547e68:b20d68c813c74f63a7cdf9c4039d8f56@sentry.io/157615', @@ -119,4 +119,4 @@ def main(gctx): time.sleep(5) if __name__ == "__main__": - main(None) + main() diff --git a/selfdrive/ui/Makefile b/selfdrive/ui/Makefile index a2d857a28d..c6cce40a5e 100644 --- a/selfdrive/ui/Makefile +++ b/selfdrive/ui/Makefile @@ -13,13 +13,9 @@ WARN_FLAGS = -Werror=implicit-function-declaration \ CFLAGS = -std=gnu11 -fPIC -O2 $(WARN_FLAGS) CXXFLAGS = -std=c++11 -fPIC -O2 $(WARN_FLAGS) -ZMQ_FLAGS = -I$(PHONELIBS)/zmq/aarch64/include -ZMQ_LIBS = -L$(PHONELIBS)/zmq/aarch64/lib \ - -l:libczmq.a -l:libzmq.a \ - -lgnustl_shared +ZMQ_LIBS = -l:libczmq.a -l:libzmq.a -lgnustl_shared -CEREAL_CFLAGS = -I$(PHONELIBS)/capnp-c/include -CEREAL_LIBS = -L$(PHONELIBS)/capnp-c/aarch64/lib -l:libcapn.a +CEREAL_LIBS = -l:libcapn.a CEREAL_OBJS = ../../cereal/gen/c/log.capnp.o NANOVG_FLAGS = -I$(PHONELIBS)/nanovg @@ -32,10 +28,23 @@ OPENGL_LIBS = -lGLESv3 OPENSL_LIBS = -lOpenSLES +UUID_LIBS = -luuid + FRAMEBUFFER_LIBS = -lutils -lgui -lEGL -CFLAGS += -DQCOM -CXXFLAGS += -DQCOM +CFLAGS += -DQCOM \ + -I$(PHONELIBS)/android_frameworks_native/include \ + -I$(PHONELIBS)/android_system_core/include \ + -I$(PHONELIBS)/android_hardware_libhardware/include +CXXFLAGS += -DQCOM \ + -I$(PHONELIBS)/android_frameworks_native/include \ + -I$(PHONELIBS)/android_system_core/include \ + -I$(PHONELIBS)/android_hardware_libhardware/include + +ifeq ($(ARCH),aarch64) +CFLAGS += -mcpu=cortex-a57 +CXXFLAGS += -mcpu=cortex-a57 +endif OBJS = slplay.o \ ui.o \ @@ -68,6 +77,7 @@ ui: $(OBJS) $(OPENGL_LIBS) \ $(OPENCL_LIBS) \ ${OPENSL_LIBS} \ + ${UUID_LIBS} \ -Wl,-rpath=/system/lib64,-rpath=/system/comma/usr/lib \ -lcutils -lm -llog -lui -ladreno_utils diff --git a/selfdrive/ui/spinner/spinner b/selfdrive/ui/spinner/spinner index 326a377aa3..acc86c78cd 100755 Binary files a/selfdrive/ui/spinner/spinner and b/selfdrive/ui/spinner/spinner differ diff --git a/selfdrive/ui/spinner/spinner.c b/selfdrive/ui/spinner/spinner.c index 477cfe1cf3..ad74251502 100644 --- a/selfdrive/ui/spinner/spinner.c +++ b/selfdrive/ui/spinner/spinner.c @@ -6,6 +6,7 @@ #include #include +#include #include #include "nanovg.h" diff --git a/selfdrive/ui/start.py b/selfdrive/ui/start.py index 08bd6217eb..e3e629b545 100755 --- a/selfdrive/ui/start.py +++ b/selfdrive/ui/start.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2 import os assert os.system("make") == 0 diff --git a/selfdrive/ui/ui.c b/selfdrive/ui/ui.c index b6a97724cc..6e24c9220b 100644 --- a/selfdrive/ui/ui.c +++ b/selfdrive/ui/ui.c @@ -458,6 +458,7 @@ sound_file* get_sound_file_by_name(const char* name) { return NULL; } + void ui_sound_init(char **error) { slplay_setup(error); if (*error) return; @@ -1567,10 +1568,15 @@ static PathData read_path(cereal_ModelData_PathData_ptr pathp) { ret.prob = pathd.prob; ret.std = pathd.std; - capn_list32 pointl = pathd.points; - capn_resolve(&pointl.p); - for (int i = 0; i < 50; i++) { - ret.points[i] = capn_to_f32(capn_get32(pointl, i)); + capn_list32 polyp = pathd.poly; + capn_resolve(&polyp.p); + for (int i = 0; i < POLYFIT_DEGREE; i++) { + ret.poly[i] = capn_to_f32(capn_get32(polyp, i)); + } + + // Compute points locations + for (int i = 0; i < MODEL_PATH_DISTANCE; i++) { + ret.points[i] = ret.poly[0] * (i*i*i) + ret.poly[1] * (i*i)+ ret.poly[2] * i + ret.poly[3]; } return ret; @@ -1603,6 +1609,216 @@ static void update_status(UIState *s, int status) { } } + +void handle_message(UIState *s, void *which) { + int err; + zmq_msg_t msg; + err = zmq_msg_init(&msg); + assert(err == 0); + err = zmq_msg_recv(&msg, which, 0); + assert(err >= 0); + + struct capn ctx; + capn_init_mem(&ctx, zmq_msg_data(&msg), zmq_msg_size(&msg), 0); + + cereal_Event_ptr eventp; + eventp.p = capn_getp(capn_root(&ctx), 0, 1); + struct cereal_Event eventd; + cereal_read_Event(&eventd, eventp); + double t = millis_since_boot(); + if (eventd.which == cereal_Event_controlsState) { + struct cereal_ControlsState datad; + cereal_read_ControlsState(&datad, eventd.controlsState); + + if (datad.vCruise != s->scene.v_cruise) { + s->scene.v_cruise_update_ts = eventd.logMonoTime; + } + s->scene.v_cruise = datad.vCruise; + s->scene.v_ego = datad.vEgo; + s->scene.curvature = datad.curvature; + s->scene.engaged = datad.enabled; + s->scene.engageable = datad.engageable; + s->scene.gps_planner_active = datad.gpsPlannerActive; + s->scene.monitoring_active = datad.driverMonitoringOn; + + s->scene.frontview = datad.rearViewCam; + + s->scene.v_curvature = datad.vCurvature; + s->scene.decel_for_turn = datad.decelForTurn; + + if (datad.alertSound.str && datad.alertSound.str[0] != '\0' && strcmp(s->alert_type, datad.alertType.str) != 0) { + char* error = NULL; + if (s->alert_sound[0] != '\0') { + sound_file* active_sound = get_sound_file_by_name(s->alert_sound); + slplay_stop_uri(active_sound->uri, &error); + if (error) { + LOGW("error stopping active sound %s", error); + } + } + + sound_file* sound = get_sound_file_by_name(datad.alertSound.str); + slplay_play(sound->uri, sound->loop, &error); + if(error) { + LOGW("error playing sound: %s", error); + } + + snprintf(s->alert_sound, sizeof(s->alert_sound), "%s", datad.alertSound.str); + snprintf(s->alert_type, sizeof(s->alert_type), "%s", datad.alertType.str); + } else if ((!datad.alertSound.str || datad.alertSound.str[0] == '\0') && s->alert_sound[0] != '\0') { + sound_file* sound = get_sound_file_by_name(s->alert_sound); + + char* error = NULL; + + slplay_stop_uri(sound->uri, &error); + if(error) { + LOGW("error stopping sound: %s", error); + } + s->alert_type[0] = '\0'; + s->alert_sound[0] = '\0'; + } + + if (datad.alertText1.str) { + snprintf(s->scene.alert_text1, sizeof(s->scene.alert_text1), "%s", datad.alertText1.str); + } else { + s->scene.alert_text1[0] = '\0'; + } + if (datad.alertText2.str) { + snprintf(s->scene.alert_text2, sizeof(s->scene.alert_text2), "%s", datad.alertText2.str); + } else { + s->scene.alert_text2[0] = '\0'; + } + s->scene.awareness_status = datad.awarenessStatus; + + s->scene.alert_ts = eventd.logMonoTime; + + s->scene.alert_size = datad.alertSize; + if (datad.alertSize == cereal_ControlsState_AlertSize_none) { + s->alert_size = ALERTSIZE_NONE; + } else if (datad.alertSize == cereal_ControlsState_AlertSize_small) { + s->alert_size = ALERTSIZE_SMALL; + } else if (datad.alertSize == cereal_ControlsState_AlertSize_mid) { + s->alert_size = ALERTSIZE_MID; + } else if (datad.alertSize == cereal_ControlsState_AlertSize_full) { + s->alert_size = ALERTSIZE_FULL; + } + + if (datad.alertStatus == cereal_ControlsState_AlertStatus_userPrompt) { + update_status(s, STATUS_WARNING); + } else if (datad.alertStatus == cereal_ControlsState_AlertStatus_critical) { + update_status(s, STATUS_ALERT); + } else if (datad.enabled) { + update_status(s, STATUS_ENGAGED); + } else { + update_status(s, STATUS_DISENGAGED); + } + + s->scene.alert_blinkingrate = datad.alertBlinkingRate; + if (datad.alertBlinkingRate > 0.) { + if (s->alert_blinked) { + if (s->alert_blinking_alpha > 0.0 && s->alert_blinking_alpha < 1.0) { + s->alert_blinking_alpha += (0.05*datad.alertBlinkingRate); + } else { + s->alert_blinked = false; + } + } else { + if (s->alert_blinking_alpha > 0.25) { + s->alert_blinking_alpha -= (0.05*datad.alertBlinkingRate); + } else { + s->alert_blinking_alpha += 0.25; + s->alert_blinked = true; + } + } + } + } else if (eventd.which == cereal_Event_radarState) { + struct cereal_RadarState datad; + cereal_read_RadarState(&datad, eventd.radarState); + struct cereal_RadarState_LeadData leaddatad; + cereal_read_RadarState_LeadData(&leaddatad, datad.leadOne); + s->scene.lead_status = leaddatad.status; + s->scene.lead_d_rel = leaddatad.dRel; + s->scene.lead_y_rel = leaddatad.yRel; + s->scene.lead_v_rel = leaddatad.vRel; + s->livempc_or_radarstate_changed = true; + } else if (eventd.which == cereal_Event_liveCalibration) { + s->scene.world_objects_visible = true; + struct cereal_LiveCalibrationData datad; + cereal_read_LiveCalibrationData(&datad, eventd.liveCalibration); + + // should we still even have this? + capn_list32 warpl = datad.warpMatrix2; + capn_resolve(&warpl.p); // is this a bug? + for (int i = 0; i < 3 * 3; i++) { + s->scene.warp_matrix.v[i] = capn_to_f32(capn_get32(warpl, i)); + } + + capn_list32 extrinsicl = datad.extrinsicMatrix; + capn_resolve(&extrinsicl.p); // is this a bug? + for (int i = 0; i < 3 * 4; i++) { + s->scene.extrinsic_matrix.v[i] = + capn_to_f32(capn_get32(extrinsicl, i)); + } + } else if (eventd.which == cereal_Event_model) { + s->scene.model_ts = eventd.logMonoTime; + s->scene.model = read_model(eventd.model); + s->model_changed = true; + } else if (eventd.which == cereal_Event_liveMpc) { + struct cereal_LiveMpcData datad; + cereal_read_LiveMpcData(&datad, eventd.liveMpc); + + capn_list32 x_list = datad.x; + capn_resolve(&x_list.p); + + for (int i = 0; i < 50; i++){ + s->scene.mpc_x[i] = capn_to_f32(capn_get32(x_list, i)); + } + + capn_list32 y_list = datad.y; + capn_resolve(&y_list.p); + + for (int i = 0; i < 50; i++){ + s->scene.mpc_y[i] = capn_to_f32(capn_get32(y_list, i)); + } + s->livempc_or_radarstate_changed = true; + } else if (eventd.which == cereal_Event_thermal) { + struct cereal_ThermalData datad; + cereal_read_ThermalData(&datad, eventd.thermal); + + if (!datad.started) { + update_status(s, STATUS_STOPPED); + } else if (s->status == STATUS_STOPPED) { + // car is started but controls doesn't have fingerprint yet + update_status(s, STATUS_DISENGAGED); + } + + s->scene.started_ts = datad.startedTs; + } else if (eventd.which == cereal_Event_uiLayoutState) { + struct cereal_UiLayoutState datad; + cereal_read_UiLayoutState(&datad, eventd.uiLayoutState); + s->scene.uilayout_sidebarcollapsed = datad.sidebarCollapsed; + s->scene.uilayout_mapenabled = datad.mapEnabled; + + bool hasSidebar = !s->scene.uilayout_sidebarcollapsed; + bool mapEnabled = s->scene.uilayout_mapenabled; + if (mapEnabled) { + s->scene.ui_viz_rx = hasSidebar ? (box_x+nav_w) : (box_x+nav_w-(bdr_s*4)); + s->scene.ui_viz_rw = hasSidebar ? (box_w-nav_w) : (box_w-nav_w+(bdr_s*4)); + s->scene.ui_viz_ro = -(sbr_w + 4*bdr_s); + } else { + s->scene.ui_viz_rx = hasSidebar ? box_x : (box_x-sbr_w+bdr_s*2); + s->scene.ui_viz_rw = hasSidebar ? box_w : (box_w+sbr_w-(bdr_s*2)); + s->scene.ui_viz_ro = hasSidebar ? -(sbr_w - 6*bdr_s) : 0; + } + } else if (eventd.which == cereal_Event_liveMapData) { + struct cereal_LiveMapData datad; + cereal_read_LiveMapData(&datad, eventd.liveMapData); + s->scene.speedlimit = datad.speedLimit; + s->scene.speedlimit_valid = datad.speedLimitValid; + s->scene.map_valid = datad.mapValid; + } + capn_free(&ctx); + zmq_msg_close(&msg); +} + static void ui_update(UIState *s) { int err; @@ -1798,222 +2014,11 @@ static void ui_update(UIState *s) { } else { // zmq messages - void* which = NULL; for (int i=0; i= 0); - - struct capn ctx; - capn_init_mem(&ctx, zmq_msg_data(&msg), zmq_msg_size(&msg), 0); - - cereal_Event_ptr eventp; - eventp.p = capn_getp(capn_root(&ctx), 0, 1); - struct cereal_Event eventd; - cereal_read_Event(&eventd, eventp); - double t = millis_since_boot(); - if (eventd.which == cereal_Event_controlsState) { - struct cereal_ControlsState datad; - cereal_read_ControlsState(&datad, eventd.controlsState); - - if (datad.vCruise != s->scene.v_cruise) { - s->scene.v_cruise_update_ts = eventd.logMonoTime; - } - s->scene.v_cruise = datad.vCruise; - s->scene.v_ego = datad.vEgo; - s->scene.curvature = datad.curvature; - s->scene.engaged = datad.enabled; - s->scene.engageable = datad.engageable; - s->scene.gps_planner_active = datad.gpsPlannerActive; - s->scene.monitoring_active = datad.driverMonitoringOn; - - s->scene.frontview = datad.rearViewCam; - - s->scene.v_curvature = datad.vCurvature; - s->scene.decel_for_turn = datad.decelForTurn; - - if (datad.alertSound.str && datad.alertSound.str[0] != '\0' && strcmp(s->alert_type, datad.alertType.str) != 0) { - char* error = NULL; - if (s->alert_sound[0] != '\0') { - sound_file* active_sound = get_sound_file_by_name(s->alert_sound); - slplay_stop_uri(active_sound->uri, &error); - if (error) { - LOGW("error stopping active sound %s", error); - } - } - - sound_file* sound = get_sound_file_by_name(datad.alertSound.str); - slplay_play(sound->uri, sound->loop, &error); - if(error) { - LOGW("error playing sound: %s", error); - } - - snprintf(s->alert_sound, sizeof(s->alert_sound), "%s", datad.alertSound.str); - snprintf(s->alert_type, sizeof(s->alert_type), "%s", datad.alertType.str); - } else if ((!datad.alertSound.str || datad.alertSound.str[0] == '\0') && s->alert_sound[0] != '\0') { - sound_file* sound = get_sound_file_by_name(s->alert_sound); - - char* error = NULL; - - slplay_stop_uri(sound->uri, &error); - if(error) { - LOGW("error stopping sound: %s", error); - } - s->alert_type[0] = '\0'; - s->alert_sound[0] = '\0'; - } - - if (datad.alertText1.str) { - snprintf(s->scene.alert_text1, sizeof(s->scene.alert_text1), "%s", datad.alertText1.str); - } else { - s->scene.alert_text1[0] = '\0'; - } - if (datad.alertText2.str) { - snprintf(s->scene.alert_text2, sizeof(s->scene.alert_text2), "%s", datad.alertText2.str); - } else { - s->scene.alert_text2[0] = '\0'; - } - s->scene.awareness_status = datad.awarenessStatus; - - s->scene.alert_ts = eventd.logMonoTime; - - s->scene.alert_size = datad.alertSize; - if (datad.alertSize == cereal_ControlsState_AlertSize_none) { - s->alert_size = ALERTSIZE_NONE; - } else if (datad.alertSize == cereal_ControlsState_AlertSize_small) { - s->alert_size = ALERTSIZE_SMALL; - } else if (datad.alertSize == cereal_ControlsState_AlertSize_mid) { - s->alert_size = ALERTSIZE_MID; - } else if (datad.alertSize == cereal_ControlsState_AlertSize_full) { - s->alert_size = ALERTSIZE_FULL; - } - - if (datad.alertStatus == cereal_ControlsState_AlertStatus_userPrompt) { - update_status(s, STATUS_WARNING); - } else if (datad.alertStatus == cereal_ControlsState_AlertStatus_critical) { - update_status(s, STATUS_ALERT); - } else if (datad.enabled) { - update_status(s, STATUS_ENGAGED); - } else { - update_status(s, STATUS_DISENGAGED); - } - - s->scene.alert_blinkingrate = datad.alertBlinkingRate; - if (datad.alertBlinkingRate > 0.) { - if (s->alert_blinked) { - if (s->alert_blinking_alpha > 0.0 && s->alert_blinking_alpha < 1.0) { - s->alert_blinking_alpha += (0.05*datad.alertBlinkingRate); - } else { - s->alert_blinked = false; - } - } else { - if (s->alert_blinking_alpha > 0.25) { - s->alert_blinking_alpha -= (0.05*datad.alertBlinkingRate); - } else { - s->alert_blinking_alpha += 0.25; - s->alert_blinked = true; - } - } - } - } else if (eventd.which == cereal_Event_radarState) { - struct cereal_RadarState datad; - cereal_read_RadarState(&datad, eventd.radarState); - struct cereal_RadarState_LeadData leaddatad; - cereal_read_RadarState_LeadData(&leaddatad, datad.leadOne); - s->scene.lead_status = leaddatad.status; - s->scene.lead_d_rel = leaddatad.dRel; - s->scene.lead_y_rel = leaddatad.yRel; - s->scene.lead_v_rel = leaddatad.vRel; - s->livempc_or_radarstate_changed = true; - } else if (eventd.which == cereal_Event_liveCalibration) { - s->scene.world_objects_visible = true; - struct cereal_LiveCalibrationData datad; - cereal_read_LiveCalibrationData(&datad, eventd.liveCalibration); - - // should we still even have this? - capn_list32 warpl = datad.warpMatrix2; - capn_resolve(&warpl.p); // is this a bug? - for (int i = 0; i < 3 * 3; i++) { - s->scene.warp_matrix.v[i] = capn_to_f32(capn_get32(warpl, i)); - } - - capn_list32 extrinsicl = datad.extrinsicMatrix; - capn_resolve(&extrinsicl.p); // is this a bug? - for (int i = 0; i < 3 * 4; i++) { - s->scene.extrinsic_matrix.v[i] = - capn_to_f32(capn_get32(extrinsicl, i)); - } - } else if (eventd.which == cereal_Event_model) { - s->scene.model_ts = eventd.logMonoTime; - s->scene.model = read_model(eventd.model); - s->model_changed = true; - } else if (eventd.which == cereal_Event_liveMpc) { - struct cereal_LiveMpcData datad; - cereal_read_LiveMpcData(&datad, eventd.liveMpc); - - capn_list32 x_list = datad.x; - capn_resolve(&x_list.p); - - for (int i = 0; i < 50; i++){ - s->scene.mpc_x[i] = capn_to_f32(capn_get32(x_list, i)); + handle_message(s, polls[i].socket); } - - capn_list32 y_list = datad.y; - capn_resolve(&y_list.p); - - for (int i = 0; i < 50; i++){ - s->scene.mpc_y[i] = capn_to_f32(capn_get32(y_list, i)); - } - s->livempc_or_radarstate_changed = true; - } else if (eventd.which == cereal_Event_thermal) { - struct cereal_ThermalData datad; - cereal_read_ThermalData(&datad, eventd.thermal); - - if (!datad.started) { - update_status(s, STATUS_STOPPED); - } else if (s->status == STATUS_STOPPED) { - // car is started but controls doesn't have fingerprint yet - update_status(s, STATUS_DISENGAGED); - } - - s->scene.started_ts = datad.startedTs; - } else if (eventd.which == cereal_Event_uiLayoutState) { - struct cereal_UiLayoutState datad; - cereal_read_UiLayoutState(&datad, eventd.uiLayoutState); - s->scene.uilayout_sidebarcollapsed = datad.sidebarCollapsed; - s->scene.uilayout_mapenabled = datad.mapEnabled; - - bool hasSidebar = !s->scene.uilayout_sidebarcollapsed; - bool mapEnabled = s->scene.uilayout_mapenabled; - if (mapEnabled) { - s->scene.ui_viz_rx = hasSidebar ? (box_x+nav_w) : (box_x+nav_w-(bdr_s*4)); - s->scene.ui_viz_rw = hasSidebar ? (box_w-nav_w) : (box_w-nav_w+(bdr_s*4)); - s->scene.ui_viz_ro = -(sbr_w + 4*bdr_s); - } else { - s->scene.ui_viz_rx = hasSidebar ? box_x : (box_x-sbr_w+bdr_s*2); - s->scene.ui_viz_rw = hasSidebar ? box_w : (box_w+sbr_w-(bdr_s*2)); - s->scene.ui_viz_ro = hasSidebar ? -(sbr_w - 6*bdr_s) : 0; - } - } else if (eventd.which == cereal_Event_liveMapData) { - struct cereal_LiveMapData datad; - cereal_read_LiveMapData(&datad, eventd.liveMapData); - s->scene.speedlimit = datad.speedLimit; - s->scene.speedlimit_valid = datad.speedLimitValid; - s->scene.map_valid = datad.mapValid; } - capn_free(&ctx); - zmq_msg_close(&msg); } } } @@ -2191,6 +2196,8 @@ int is_leon() { return strstr(str, "letv") != NULL; } + + int main(int argc, char* argv[]) { int err; setpriority(PRIO_PROCESS, 0, -14); @@ -2231,8 +2238,8 @@ int main(int argc, char* argv[]) { // light sensor scaling params const int LEON = is_leon(); - const float BRIGHTNESS_B = LEON? 10.0 : 5.0; - const float BRIGHTNESS_M = LEON? 2.6 : 1.3; + const float BRIGHTNESS_B = LEON ? 10.0 : 5.0; + const float BRIGHTNESS_M = LEON ? 2.6 : 1.3; float smooth_brightness = BRIGHTNESS_B; @@ -2253,8 +2260,9 @@ int main(int argc, char* argv[]) { // light sensor is only exposed on EONs float clipped_brightness = (s->light_sensor*BRIGHTNESS_M) + BRIGHTNESS_B; - if (clipped_brightness > 255) clipped_brightness = 255; + if (clipped_brightness > 512) clipped_brightness = 512; smooth_brightness = clipped_brightness * 0.01 + smooth_brightness * 0.99; + if (smooth_brightness > 255) smooth_brightness = 255; set_brightness(s, (int)smooth_brightness); if (!s->vision_connected) { diff --git a/selfdrive/visiond/SConscript b/selfdrive/visiond/SConscript deleted file mode 100644 index e55fbd94d9..0000000000 --- a/selfdrive/visiond/SConscript +++ /dev/null @@ -1,17 +0,0 @@ -Import('env') -lenv = env.Clone() -lenv['CPPPATH'] += ['include'] -lenv['LIBPATH'] += ['/system/vendor/lib64'] -lenv['CFLAGS'] += ' -DQCOM' -lenv['CXXFLAGS'] += ' -DQCOM -U __ANDROID__' -lenv.Program(['visiond.cc', 'model.c', 'transform.c', 'loadyuv.c', 'buffering.c', 'efd.c', - 'yuvmodel.c', 'temporalmodel.c', 'monitoring.c', 'monitoringmodel.c', 'clutil.c', - 'camera_qcom.c', 'visionbuf_ion.c'], - LIBS=['zmq', 'czmq', 'capnp', 'capnp_c', 'kj', 'yaml-cpp', 'z', 'curl', - 'gsl', 'CB', 'OpenCL', - 'opencv_video', 'opencv_imgproc', 'opencv_core', - 'gnustl_shared', 'log', 'cutils', - 'yuv', - 'common', 'cereal', - ]) - diff --git a/selfdrive/visiond/build_from_src.mk b/selfdrive/visiond/build_from_src.mk index c9394f34a8..d9d320cf3b 100644 --- a/selfdrive/visiond/build_from_src.mk +++ b/selfdrive/visiond/build_from_src.mk @@ -12,13 +12,13 @@ WARN_FLAGS = -Werror=implicit-function-declaration \ -Werror=format-extra-args \ -Wno-deprecated-declarations -CFLAGS = -std=gnu11 -fPIC -O2 $(WARN_FLAGS) -CXXFLAGS = -std=c++14 -fPIC -O2 $(WARN_FLAGS) +CFLAGS = -I. -std=gnu11 -fPIC -O2 $(WARN_FLAGS) +CXXFLAGS = -I. -std=c++14 -fPIC -O2 $(WARN_FLAGS) -#ifneq ($(RELEASE),1) -#CFLAGS += -g -#CXXFLAGS += -g -#endif +ifeq ($(ARCH),aarch64) +CFLAGS += -mcpu=cortex-a57 +CXXFLAGS += -mcpu=cortex-a57 +endif JSON_FLAGS = -I$(PHONELIBS)/json/src JSON11_FLAGS = -I$(PHONELIBS)/json11/ @@ -38,45 +38,53 @@ ifeq ($(UNAME_S),Darwin) $(PHONELIBS)/zmq/mac/lib/libzmq.a OPENCL_LIBS = -framework OpenCL + + PLATFORM_OBJS = cameras/camera_fake.o \ + ../common/visionbuf_cl.o else - LIBYUV_FLAGS = -I$(PHONELIBS)/libyuv/x64/include + # assume x86_64 linux + LIBYUV_FLAGS = -I$(PHONELIBS)/libyuv/include LIBYUV_LIBS = $(PHONELIBS)/libyuv/x64/lib/libyuv.a - ZMQ_FLAGS = -I$(EXTERNAL)/zmq/include - ZMQ_LIBS = -L$(EXTERNAL)/zmq/lib \ - -l:libczmq.a -l:libzmq.a + ZMQ_FLAGS = -I$(PHONELIBS)/zmq/aarch64/include + ZMQ_LIBS = -l:libczmq.a -l:libzmq.a -lsodium OPENCL_LIBS = -lOpenCL -endif + UUID_LIBS = -luuid + + TF_FLAGS = -I$(EXTERNAL)/tensorflow/include + TF_LIBS = -L$(EXTERNAL)/tensorflow/lib -ltensorflow \ + -Wl,-rpath $(EXTERNAL)/tensorflow/lib + + SNPE_FLAGS = -I$(PHONELIBS)/snpe/include/ + SNPE_LIBS = -L$(PHONELIBS)/snpe/x86_64-linux-clang/ \ + -lSNPE -lsymphony-cpu \ + -Wl,-rpath $(PHONELIBS)/snpe/x86_64-linux-clang/ + + CFLAGS += -g + CXXFLAGS += -g -I../common - CURL_FLAGS = -I/usr/include/curl - CURL_LIBS = -lcurl -lz + PLATFORM_OBJS = cameras/camera_frame_stream.o \ + ../common/visionbuf_cl.o \ + ../common/visionimg.o \ + runners/tfmodel.o +endif SSL_FLAGS = -I/usr/include/openssl/ SSL_LIBS = -lssl -lcrypto - OPENCV_FLAGS = - OPENCV_LIBS = -lopencv_video \ - -lopencv_imgproc \ - -lopencv_core \ - -lopencv_highgui OTHER_LIBS = -lz -lm -lpthread - PLATFORM_OBJS = camera_fake.o \ - ../common/visionbuf_cl.o - CFLAGS += -D_GNU_SOURCE \ -DCLU_NO_CACHE + OBJS = visiond.o else # assume phone LIBYUV_FLAGS = -I$(PHONELIBS)/libyuv/include LIBYUV_LIBS = $(PHONELIBS)/libyuv/lib/libyuv.a - ZMQ_FLAGS = -I$(PHONELIBS)/zmq/aarch64/include - ZMQ_LIBS = -L$(PHONELIBS)/zmq/aarch64/lib \ - -l:libczmq.a -l:libzmq.a \ - -lgnustl_shared + ZMQ_LIBS = -l:libczmq.a -l:libzmq.a -lgnustl_shared CURL_FLAGS = -I$(PHONELIBS)/curl/include CURL_LIBS = $(PHONELIBS)/curl/lib/libcurl.a \ @@ -89,27 +97,31 @@ else OPENCL_FLAGS = -I$(PHONELIBS)/opencl/include OPENCL_LIBS = -lgsl -lCB -lOpenCL - OPENCV_FLAGS = -I/usr/local/sdk/native/jni/include - OPENCV_LIBS = -L/usr/local/sdk/native/libs \ - -l:libopencv_video.a \ - -l:libopencv_imgproc.a \ - -l:libopencv_core.a - OPENGL_LIBS = -lGLESv3 -lEGL + UUID_LIBS = -luuid SNPE_FLAGS = -I$(PHONELIBS)/snpe/include/ SNPE_LIBS = -lSNPE -lsymphony-cpu -lsymphonypower OTHER_LIBS = -lz -lcutils -lm -llog -lui -ladreno_utils - PLATFORM_OBJS = camera_qcom.o \ - ../common/visionbuf_ion.o - - CFLAGS += -DQCOM - CXXFLAGS += -DQCOM + PLATFORM_OBJS = cameras/camera_qcom.o \ + ../common/visionbuf_ion.o \ + ../common/visionimg.o + + CFLAGS += -DQCOM \ + -I$(PHONELIBS)/android_system_core/include \ + -I$(PHONELIBS)/android_frameworks_native/include \ + -I$(PHONELIBS)/android_hardware_libhardware/include \ + -I$(PHONELIBS)/linux/include + CXXFLAGS += -DQCOM \ + -I$(PHONELIBS)/android_system_core/include \ + -I$(PHONELIBS)/android_frameworks_native/include \ + -I$(PHONELIBS)/android_hardware_libhardware/include \ + -I$(PHONELIBS)/linux/include + OBJS = visiond.o endif -OBJS = visiond.o OUTPUT = visiond .PHONY: all @@ -121,58 +133,26 @@ OBJS += $(PLATFORM_OBJS) \ ../common/swaglog.o \ ../common/ipc.o \ ../common/visionipc.o \ - ../common/visionimg.o \ ../common/util.o \ ../common/params.o \ ../common/efd.o \ ../common/buffering.o \ - transform.o \ - loadyuv.o \ - rgb_to_yuv.o \ - commonmodel.o \ - snpemodel.o \ - monitoring.o \ - model.o \ + transforms/transform.o \ + transforms/loadyuv.o \ + transforms/rgb_to_yuv.o \ + models/commonmodel.o \ + runners/snpemodel.o \ + models/posenet.o \ + models/monitoring.o \ + models/driving.o \ clutil.o \ $(PHONELIBS)/json/src/json.o \ $(PHONELIBS)/json11/json11.o \ $(CEREAL_OBJS) -#MODEL_DATA = ../../models/driving_bigmodel.dlc ../../models/monitoring_model.dlc -MODEL_DATA = ../../models/driving_model.dlc ../../models/monitoring_model.dlc ../../models/posenet.dlc -MODEL_OBJS = $(MODEL_DATA:.dlc=.o) -OBJS += $(MODEL_OBJS) - -ifeq ($(RELEASE),1) -CFLAGS += -DCLU_NO_SRC -CXXFLAGS += -DCLU_NO_SRC -CLCACHE_FILES = $(wildcard /tmp/clcache/*.clb) -CLCACHE_OBJS += $(CLCACHE_FILES:.clb=.o) -OBJS += $(CLCACHE_OBJS) - -clutil.o: clcache_bins.h -clcache_bins.h: $(CLCACHE_FILES) /tmp/clcache/index.cli - rm -f '$@' - for hash in $(basename $(notdir $(CLCACHE_FILES))) ; do \ - echo "extern const uint8_t clb_$$hash[] asm(\"_binary_$${hash}_clb_start\");" ; \ - echo "extern const uint8_t clb_$${hash}_end[] asm(\"_binary_$${hash}_clb_end\");" ; \ - done >> '$@' - echo "static const CLUProgramIndex clu_index[] = {" >> '$@' - while read idx_hash code_hash; do \ - echo "{ 0x$$idx_hash, clb_$${code_hash}, clb_$${code_hash}_end }," ; \ - done < /tmp/clcache/index.cli >> '$@' - echo "};" >> '$@' - -$(CLCACHE_OBJS): %.o: %.clb - @echo "[ bin2o ] $@" - cd '$(dir $<)' && ld -r -b binary '$(notdir $<)' -o '$(abspath $@)' - -LDFLAGS += -s -endif - DEPS := $(OBJS:.o=.d) -rgb_to_yuv_test: rgb_to_yuv_test.o clutil.o rgb_to_yuv.o ../common/util.o +rgb_to_yuv_test: transforms/rgb_to_yuv_test.o clutil.o transforms/rgb_to_yuv.o ../common/util.o @echo "[ LINK ] $@" $(CXX) -fPIC -o '$@' $^ \ $(LIBYUV_LIBS) \ @@ -187,16 +167,18 @@ $(OUTPUT): $(OBJS) $(CXX) -fPIC -o '$@' $^ \ $(LDFLAGS) \ $(LIBYUV_LIBS) \ - $(OPENCV_LIBS) \ $(OPENGL_LIBS) \ $(CEREAL_LIBS) \ $(ZMQ_LIBS) \ + -ljpeg \ -L/usr/lib \ -L/system/vendor/lib64 \ $(OPENCL_LIBS) \ $(CURL_LIBS) \ $(SSL_LIBS) \ + $(TF_LIBS) \ $(SNPE_LIBS) \ + $(UUID_LIBS) \ $(OTHER_LIBS) $(MODEL_OBJS): %.o: %.dlc @@ -207,11 +189,12 @@ $(MODEL_OBJS): %.o: %.dlc @echo "[ CXX ] $@" $(CXX) $(CXXFLAGS) -MMD \ -Iinclude -I.. -I../.. \ - $(OPENCV_FLAGS) $(EIGEN_FLAGS) \ + $(EIGEN_FLAGS) \ $(ZMQ_FLAGS) \ $(CEREAL_CXXFLAGS) \ $(OPENCL_FLAGS) \ $(LIBYUV_FLAGS) \ + $(TF_FLAGS) \ $(SNPE_FLAGS) \ $(JSON_FLAGS) \ $(JSON11_FLAGS) $(CURL_FLAGS) \ diff --git a/selfdrive/visiond/camera_fake.cc b/selfdrive/visiond/camera_fake.cc deleted file mode 100644 index 5b7c9cb7b9..0000000000 --- a/selfdrive/visiond/camera_fake.cc +++ /dev/null @@ -1,267 +0,0 @@ -#include "camera_fake.h" - -#include -#include -#include - -#include -#include -#include -#include "cereal/gen/cpp/log.capnp.h" - -#include "common/util.h" -#include "common/timing.h" -#include "common/swaglog.h" -#include "buffering.h" - -extern volatile int do_exit; - -#define FRAME_WIDTH 1164 -#define FRAME_HEIGHT 874 - -namespace { -void camera_open(CameraState *s, VisionBuf *camera_bufs, bool rear) { - assert(camera_bufs); - s->camera_bufs = camera_bufs; -} - -void camera_close(CameraState *s) { - tbuffer_stop(&s->camera_tb); -} - -void camera_release_buffer(void *cookie, int buf_idx) { - CameraState *s = static_cast(cookie); -} - -void camera_init(CameraState *s, int camera_id, unsigned int fps) { - assert(camera_id < ARRAYSIZE(cameras_supported)); - s->ci = cameras_supported[camera_id]; - assert(s->ci.frame_width != 0); - - s->frame_size = s->ci.frame_height * s->ci.frame_stride; - s->fps = fps; - - tbuffer_init2(&s->camera_tb, FRAME_BUF_COUNT, "frame", camera_release_buffer, - s); -} - - -void run_simulator(DualCameraState *s) { - int err = 0; - - zsock_t *frame_sock = zsock_new_sub(">tcp://127.0.0.1:9003", ""); - assert(frame_sock); - void *frame_sock_raw = zsock_resolve(frame_sock); - - CameraState *const rear_camera = &s->rear; - - auto *tb = &rear_camera->camera_tb; - - while (!do_exit) { - const int buf_idx = tbuffer_select(tb); - - auto *buf = &rear_camera->camera_bufs[buf_idx]; - - zmq_msg_t t_msg; - err = zmq_msg_init(&t_msg); - assert(err == 0); - - zmq_msg_t frame_msg; - err = zmq_msg_init(&frame_msg); - assert(err == 0); - - // recv multipart (t, frame) - err = zmq_msg_recv(&t_msg, frame_sock_raw, 0); - assert(err != -1); - err = zmq_msg_recv(&frame_msg, frame_sock_raw, 0); - assert(err != -1); - - assert(zmq_msg_size(&t_msg) >= 8); - uint8_t* dat = (uint8_t*)zmq_msg_data(&t_msg); - float t = *(float*)&dat[0]; - uint32_t frame = *(uint32_t*)&dat[4]; - - rear_camera->camera_bufs_metadata[buf_idx] = { - .frame_id = frame, - .timestamp_eof = nanos_since_boot(), - .frame_length = 0, - .integ_lines = 0, - .global_gain = 0, - }; - - - assert(zmq_msg_size(&frame_msg) == rear_camera->frame_size); - - err = libyuv::RAWToRGB24((const uint8_t*)zmq_msg_data(&frame_msg), rear_camera->ci.frame_width*3, - (uint8_t*)buf->addr, rear_camera->ci.frame_stride, - rear_camera->ci.frame_width, rear_camera->ci.frame_height); - assert(err == 0); - - visionbuf_sync(buf, VISIONBUF_SYNC_TO_DEVICE); - tbuffer_dispatch(tb, buf_idx); - - err = zmq_msg_close(&frame_msg); - assert(err == 0); - err = zmq_msg_close(&t_msg); - assert(err == 0); - } - - zsock_destroy(&frame_sock); -} - -void run_unlogger(DualCameraState *s) { - zsock_t *frame_sock = zsock_new_sub(NULL, ""); - assert(frame_sock); - int err = zsock_connect(frame_sock, - "ipc:///tmp/9464f05d-9d88-4fc9-aa17-c75352d9590d"); - assert(err == 0); - void *frame_sock_raw = zsock_resolve(frame_sock); - - CameraState *const rear_camera = &s->rear; - auto frame_data = std::vector{}; - - auto *tb = &rear_camera->camera_tb; - - while (!do_exit) { - // Handle rear camera only. - zmq_msg_t msg; - int rc = zmq_msg_init(&msg); - assert(rc == 0); - rc = zmq_msg_recv(&msg, frame_sock_raw, 0); - if (rc == -1) { - if (do_exit) { - break; - } else { - fprintf(stderr, "Could not recv frame message: %d\n", errno); - } - } - assert(rc != -1); - - const size_t msg_size_words = zmq_msg_size(&msg) / sizeof(capnp::word); - assert(msg_size_words * sizeof(capnp::word) == zmq_msg_size(&msg)); - - if (frame_data.size() < msg_size_words) { - frame_data = std::vector{msg_size_words}; - } - std::memcpy(frame_data.data(), zmq_msg_data(&msg), - msg_size_words * sizeof(*frame_data.data())); - zmq_msg_close(&msg); - - capnp::FlatArrayMessageReader message{ - kj::arrayPtr(frame_data.data(), msg_size_words), {}}; - - const auto &event = message.getRoot(); - assert(event.which() == cereal::Event::FRAME); - const auto reader = event.getFrame(); - assert(reader.hasImage()); - const auto yuv_image = reader.getImage(); - - // Copy camera data to buffer. - const size_t width = rear_camera->ci.frame_width; - const size_t height = rear_camera->ci.frame_height; - - const size_t y_len = width * height; - const uint8_t *const y = yuv_image.begin(); - const uint8_t *const u = y + y_len; - const uint8_t *const v = u + y_len / 4; - - assert(yuv_image.size() == y_len * 3 / 2); - - const int buf_idx = tbuffer_select(tb); - rear_camera->camera_bufs_metadata[buf_idx] = { - .frame_id = reader.getFrameId(), - .timestamp_eof = reader.getTimestampEof(), - .frame_length = static_cast(reader.getFrameLength()), - .integ_lines = static_cast(reader.getIntegLines()), - .global_gain = static_cast(reader.getGlobalGain()), - }; - - auto *buf = &rear_camera->camera_bufs[buf_idx]; - uint8_t *const rgb = static_cast(buf->addr); - - // Convert to RGB. - const int result = libyuv::I420ToRGB24(y, width, u, width / 2, v, width / 2, - rgb, width * 3, width, height); - assert(result == 0); - - visionbuf_sync(buf, VISIONBUF_SYNC_TO_DEVICE); - - // HACK(mgraczyk): Do not drop frames. - while (*(volatile int*)&tb->pending_idx != -1) { - usleep(20000); - } - tbuffer_dispatch(tb, buf_idx); - } - - zsock_destroy(&frame_sock); -} - -} // namespace - -CameraInfo cameras_supported[CAMERA_ID_MAX] = { - [CAMERA_ID_IMX298] = { - .frame_width = FRAME_WIDTH, - .frame_height = FRAME_HEIGHT, - .frame_stride = FRAME_WIDTH*3, - .bayer = false, - .bayer_flip = false, - }, -}; - -void cameras_init(DualCameraState *s) { - memset(s, 0, sizeof(*s)); - - camera_init(&s->rear, CAMERA_ID_IMX298, 20); - camera_init(&s->front, CAMERA_ID_IMX298, 20); - - if (getenv("SIMULATOR2")) { - // simulator camera is flipped vertically - s->rear.transform = (mat3){{ - 1.0, 0.0, 0.0, - 0.0, -1.0, s->rear.ci.frame_height - 1.0f, - 0.0, 0.0, 1.0, - }}; - } else { - // assume the input is upside-down - s->rear.transform = (mat3){{ - -1.0, 0.0, s->rear.ci.frame_width - 1.0f, - 0.0, -1.0, s->rear.ci.frame_height - 1.0f, - 0.0, 0.0, 1.0, - }}; - } -} - -void cameras_open(DualCameraState *s, VisionBuf *camera_bufs_rear, - VisionBuf *camera_bufs_focus, VisionBuf *camera_bufs_stats, - VisionBuf *camera_bufs_front) { - assert(camera_bufs_rear); - assert(camera_bufs_front); - int err; - - // LOG("*** open front ***"); - camera_open(&s->front, camera_bufs_front, false); - - // LOG("*** open rear ***"); - camera_open(&s->rear, camera_bufs_rear, true); -} - -void cameras_close(DualCameraState *s) { - camera_close(&s->rear); - camera_close(&s->front); -} - -void camera_autoexposure(CameraState *s, float grey_frac) {} - - -void cameras_run(DualCameraState *s) { - set_thread_name("fake_camera"); - - if (getenv("SIMULATOR2")) { - run_simulator(s); - } else { - run_unlogger(s); - } - - cameras_close(s); - -} diff --git a/selfdrive/visiond/camera_fake.h b/selfdrive/visiond/camera_fake.h deleted file mode 100644 index 04ad01a6d0..0000000000 --- a/selfdrive/visiond/camera_fake.h +++ /dev/null @@ -1,52 +0,0 @@ -#ifndef FAKE_CAMERA_H -#define FAKE_CAMERA_H - -#include - -#include "common/mat.h" - -#include "buffering.h" -#include "common/visionbuf.h" -#include "camera_common.h" - -#define FRAME_BUF_COUNT 4 - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct CameraState { - int camera_id; - CameraInfo ci; - int frame_size; - - VisionBuf *camera_bufs; - FrameMetadata camera_bufs_metadata[FRAME_BUF_COUNT]; - TBuffer camera_tb; - - int fps; - float digital_gain; - - mat3 transform; -} CameraState; - - -typedef struct DualCameraState { - int ispif_fd; - - CameraState rear; - CameraState front; -} DualCameraState; - -void cameras_init(DualCameraState *s); -void cameras_open(DualCameraState *s, VisionBuf *camera_bufs_rear, VisionBuf *camera_bufs_focus, VisionBuf *camera_bufs_stats, VisionBuf *camera_bufs_front); -void cameras_run(DualCameraState *s); -void cameras_close(DualCameraState *s); - -void camera_autoexposure(CameraState *s, float grey_frac); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif diff --git a/selfdrive/visiond/camera_common.h b/selfdrive/visiond/cameras/camera_common.h similarity index 100% rename from selfdrive/visiond/camera_common.h rename to selfdrive/visiond/cameras/camera_common.h diff --git a/selfdrive/visiond/camera_qcom.c b/selfdrive/visiond/cameras/camera_qcom.c similarity index 100% rename from selfdrive/visiond/camera_qcom.c rename to selfdrive/visiond/cameras/camera_qcom.c diff --git a/selfdrive/visiond/camera_qcom.h b/selfdrive/visiond/cameras/camera_qcom.h similarity index 100% rename from selfdrive/visiond/camera_qcom.h rename to selfdrive/visiond/cameras/camera_qcom.h diff --git a/selfdrive/visiond/debayer.cl b/selfdrive/visiond/cameras/debayer.cl similarity index 100% rename from selfdrive/visiond/debayer.cl rename to selfdrive/visiond/cameras/debayer.cl diff --git a/selfdrive/visiond/sensor_i2c.h b/selfdrive/visiond/cameras/sensor_i2c.h similarity index 100% rename from selfdrive/visiond/sensor_i2c.h rename to selfdrive/visiond/cameras/sensor_i2c.h diff --git a/selfdrive/visiond/constants.py b/selfdrive/visiond/constants.py index 878478e9cf..56c4b76a3a 100644 --- a/selfdrive/visiond/constants.py +++ b/selfdrive/visiond/constants.py @@ -1,2 +1,3 @@ MAX_DISTANCE = 140. LANE_OFFSET = 1.8 +MAX_REL_V = 10. diff --git a/selfdrive/visiond/model.cc b/selfdrive/visiond/model.cc deleted file mode 100644 index 2fbb4f3c92..0000000000 --- a/selfdrive/visiond/model.cc +++ /dev/null @@ -1,97 +0,0 @@ -#include "common/timing.h" -#include "model.h" - -#ifdef BIGMODEL - #define MODEL_WIDTH 864 - #define MODEL_HEIGHT 288 - #define MODEL_NAME "driving_bigmodel_dlc" -#else - #define MODEL_WIDTH 320 - #define MODEL_HEIGHT 160 - #define MODEL_NAME "driving_model_dlc" -#endif - -#define OUTPUT_SIZE 161 - -#ifdef TEMPORAL - #define TEMPORAL_SIZE 512 -#else - #define TEMPORAL_SIZE 0 -#endif - -extern const uint8_t driving_model_data[] asm("_binary_" MODEL_NAME "_start"); -extern const uint8_t driving_model_end[] asm("_binary_" MODEL_NAME "_end"); -const size_t driving_model_size = driving_model_end - driving_model_data; - -void model_init(ModelState* s, cl_device_id device_id, cl_context context, int temporal) { - model_input_init(&s->in, MODEL_WIDTH, MODEL_HEIGHT, device_id, context); - const int output_size = OUTPUT_SIZE + TEMPORAL_SIZE; - s->output = (float*)malloc(output_size * sizeof(float)); - memset(s->output, 0, output_size * sizeof(float)); - s->m = new SNPEModel(driving_model_data, driving_model_size, s->output, output_size); -#ifdef TEMPORAL - assert(temporal); - s->m->addRecurrent(&s->output[OUTPUT_SIZE], TEMPORAL_SIZE); -#else - assert(!temporal); -#endif -} - -ModelData model_eval_frame(ModelState* s, cl_command_queue q, - cl_mem yuv_cl, int width, int height, - mat3 transform, void* sock) { - struct { - float *path; - float *left_lane; - float *right_lane; - float *lead; - } net_outputs = {NULL}; - - //for (int i = 0; i < OUTPUT_SIZE + TEMPORAL_SIZE; i++) { printf("%f ", s->output[i]); } printf("\n"); - - float *net_input_buf = model_input_prepare(&s->in, q, yuv_cl, width, height, transform); - s->m->execute(net_input_buf); - - // net outputs - net_outputs.path = &s->output[0]; - net_outputs.left_lane = &s->output[51]; - net_outputs.right_lane = &s->output[51+53]; - net_outputs.lead = &s->output[51+53+53]; - - ModelData model = {0}; - - for (int i=0; i 0. ? model.lead.dist : 0.; - - model.lead.std = max_dist * sqrt(2.) / net_outputs.lead[1]; - softmax(&net_outputs.lead[2], softmax_buff, 2); - model.lead.prob = softmax_buff[0]; - - return model; -} - -void model_free(ModelState* s) { - free(s->output); - model_input_free(&s->in); - delete s->m; -} - diff --git a/selfdrive/visiond/commonmodel.c b/selfdrive/visiond/models/commonmodel.c similarity index 92% rename from selfdrive/visiond/commonmodel.c rename to selfdrive/visiond/models/commonmodel.c index 595d2609e7..c2bb657bb5 100644 --- a/selfdrive/visiond/commonmodel.c +++ b/selfdrive/visiond/models/commonmodel.c @@ -59,6 +59,14 @@ void model_input_free(ModelInput* s) { } +float sigmoid(float input) { + return 1 / (1 + expf(-input)); +} + +float softplus(float input) { + return log1p(expf(input)); +} + void softmax(const float* input, float* output, size_t len) { float max_val = -FLT_MAX; for(int i = 0; i < len; i++) { @@ -85,16 +93,16 @@ void softmax(const float* input, float* output, size_t len) { static cereal_ModelData_PathData_ptr path_to_cereal(struct capn_segment *cs, const PathData data) { - capn_list32 points_ptr = capn_new_list32(cs, MODEL_PATH_DISTANCE); - for (int i=0; i +#include +#include +#include + +#ifdef QCOM + #include +#else + #include +#endif + +#include "common/timing.h" +#include "driving.h" + +#ifdef MEDMODEL + #define MODEL_WIDTH 512 + #define MODEL_HEIGHT 256 + #define MODEL_NAME "driving_model_dlc" +#else + #define MODEL_WIDTH 320 + #define MODEL_HEIGHT 160 + #define MODEL_NAME "driving_model_dlc" +#endif + +#define OUTPUT_SIZE (200 + 2*201 + 26) +#define LEAD_MDN_N 5 + +#ifdef TEMPORAL + #define TEMPORAL_SIZE 512 +#else + #define TEMPORAL_SIZE 0 +#endif + +Eigen::Matrix vander; + +void model_init(ModelState* s, cl_device_id device_id, cl_context context, int temporal) { + model_input_init(&s->in, MODEL_WIDTH, MODEL_HEIGHT, device_id, context); + const int output_size = OUTPUT_SIZE + TEMPORAL_SIZE; + s->output = (float*)malloc(output_size * sizeof(float)); + memset(s->output, 0, output_size * sizeof(float)); + s->m = new DefaultRunModel("../../models/driving_model.dlc", s->output, output_size); +#ifdef TEMPORAL + assert(temporal); + s->m->addRecurrent(&s->output[OUTPUT_SIZE], TEMPORAL_SIZE); +#endif + + // Build Vandermonde matrix + for(int i = 0; i < MODEL_PATH_DISTANCE; i++) { + for(int j = 0; j < POLYFIT_DEGREE; j++) { + vander(i, j) = pow(i, POLYFIT_DEGREE-j-1); + } + } +} + +ModelData model_eval_frame(ModelState* s, cl_command_queue q, + cl_mem yuv_cl, int width, int height, + mat3 transform, void* sock) { + struct { + float *path; + float *left_lane; + float *right_lane; + float *lead; + } net_outputs = {NULL}; + + //for (int i = 0; i < OUTPUT_SIZE + TEMPORAL_SIZE; i++) { printf("%f ", s->output[i]); } printf("\n"); + + float *net_input_buf = model_input_prepare(&s->in, q, yuv_cl, width, height, transform); + + //printf("readinggggg \n"); + //FILE *f = fopen("goof_frame", "r"); + //fread(net_input_buf, sizeof(float), MODEL_HEIGHT*MODEL_WIDTH*3/2, f); + //fclose(f); + //sleep(1); + //printf("done \n"); + s->m->execute(net_input_buf); + + // net outputs + net_outputs.path = &s->output[0]; + net_outputs.left_lane = &s->output[MODEL_PATH_DISTANCE*2]; + net_outputs.right_lane = &s->output[MODEL_PATH_DISTANCE*2 + MODEL_PATH_DISTANCE*2 + 1]; + net_outputs.lead = &s->output[MODEL_PATH_DISTANCE*2 + (MODEL_PATH_DISTANCE*2 + 1)*2]; + + ModelData model = {0}; + + for (int i=0; i net_outputs.lead[mdn_max_idx*5 + 4]) { + mdn_max_idx = i; + } + } + model.lead.prob = sigmoid(net_outputs.lead[LEAD_MDN_N*5]); + model.lead.dist = net_outputs.lead[mdn_max_idx*5] * max_dist; + model.lead.std = softplus(net_outputs.lead[mdn_max_idx*5 + 2]) * max_dist; + model.lead.rel_v = net_outputs.lead[mdn_max_idx*5 + 1] * max_rel_vel; + model.lead.rel_v_std = softplus(net_outputs.lead[mdn_max_idx*5 + 3]) * max_rel_vel; + return model; +} + +void model_free(ModelState* s) { + free(s->output); + model_input_free(&s->in); + delete s->m; +} + +void poly_fit(float *in_pts, float *in_stds, float *out) { + // References to inputs + Eigen::Map > pts(in_pts, MODEL_PATH_DISTANCE); + Eigen::Map > std(in_stds, MODEL_PATH_DISTANCE); + Eigen::Map > p(out, POLYFIT_DEGREE); + + // Build Least Squares equations + Eigen::Matrix lhs = vander.array().colwise() / std.array(); + Eigen::Matrix rhs = pts.array() / std.array(); + + // Solve inplace + Eigen::ColPivHouseholderQR > qr(lhs); + p = qr.solve(rhs); +} diff --git a/selfdrive/visiond/model.h b/selfdrive/visiond/models/driving.h similarity index 82% rename from selfdrive/visiond/model.h rename to selfdrive/visiond/models/driving.h index 06a65f8539..2afb205217 100644 --- a/selfdrive/visiond/model.h +++ b/selfdrive/visiond/models/driving.h @@ -2,19 +2,19 @@ #define MODEL_H // gate this here -//#define BIGMODEL +#define MEDMODEL #define TEMPORAL #include "common/mat.h" #include "common/modeldata.h" #include "commonmodel.h" -#include "snpemodel.h" +#include "runners/run.h" typedef struct ModelState { ModelInput in; float *output; - SNPEModel *m; + RunModel *m; } ModelState; void model_init(ModelState* s, cl_device_id device_id, @@ -23,5 +23,6 @@ ModelData model_eval_frame(ModelState* s, cl_command_queue q, cl_mem yuv_cl, int width, int height, mat3 transform, void* sock); void model_free(ModelState* s); +void poly_fit(float *in_pts, float *in_stds, float *out); #endif diff --git a/selfdrive/visiond/monitoring.cc b/selfdrive/visiond/models/monitoring.cc similarity index 80% rename from selfdrive/visiond/monitoring.cc rename to selfdrive/visiond/models/monitoring.cc index 921473108c..7b151d0c41 100644 --- a/selfdrive/visiond/monitoring.cc +++ b/selfdrive/visiond/models/monitoring.cc @@ -1,16 +1,13 @@ +#include #include "monitoring.h" #include "common/mat.h" #define MODEL_WIDTH 320 #define MODEL_HEIGHT 160 -extern const uint8_t monitoring_model_data[] asm("_binary_monitoring_model_dlc_start"); -extern const uint8_t monitoring_model_end[] asm("_binary_monitoring_model_dlc_end"); -const size_t monitoring_model_size = monitoring_model_end - monitoring_model_data; - void monitoring_init(MonitoringState* s, cl_device_id device_id, cl_context context) { model_input_init(&s->in, MODEL_WIDTH, MODEL_HEIGHT, device_id, context); - s->m = new SNPEModel(monitoring_model_data, monitoring_model_size, (float*)&s->output, OUTPUT_SIZE); + s->m = new SNPEModel("../../models/monitoring_model.dlc", (float*)&s->output, OUTPUT_SIZE); } MonitoringResult monitoring_eval_frame(MonitoringState* s, cl_command_queue q, diff --git a/selfdrive/visiond/monitoring.h b/selfdrive/visiond/models/monitoring.h similarity index 93% rename from selfdrive/visiond/monitoring.h rename to selfdrive/visiond/models/monitoring.h index 1e9e25018e..f9f4516bd8 100644 --- a/selfdrive/visiond/monitoring.h +++ b/selfdrive/visiond/models/monitoring.h @@ -2,7 +2,7 @@ #define MONITORING_H #include "commonmodel.h" -#include "snpemodel.h" +#include "runners/run.h" #ifdef __cplusplus extern "C" { @@ -17,7 +17,7 @@ typedef struct MonitoringResult { typedef struct MonitoringState { ModelInput in; - SNPEModel *m; + RunModel *m; float output[OUTPUT_SIZE]; } MonitoringState; diff --git a/selfdrive/visiond/models/posenet.cc b/selfdrive/visiond/models/posenet.cc new file mode 100644 index 0000000000..d1c8d80544 --- /dev/null +++ b/selfdrive/visiond/models/posenet.cc @@ -0,0 +1,58 @@ +#include +#include +#include "posenet.h" + +void posenet_init(PosenetState *s) { + s->input = (float*)malloc(2*200*532*sizeof(float)); + s->m = new DefaultRunModel("../../models/posenet.dlc", s->output, sizeof(s->output)/sizeof(float)); +} + +void posenet_push(PosenetState *s, uint8_t *yuv_ptr_y, int yuv_width) { + // move second frame to first frame + memmove(&s->input[0], &s->input[1], sizeof(float)*(200*532*2 - 1)); + + // fill posenet input + float a; + // posenet uses a half resolution cropped frame + // with upper left corner: [50, 237] and + // bottom right corner: [1114, 637] + // So the resulting crop is 532 X 200 + for (int y=237; y<637; y+=2) { + int yy = (y-237)/2; + for (int x = 50; x < 1114; x+=2) { + int xx = (x-50)/2; + a = 0; + a += yuv_ptr_y[yuv_width*(y+0) + (x+1)]; + a += yuv_ptr_y[yuv_width*(y+1) + (x+1)]; + a += yuv_ptr_y[yuv_width*(y+0) + (x+0)]; + a += yuv_ptr_y[yuv_width*(y+1) + (x+0)]; + // The posenet takes a normalized image input + // like the driving model so [0,255] is remapped + // to [-1,1] + s->input[(yy*532+xx)*2 + 1] = (a/512.0 - 1.0); + } + } +} + +void posenet_eval(PosenetState *s) { + s->m->execute(s->input); + + // fix stddevs + for (int i = 6; i < 12; i++) { + s->output[i] = log1p(exp(s->output[i])) + 1e-6; + } + // to radians + for (int i = 3; i < 6; i++) { + s->output[i] = M_PI * s->output[i] / 180.0; + } + // to radians + for (int i = 9; i < 12; i++) { + s->output[i] = M_PI * s->output[i] / 180.0; + } +} + +void posenet_free(PosenetState *s) { + delete s->m; + free(s->input); +} + diff --git a/selfdrive/visiond/models/posenet.h b/selfdrive/visiond/models/posenet.h new file mode 100644 index 0000000000..2e6571a1d4 --- /dev/null +++ b/selfdrive/visiond/models/posenet.h @@ -0,0 +1,27 @@ +#ifndef POSENET_H +#define POSENET_H + +#include +#include "runners/run.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct PosenetState { + float output[12]; + float *input; + RunModel *m; +} PosenetState; + +void posenet_init(PosenetState *s); +void posenet_push(PosenetState *s, uint8_t *yuv_ptr_y, int yuv_width); +void posenet_eval(PosenetState *s); +void posenet_free(PosenetState *s); + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/selfdrive/visiond/runners/run.h b/selfdrive/visiond/runners/run.h new file mode 100644 index 0000000000..d92519daf1 --- /dev/null +++ b/selfdrive/visiond/runners/run.h @@ -0,0 +1,14 @@ +#ifndef RUN_H +#define RUN_H + +#include "runmodel.h" +#include "snpemodel.h" + +#ifdef QCOM + #define DefaultRunModel SNPEModel +#else + #include "tfmodel.h" + #define DefaultRunModel TFModel +#endif + +#endif diff --git a/selfdrive/visiond/runners/runmodel.h b/selfdrive/visiond/runners/runmodel.h new file mode 100644 index 0000000000..245f4c8df2 --- /dev/null +++ b/selfdrive/visiond/runners/runmodel.h @@ -0,0 +1,11 @@ +#ifndef RUNMODEL_H +#define RUNMODEL_H + +class RunModel { +public: + virtual void addRecurrent(float *state, int state_size) {} + virtual void execute(float *net_input_buf) {} +}; + +#endif + diff --git a/selfdrive/visiond/snpemodel.cc b/selfdrive/visiond/runners/snpemodel.cc similarity index 87% rename from selfdrive/visiond/snpemodel.cc rename to selfdrive/visiond/runners/snpemodel.cc index ae7b7f10a1..15b3bcc317 100644 --- a/selfdrive/visiond/snpemodel.cc +++ b/selfdrive/visiond/runners/snpemodel.cc @@ -1,3 +1,6 @@ +#include +#include +#include "common/util.h" #include "snpemodel.h" void PrintErrorStringAndExit() { @@ -6,22 +9,34 @@ void PrintErrorStringAndExit() { std::exit(EXIT_FAILURE); } -SNPEModel::SNPEModel(const uint8_t *model_data, const size_t model_size, float *output, size_t output_size) { +SNPEModel::SNPEModel(const char *path, float *output, size_t output_size) { +#ifdef QCOM assert(zdl::SNPE::SNPEFactory::isRuntimeAvailable(zdl::DlSystem::Runtime_t::GPU)); +#endif + size_t model_size; + model_data = (uint8_t *)read_file(path, &model_size); + assert(model_data); // load model std::unique_ptr container = zdl::DlContainer::IDlContainer::open(model_data, model_size); if (!container) { PrintErrorStringAndExit(); } - printf("loaded model with size: %d\n", model_size); + printf("loaded model with size: %u\n", model_size); // create model runner zdl::SNPE::SNPEBuilder snpeBuilder(container.get()); while (!snpe) { +#ifdef QCOM snpe = snpeBuilder.setOutputLayers({}) .setRuntimeProcessor(zdl::DlSystem::Runtime_t::GPU) .setUseUserSuppliedBuffers(true) .setPerformanceProfile(zdl::DlSystem::PerformanceProfile_t::HIGH_PERFORMANCE) .build(); +#else + snpe = snpeBuilder.setOutputLayers({}) + .setUseUserSuppliedBuffers(true) + .setPerformanceProfile(zdl::DlSystem::PerformanceProfile_t::HIGH_PERFORMANCE) + .build(); +#endif if (!snpe) std::cerr << zdl::DlSystem::getLastErrorString() << std::endl; } diff --git a/selfdrive/visiond/snpemodel.h b/selfdrive/visiond/runners/snpemodel.h similarity index 80% rename from selfdrive/visiond/snpemodel.h rename to selfdrive/visiond/runners/snpemodel.h index a7fc6083db..0a6e030f47 100644 --- a/selfdrive/visiond/snpemodel.h +++ b/selfdrive/visiond/runners/snpemodel.h @@ -11,12 +11,19 @@ #include #include -class SNPEModel { +#include "runmodel.h" + +class SNPEModel : public RunModel { public: - SNPEModel(const uint8_t *model_data, const size_t model_size, float *output, size_t output_size); + SNPEModel(const char *path, float *output, size_t output_size); + ~SNPEModel() { + if (model_data) free(model_data); + } void addRecurrent(float *state, int state_size); void execute(float *net_input_buf); private: + uint8_t *model_data = NULL; + // snpe model stuff std::unique_ptr snpe; diff --git a/selfdrive/visiond/loadyuv.c b/selfdrive/visiond/transforms/loadyuv.c similarity index 96% rename from selfdrive/visiond/loadyuv.c rename to selfdrive/visiond/transforms/loadyuv.c index 2b50fb9d2a..2518145100 100644 --- a/selfdrive/visiond/loadyuv.c +++ b/selfdrive/visiond/transforms/loadyuv.c @@ -17,7 +17,7 @@ void loadyuv_init(LoadYUVState* s, cl_context ctx, cl_device_id device_id, int w "-cl-fast-relaxed-math -cl-denorms-are-zero " "-DTRANSFORMED_WIDTH=%d -DTRANSFORMED_HEIGHT=%d", width, height); - cl_program prg = CLU_LOAD_FROM_FILE(ctx, device_id, "loadyuv.cl", args); + cl_program prg = CLU_LOAD_FROM_FILE(ctx, device_id, "transforms/loadyuv.cl", args); s->loadys_krnl = clCreateKernel(prg, "loadys", &err); assert(err == 0); diff --git a/selfdrive/visiond/loadyuv.cl b/selfdrive/visiond/transforms/loadyuv.cl similarity index 100% rename from selfdrive/visiond/loadyuv.cl rename to selfdrive/visiond/transforms/loadyuv.cl diff --git a/selfdrive/visiond/loadyuv.h b/selfdrive/visiond/transforms/loadyuv.h similarity index 100% rename from selfdrive/visiond/loadyuv.h rename to selfdrive/visiond/transforms/loadyuv.h diff --git a/selfdrive/visiond/rgb_to_yuv.c b/selfdrive/visiond/transforms/rgb_to_yuv.c similarity index 94% rename from selfdrive/visiond/rgb_to_yuv.c rename to selfdrive/visiond/transforms/rgb_to_yuv.c index 0ce3d5a027..2626e6eebe 100644 --- a/selfdrive/visiond/rgb_to_yuv.c +++ b/selfdrive/visiond/transforms/rgb_to_yuv.c @@ -20,7 +20,7 @@ void rgb_to_yuv_init(RGBToYUVState* s, cl_context ctx, cl_device_id device_id, i #endif "-DWIDTH=%d -DHEIGHT=%d -DUV_WIDTH=%d -DUV_HEIGHT=%d -DRGB_STRIDE=%d -DRGB_SIZE=%d", width, height, width/ 2, height / 2, rgb_stride, width * height); - cl_program prg = CLU_LOAD_FROM_FILE(ctx, device_id, "rgb_to_yuv.cl", args); + cl_program prg = CLU_LOAD_FROM_FILE(ctx, device_id, "transforms/rgb_to_yuv.cl", args); s->rgb_to_yuv_krnl = clCreateKernel(prg, "rgb_to_yuv", &err); assert(err == 0); diff --git a/selfdrive/visiond/rgb_to_yuv.cl b/selfdrive/visiond/transforms/rgb_to_yuv.cl similarity index 100% rename from selfdrive/visiond/rgb_to_yuv.cl rename to selfdrive/visiond/transforms/rgb_to_yuv.cl diff --git a/selfdrive/visiond/rgb_to_yuv.h b/selfdrive/visiond/transforms/rgb_to_yuv.h similarity index 100% rename from selfdrive/visiond/rgb_to_yuv.h rename to selfdrive/visiond/transforms/rgb_to_yuv.h diff --git a/selfdrive/visiond/rgb_to_yuv_test.cc b/selfdrive/visiond/transforms/rgb_to_yuv_test.cc similarity index 100% rename from selfdrive/visiond/rgb_to_yuv_test.cc rename to selfdrive/visiond/transforms/rgb_to_yuv_test.cc diff --git a/selfdrive/visiond/transform.c b/selfdrive/visiond/transforms/transform.c similarity index 99% rename from selfdrive/visiond/transform.c rename to selfdrive/visiond/transforms/transform.c index 5f3d7ad5a1..0b4150ddb2 100644 --- a/selfdrive/visiond/transform.c +++ b/selfdrive/visiond/transforms/transform.c @@ -9,7 +9,7 @@ void transform_init(Transform* s, cl_context ctx, cl_device_id device_id) { int err = 0; memset(s, 0, sizeof(*s)); - cl_program prg = CLU_LOAD_FROM_FILE(ctx, device_id, "transform.cl", ""); + cl_program prg = CLU_LOAD_FROM_FILE(ctx, device_id, "transforms/transform.cl", ""); s->krnl = clCreateKernel(prg, "warpPerspective", &err); assert(err == 0); diff --git a/selfdrive/visiond/transform.cl b/selfdrive/visiond/transforms/transform.cl similarity index 100% rename from selfdrive/visiond/transform.cl rename to selfdrive/visiond/transforms/transform.cl diff --git a/selfdrive/visiond/transform.h b/selfdrive/visiond/transforms/transform.h similarity index 100% rename from selfdrive/visiond/transform.h rename to selfdrive/visiond/transforms/transform.h diff --git a/selfdrive/visiond/visiond.cc b/selfdrive/visiond/visiond.cc index 77a7e5f485..530fd68f91 100644 --- a/selfdrive/visiond/visiond.cc +++ b/selfdrive/visiond/visiond.cc @@ -24,6 +24,7 @@ #include #include #include +#include #include "common/version.h" #include "common/util.h" @@ -39,14 +40,17 @@ #include "bufs.h" #ifdef QCOM -#include "camera_qcom.h" +#include "cameras/camera_qcom.h" #else -#include "camera_fake.h" +#include "cameras/camera_frame_stream.h" #endif -#include "model.h" -#include "monitoring.h" -#include "rgb_to_yuv.h" +// 3 models +#include "models/driving.h" +#include "models/monitoring.h" +#include "models/posenet.h" + +#include "transforms/rgb_to_yuv.h" #include "cereal/gen/cpp/log.capnp.h" @@ -152,6 +156,8 @@ struct VisionState { zsock_t *monitoring_sock; void* monitoring_sock_raw; + PosenetState posenet; + // Protected by transform_lock. bool run_model; mat3 cur_transform; @@ -174,6 +180,9 @@ struct VisionState { zsock_t *posenet_sock; void* posenet_sock_raw; + zsock_t *thumbnail_sock; + void* thumbnail_sock_raw; + pthread_mutex_t clients_lock; VisionClientState clients[MAX_CLIENTS]; @@ -218,7 +227,7 @@ cl_program build_debayer_program(VisionState *s, frame_width, frame_height, frame_stride, rgb_width, rgb_height, rgb_stride, bayer_flip, hdr); - return CLU_LOAD_FROM_FILE(s->context, s->device_id, "debayer.cl", args); + return CLU_LOAD_FROM_FILE(s->context, s->device_id, "cameras/debayer.cl", args); } void cl_init(VisionState *s) { @@ -247,45 +256,6 @@ void cl_free(VisionState *s) { assert(err == 0); } -////////// - -#if 0 -// from libadreno_utils.so -extern "C" void compute_aligned_width_and_height(int width, - int height, - int bpp, - int tile_mode, - int raster_mode, - int padding_threshold, - int *aligned_w, - int *aligned_h); - -// TODO: move to visionbuf -void alloc_rgb888_bufs_cl(cl_device_id device_id, cl_context ctx, - int width, int height, int count, - int *out_stride, size_t *out_size, - VisionBuf *out_bufs, cl_mem *out_cl) { - - int aligned_w = 0, aligned_h = 0; -#ifdef QCOM - compute_aligned_width_and_height(ALIGN(width, 32), ALIGN(height, 32), 3, 0, 0, 512, &aligned_w, &aligned_h); -#else - aligned_w = width; aligned_h = height; -#endif - - int stride = aligned_w * 3; - size_t size = aligned_w * aligned_h * 3; - - for (int i=0; iui_tb, UI_BUF_COUNT, "rgb"); - assert(s->cameras.front.ci.bayer); + //assert(s->cameras.front.ci.bayer); s->rgb_front_width = s->cameras.front.ci.frame_width/2; s->rgb_front_height = s->cameras.front.ci.frame_height/2; @@ -375,36 +345,27 @@ void init_buffers(VisionState *s) { s->yuv_transform = s->cameras.rear.transform; } - // build all the camera debayer programs - for (int i=0; icameras.rear.ci.bayer) { + s->prg_debayer_rear = build_debayer_program(s, s->cameras.rear.ci.frame_width, s->cameras.rear.ci.frame_height, + s->cameras.rear.ci.frame_stride, + s->rgb_width, s->rgb_height, s->rgb_stride, + s->cameras.rear.ci.bayer_flip, s->cameras.rear.ci.hdr); + s->krnl_debayer_rear = clCreateKernel(s->prg_debayer_rear, "debayer10", &err); + assert(err == 0); } - s->prg_debayer_rear = build_debayer_program(s, s->cameras.rear.ci.frame_width, s->cameras.rear.ci.frame_height, - s->cameras.rear.ci.frame_stride, - s->rgb_width, s->rgb_height, s->rgb_stride, - s->cameras.rear.ci.bayer_flip, s->cameras.rear.ci.hdr); + if (s->cameras.front.ci.bayer) { + s->prg_debayer_front = build_debayer_program(s, s->cameras.front.ci.frame_width, s->cameras.front.ci.frame_height, + s->cameras.front.ci.frame_stride, + s->rgb_front_width, s->rgb_front_height, s->rgb_front_stride, + s->cameras.front.ci.bayer_flip, s->cameras.front.ci.hdr); - s->prg_debayer_front = build_debayer_program(s, s->cameras.front.ci.frame_width, s->cameras.front.ci.frame_height, - s->cameras.front.ci.frame_stride, - s->rgb_front_width, s->rgb_front_height, s->rgb_front_stride, - s->cameras.front.ci.bayer_flip, s->cameras.front.ci.hdr); - - s->krnl_debayer_rear = clCreateKernel(s->prg_debayer_rear, "debayer10", &err); - assert(err == 0); - s->krnl_debayer_front = clCreateKernel(s->prg_debayer_front, "debayer10", &err); - assert(err == 0); + s->krnl_debayer_front = clCreateKernel(s->prg_debayer_front, "debayer10", &err); + assert(err == 0); + } rgb_to_yuv_init(&s->rgb_to_yuv_state, s->context, s->device_id, s->yuv_width, s->yuv_height, s->rgb_stride); rgb_to_yuv_init(&s->front_rgb_to_yuv_state, s->context, s->device_id, s->yuv_front_width, s->yuv_front_height, s->rgb_front_stride); - } void free_buffers(VisionState *s) { @@ -755,11 +716,6 @@ void* monitoring_thread(void *arg) { MonitoringResult res = monitoring_eval_frame(&s->monitoring, q, s->yuv_front_cl[buf_idx], s->yuv_front_width, s->yuv_front_height); - // for (int i=0; i<6; i++) { - // printf("%f ", res.vs[i]); - // } - // printf("\n"); - // send driver monitoring packet { capnp::MallocMessageBuilder msg; @@ -899,15 +855,6 @@ void* frontview_thread(void *arg) { return NULL; } -#define POSENET - -#ifdef POSENET -#include "snpemodel.h" -extern const uint8_t posenet_model_data[] asm("_binary_posenet_dlc_start"); -extern const uint8_t posenet_model_end[] asm("_binary_posenet_dlc_end"); -const size_t posenet_model_size = posenet_model_end - posenet_model_data; -#endif - void* processing_thread(void *arg) { int err; VisionState *s = (VisionState*)arg; @@ -938,14 +885,6 @@ void* processing_thread(void *arg) { FILE *dump_rgb_file = fopen("/sdcard/dump.rgb", "wb"); #endif -#ifdef POSENET - int posenet_counter = 0; - float pose_output[12]; - float *posenet_input = (float*)malloc(2*200*532*sizeof(float)); - SNPEModel *posenet = new SNPEModel(posenet_model_data, posenet_model_size, - pose_output, sizeof(pose_output)/sizeof(float)); -#endif - // init the net LOG("processing start!"); @@ -1048,6 +987,7 @@ void* processing_thread(void *arg) { model_publish(model_sock_raw, frame_id, model_transform, s->model_bufs[ui_idx]); } + // send frame event { capnp::MallocMessageBuilder msg; @@ -1066,6 +1006,7 @@ void* processing_thread(void *arg) { framed.setLensErr(frame_data.lens_err); framed.setLensTruePos(frame_data.lens_true_pos); + #ifndef QCOM framed.setImage(kj::arrayPtr((const uint8_t*)s->yuv_ion[yuv_idx].addr, s->yuv_buf_size)); #endif @@ -1073,68 +1014,23 @@ void* processing_thread(void *arg) { kj::ArrayPtr transform_vs(&s->yuv_transform.v[0], 9); framed.setTransform(transform_vs); - auto words = capnp::messageToFlatArray(msg); - auto bytes = words.asBytes(); - zmq_send(s->recorder_sock_raw, bytes.begin(), bytes.size(), ZMQ_DONTWAIT); + if (s->recorder_sock_raw != NULL) { + auto words = capnp::messageToFlatArray(msg); + auto bytes = words.asBytes(); + zmq_send(s->recorder_sock_raw, bytes.begin(), bytes.size(), ZMQ_DONTWAIT); + } } - -#ifdef POSENET + // push the frame to the posenet + // TODO: This doesn't always have to run double pt1 = 0, pt2 = 0, pt3 = 0; pt1 = millis_since_boot(); - - // move second frame to first frame - memmove(&posenet_input[0], &posenet_input[1], sizeof(float)*(200*532*2 - 1)); - - // fill posenet input - float a; - // posenet uses a half resolution cropped frame - // with upper left corner: [50, 237] and - // bottom right corner: [1114, 637] - // So the resulting crop is 532 X 200 - for (int y=237; y<637; y+=2) { - int yy = (y-237)/2; - for (int x = 50; x < 1114; x+=2) { - int xx = (x-50)/2; - a = 0; - a += yuv_ptr_y[s->yuv_width*(y+0) + (x+1)]; - a += yuv_ptr_y[s->yuv_width*(y+1) + (x+1)]; - a += yuv_ptr_y[s->yuv_width*(y+0) + (x+0)]; - a += yuv_ptr_y[s->yuv_width*(y+1) + (x+0)]; - // The posenet takes a normalized image input - // like the driving model so [0,255] is remapped - // to [-1,1] - posenet_input[(yy*532+xx)*2 + 1] = (a/512.0 - 1.0); - } - } - //FILE *fp; - //fp = fopen( "testing" , "r" ); - //fread(posenet_input , sizeof(float) , 200*532*2 , fp); - //fclose(fp); - //sleep(5); - + posenet_push(&s->posenet, yuv_ptr_y, s->yuv_width); pt2 = millis_since_boot(); - posenet_counter++; - - if (posenet_counter % 5 == 0){ - // run posenet - //printf("avg %f\n", pose_output[0]); - posenet->execute(posenet_input); - - - // fix stddevs - for (int i = 6; i < 12; i++) { - pose_output[i] = log1p(exp(pose_output[i])) + 1e-6; - } - // to radians - for (int i = 3; i < 6; i++) { - pose_output[i] = M_PI * pose_output[i] / 180.0; - } - // to radians - for (int i = 9; i < 12; i++) { - pose_output[i] = M_PI * pose_output[i] / 180.0; - } + // posenet runs every 5 + if (cnt % 5 == 0) { + posenet_eval(&s->posenet); // send posenet event { @@ -1143,13 +1039,13 @@ void* processing_thread(void *arg) { event.setLogMonoTime(nanos_since_boot()); auto posenetd = event.initCameraOdometry(); - kj::ArrayPtr trans_vs(&pose_output[0], 3); + kj::ArrayPtr trans_vs(&s->posenet.output[0], 3); posenetd.setTrans(trans_vs); - kj::ArrayPtr rot_vs(&pose_output[3], 3); + kj::ArrayPtr rot_vs(&s->posenet.output[3], 3); posenetd.setRot(rot_vs); - kj::ArrayPtr trans_std_vs(&pose_output[6], 3); + kj::ArrayPtr trans_std_vs(&s->posenet.output[6], 3); posenetd.setTransStd(trans_std_vs); - kj::ArrayPtr rot_std_vs(&pose_output[9], 3); + kj::ArrayPtr rot_std_vs(&s->posenet.output[9], 3); posenetd.setRotStd(rot_std_vs); auto words = capnp::messageToFlatArray(msg); @@ -1157,10 +1053,69 @@ void* processing_thread(void *arg) { zmq_send(s->posenet_sock_raw, bytes.begin(), bytes.size(), ZMQ_DONTWAIT); } pt3 = millis_since_boot(); - //LOGD("pre: %.2fms | posenet: %.2fms", (pt2-pt1), (pt3-pt1)); + LOGD("pre: %.2fms | posenet: %.2fms", (pt2-pt1), (pt3-pt1)); } -#endif + // one thumbnail per 5 seconds (instead of %5 == 0 posenet) + if (cnt % 100 == 3) { + uint8_t* thumbnail_buffer = NULL; + uint64_t thumbnail_len = 0; + + unsigned char *row = (unsigned char *)malloc(s->rgb_width/2*3); + mt1 = millis_since_boot(); + + struct jpeg_compress_struct cinfo; + struct jpeg_error_mgr jerr; + + cinfo.err = jpeg_std_error(&jerr); + jpeg_create_compress(&cinfo); + jpeg_mem_dest(&cinfo, &thumbnail_buffer, &thumbnail_len); + + cinfo.image_width = s->rgb_width / 2; + cinfo.image_height = s->rgb_height / 2; + cinfo.input_components = 3; + cinfo.in_color_space = JCS_RGB; + + jpeg_set_defaults(&cinfo); + jpeg_set_quality(&cinfo, 50, true); + jpeg_start_compress(&cinfo, true); + + JSAMPROW row_pointer[1]; + for (int i = 0; i < s->rgb_height; i+=2) { + for (int j = 0; j < s->rgb_width*3; j+=6) { + for (int k = 0; k < 3; k++) { + uint16_t dat = 0; + dat += bgr_ptr[s->rgb_stride*i + j + k]; + dat += bgr_ptr[s->rgb_stride*i + j+3 + k]; + dat += bgr_ptr[s->rgb_stride*(i+1) + j + k]; + dat += bgr_ptr[s->rgb_stride*(i+1) + j+3 + k]; + row[(j/2) + (2-k)] = dat/4; + } + } + row_pointer[0] = row; + jpeg_write_scanlines(&cinfo, row_pointer, 1); + } + free(row); + jpeg_finish_compress(&cinfo); + + mt2 = millis_since_boot(); + //printf("jpeg produced %lu bytes in %f\n", thumbnail_len, mt2-mt1); + + capnp::MallocMessageBuilder msg; + cereal::Event::Builder event = msg.initRoot(); + event.setLogMonoTime(nanos_since_boot()); + + auto thumbnaild = event.initThumbnail(); + thumbnaild.setFrameId(frame_data.frame_id); + thumbnaild.setTimestampEof(frame_data.timestamp_eof); + thumbnaild.setThumbnail(kj::arrayPtr((const uint8_t*)thumbnail_buffer, thumbnail_len)); + + auto words = capnp::messageToFlatArray(msg); + auto bytes = words.asBytes(); + zmq_send(s->thumbnail_sock_raw, bytes.begin(), bytes.size(), ZMQ_DONTWAIT); + + free(thumbnail_buffer); + } tbuffer_dispatch(&s->ui_tb, ui_idx); @@ -1206,8 +1161,8 @@ void* processing_thread(void *arg) { double t5 = millis_since_boot(); - /*LOGD("queued: %.2fms, yuv: %.2f, model: %.2fms | processing: %.3fms", - (t2-t1), (yt2-yt1), (mt2-mt1), (t5-t1));*/ + LOGD("queued: %.2fms, yuv: %.2f, model: %.2fms | processing: %.3fms", + (t2-t1), (yt2-yt1), (mt2-mt1), (t5-t1)); } #ifdef DUMP_RGB @@ -1258,7 +1213,7 @@ void* live_thread(void *arg) { if (event.isLiveCalibration()) { pthread_mutex_lock(&s->transform_lock); -#ifdef BIGMODEL +#ifdef MEDMODEL auto wm2 = event.getLiveCalibration().getWarpMatrixBig(); #else auto wm2 = event.getLiveCalibration().getWarpMatrix2(); @@ -1304,11 +1259,12 @@ void party(VisionState *s, bool nomodel) { processing_thread, s); assert(err == 0); - +#ifdef QCOM pthread_t frontview_thread_handle; err = pthread_create(&frontview_thread_handle, NULL, frontview_thread, s); assert(err == 0); +#endif pthread_t monitoring_thread_handle; err = pthread_create(&monitoring_thread_handle, NULL, monitoring_thread, s); @@ -1332,9 +1288,11 @@ void party(VisionState *s, bool nomodel) { zsock_signal(s->terminate_pub, 0); +#ifdef QCOM LOG("joining frontview_thread"); err = pthread_join(frontview_thread_handle, NULL); assert(err == 0); +#endif #ifndef __APPLE__ LOG("joining visionserver_thread"); @@ -1355,9 +1313,6 @@ void party(VisionState *s, bool nomodel) { } -// TODO: make a version of visiond that runs on pc using streamed video from EON. -// BOUNTY: free EON+panda+giraffe - int main(int argc, char **argv) { int err; @@ -1388,6 +1343,7 @@ int main(int argc, char **argv) { model_init(&s->model, s->device_id, s->context, true); monitoring_init(&s->monitoring, s->device_id, s->context); + posenet_init(&s->posenet); // s->zctx = zctx_shadow_zmq_ctx(zsys_init()); @@ -1404,9 +1360,11 @@ int main(int argc, char **argv) { init_buffers(s); - s->recorder_sock = zsock_new_pub("@tcp://*:8002"); - assert(s->recorder_sock); - s->recorder_sock_raw = zsock_resolve(s->recorder_sock); + #ifdef QCOM + s->recorder_sock = zsock_new_pub("@tcp://*:8002"); + assert(s->recorder_sock); + s->recorder_sock_raw = zsock_resolve(s->recorder_sock); + #endif s->monitoring_sock = zsock_new_pub("@tcp://*:8063"); assert(s->monitoring_sock); @@ -1416,6 +1374,10 @@ int main(int argc, char **argv) { assert(s->posenet_sock); s->posenet_sock_raw = zsock_resolve(s->posenet_sock); + s->thumbnail_sock = zsock_new_pub("@tcp://*:8069"); + assert(s->thumbnail_sock); + s->thumbnail_sock_raw = zsock_resolve(s->thumbnail_sock); + cameras_open(&s->cameras, &s->camera_bufs[0], &s->focus_bufs[0], &s->stats_bufs[0], &s->front_camera_bufs[0]); if (test_run) { @@ -1425,6 +1387,8 @@ int main(int argc, char **argv) { zsock_destroy(&s->recorder_sock); zsock_destroy(&s->monitoring_sock); + zsock_destroy(&s->posenet_sock); + zsock_destroy(&s->thumbnail_sock); // zctx_destroy(&s->zctx); model_free(&s->model);